1 / 90

# Building Abstractions with Data (Part 2) - PowerPoint PPT Presentation

Building Abstractions with Data (Part 2). CS 21a: Introduction to Computing I First Semester, 2013-2014. Last Time…. Building abstractions for data, analogous to abstractions for procedures The idea of types Algorithm- centered perspective Algorithms are active

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

## PowerPoint Slideshow about 'Building Abstractions with Data (Part 2)' - emele

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

### Building Abstractions with Data (Part 2)

CS 21a: Introduction to Computing I

First Semester, 2013-2014

• Building abstractions for data, analogous to abstractions for procedures

• The idea of types

• Algorithm-centered perspective

• Algorithms are active

• Algorithms manipulate data

• More layers of abstraction

• A deeper discussion about data types

• Data-centeredperspective

• Data are active

• Data use algorithms

• Hierarchies of Abstraction

• Data Types and Data Structures

• From Procedural to OOP

• This should come as no surprise, given that we want to apply the same principles of abstraction to both algorithms and data.

class Point {

intx, y;

}

class Circle {

Point center;

}

classLineSegment {

Point firstEndPoint, secondEndPoint;

}

classStickFigure {

LineSegmentleftArm,

rightArm,

body,

leftLeg,

rightLeg;

}

• The means of combination has the closure property (mathematics).

• Recall: A set is closed under an operation if performing the operation on members of the set produces a member of the same set.

• Example: integer + integer = integer

• If our set is a set of combinations (including primitives) and the operator is a combination operator, we have the following:

• Expression op expression = expression

• Procedure combine procedure = procedure

• Data structure combine data structure = data structure

• Notice the intimate relationship between hierarchies, trees, recursion, and the closure property.

• Define all the data types needed, along with the constructors and selectors, to implement a Facebook profile with the following information:

• Id

• Name

• Birthday and Age

• Phone Number

• Hometown

• Location

• Hierarchies of Abstraction

• Data Types and Data Structures

• From Procedural to OOP

• A set of possible values

• Constructors are the means for building the whole (data of compound data type) out of the parts (data of simpler data types).

• Selectors are the means for taking the parts (data of simpler data types) from the whole (data of compound data type).

• A data type is a set of values and the expression of the need for constructors and selectors for breaking down those values in terms of simpler data types.

• The value of f is a Fractioniff…

• The value of f is the result of makeFraction(a, b) implies num(f)is a and denom(f) is b, for some integers a and b

• Not just any variable can be meaningfully passed to numor denom

• Not just any definition of makeFraction, num, and denomwill produce data that obeys this property

• A data structure is a implementation of a data type.

• A correct data structure for a data type has the correct definitions of the constructors and selectors to ensure that the data obeys rules imposed by the data type.

• A data structure includes a complete description of how a data type is composed of simpler data types:

• The types and (internally) the names of its parts.

• Constructors: How the whole is made from the parts.

• Selectors: How the parts are obtained from the whole.

• The set is not the member of the set.

• 1 is an int, but 1 is not int.

• The data type is the blueprint, or idea, that all its instances must follow.

• A piece of data is an instance of a data type.

Note: it’s sometimes convenient to use the term “data type” to refer to both the abstract data type (which embodies the required properties without caring about the implementation) and any single concrete data structure that correctly implements the abstract data type.

Problems

Data Types

A data type is a set of values and the expression of the need for procedures (constructors and selectors) for relating those values to simpler data types.

• A problem is a set of input-output pairs and the expression of the need for procedures for relating those input-output pairs to simpler problems.

Algorithms

Data Structures

Data structures implement data types.

There are many data structures that correctly implement one data type.

Choice depends on application.

• Algorithms solve problems.

• There are many algorithms that correctly solve one problem.

• Choice depends on application.

Computations

Data

Two independent pieces of data created from the same data structure may yield different values, even if they arise out of the same data structure.

• Two independent simulations of the same algorithm may yield different behaviors, even if they arise out of the same algorithm.

Computations

Data

Two different data structures that implement the same data type can yield two pieces of data that look different, but given the same procedure applications will produce the same behavior.

• Two different algorithms that solve the same problem can yield two computations that look different, but given the same question will produce the same answers.

• Primitive data (and Strings) can be instantiated from a primitive data type (and the String type) using a literal.

• Constructor: assigning a literal to a variable.

• The value of a variable containing primitive data can be obtained by directly looking up the associated literal.

• Selector: directly evaluating a variable.

• Variables are symbols that refer to other symbols. A variable needs to be evaluated against an environment to know its value.

• A literal, as opposed to a variable, is a symbol which refers to itself. Its value is itself.

• Examples: 5, 3.14, "Hello", true, false.

• Variables: The name is not the variable is not the value.

• Literals: The name is the literal is the value.

• Some literals get used often enough that they can be given a name.

• Can be declared outside procedures so that they can be used in all of them

• Examples:

• // inside a procedure

finalintPI = 3.14159265359;

• // outside a procedure

staticintDIME_VALUE = 0.10;

• Create a procedure that computes the area of a circle given its radius.

• Declare as a constant.

• Hierarchies of Abstraction

• Data Types and Data Structures

• From Procedural to OOP

• I have tons of procedures in one file, now what?

• Can happen in even larger systems

• Ok, I’ve built barriers of abstraction with procedures to help me maintain the complexity, but…

• Loading a 1MB file in my IDE just to edit a small part of the system? No, thanks.

Algorithm-Centered Solution

• Group all related functionality in modules:

• Example in games

• All physics in one module

• All A.I. in one module

• All constants in one module

• All graphics in one module

• javapjava.lang.Mathto see how it’s designed

public class Fraction

{

intnumerator;

intdenominator;

static Fraction makeFraction(intnum, intdenom) {

Fraction f = newFraction();

f.numerator = num;

f.denominator = denom;

return f;

}

static intnum(Fraction x) {

returnx.numerator;

}

static intdenom(Fraction x) {

returnx.denominator;

}

}

publicclass Arithmetic {

staticFraction add(Fraction a, Fraction b) {

intnum = Fraction.num(a) * Fraction.denom(b) +

Fraction.num(b) * Fraction.denom(a);

intdenom = Fraction.denom(a) * Fraction.denom(b);

returnFraction.makeFraction(num, denom);

}

// other operations for arithmetic

// static ComplexNum add(ComplexNum a, ComplexNum b)

}

publicclass Printing {

staticvoid print(Fraction x) {

print(Fraction.num(x));

print("/");

print(Fraction.denom(x));

}

// other operations for printing

// static ComplexNum print(ComplexNum x)

}

publicclassProgramThatUsesFraction{

publicstaticvoid main(String args[]) {

Fraction x = Fraction.makeFraction(3, 2);

Fraction y = Fraction.makeFraction(1, 5);

Printing.print(sum); }

}

Data-Centered Solution

• Group everything that has to do with a data type in one class.

• A class is a blueprint for all objects of a given type, which includes all the procedures that can operate on the given type.

An Algorithm-Centered View of Data Types

• Data types are sets of possible values.

• Data types are specified for operations.

• Operations can only take values of certain types as operands.

• Operations only return values of certain types.

A Data-Centered View of Data Types

• Data types are sets of possible values.

• Operations are specified for data types.

• Only certain operations can be performed on the values of a type.

• Only certain operations can produce values of a (possibly different) data type.

Procedural is Algorithm-Centered, OOP is Data-Centered

• The main idea of OOP:

• Give data behavior

• Couple relevant operations on the data type with the data type definition

• Let data be active, instead of passive arguments to procedures

• Statements: Do actions on things.

• Expressions: Combine things to create other things.

• Constructors: There are special actions to create things.

• Selectors: There are special actions to break things apart.

• Statements: Things perform actions.

• Expressions: Things interact with other things to produce other things.

• Constructors: Beginning with an initial state is one of the special actions a thing can perform.

• Accessors: Things can report about its state with special actions.

• Mutators: Things can change its state with special actions.

The state of an object is its complete description in terms of the values of its components or fields.

Procedural

Object-Oriented

Method invocation

Accessor method

• Procedure call

• Selector

• Suggestion: open the procedural version too to see how the similarities and differences.

public class Fraction {

intnumerator, denominator;

public Fraction(intnum, intdenom) {

this.numerator= num;

this.denominator= denom;

}

public intnum() {

returnthis.numerator;

}

public intdenom() {

returnthis.denominator;

}

Put this in a different file from the one that contains your main method.

public void print() {

print(this.num());

print("/");

print(this.denom());

}

intnum = this.num() * x.denom() +

x.num() * this.denom();

intdenom = this.denom() * x.denom();

return new Fraction(num, denom);

}

Put this in a different file from the one that contains your main method.

publicvoidsetNum(int x) {

numerator = x;

}

publicvoidsetDenom(int x) {

denominator = x;

}

publicvoid reduce() {

intdivisor = ClassWeDefine.gcd(num(), denom());

setNum( num() / divisor );

setDenom( denom() / divisor );

}

}

Now we can reduce Fractions exactly when we need to!

publicstaticvoid main(String args[])

{

Fraction x = new Fraction(3, 2);

Fraction y = new Fraction(1, 5);

}

• Changed syntax for defining a constructor (the name of the procedure and the return type is the same and is just typed-in once).

• Changed syntax for calling a constructor that we defined.

• The call to a “primitive” constructor can be given arguments.

• To make it possible to invoke the constructors, accessors, and mutatorsfrom a different class/file

• Dropped static

• static means the method, field, or inner class belongs to the class, instead of a specific instance.

• static is usually used to use a class as a module for procedures.

• Math.pow is a static procedure.

• ClassName.procedure(arguments);

• Takes input and returns output, usually with no side effects: no changing of state/data associated with objects

• Procedural style

• java YourProgramNamecalls YourProgramName.main

• Fraction’s add is a non-static method.

• instanceVariable.method(arguments);

• Usually deals with the data associated with an object instance

• OO style

• There are other uses of static in OOP, not just for distinguishing OO and Procedural.

• Beyond the scope of this course.

• The object instance is now an implicit argument of the procedure, instead of an explicit one, referred to by the this keyword.

• The dot operator is used to invoke a method on an object instance as well as access a field.

• Operations on Fractions are now part of the Fraction data type definition (data structure)!

• Data and procedures coupled more closely

• Mutator methods: forcefully changing the values of variables.

• OOP encourages you to think of changing state.

• Stateless systems: a name for the input, another name for the output

• State-full systems: one name for the entire “lifetime” of the data

• from the moment of its “birth” at input

• to the moment of its “death” at output

• and all the transformations in between

• Convert the Facebook profile definition into OO-style. Add the necessary mutator methods.

• The thiskeyword can be dropped.

• If we use a variable name that isn’t in the scope of the method (neither a local variable name nor a parameter name), Java assumes you’re referring to an instance field.

• Of course, if there’s no instance field, you get a nasty compile error.

• The scope of the method is nested inside the scope of the class.

public class Fraction {

intnumerator, denominator;

public intnum() {

returnthis.numerator;

}

// constructor and other methods here

}

public class Fraction {

intnumerator, denominator;

public intnum() {

returnnumerator;

}

// constructor and other methods here

}

public class Fraction {

intnumerator, denominator;

public intnum() {

returnthis.num;

}

// constructor and other methods here

}

public class Fraction {

intnumerator, denominator;

public intnum() {

returnthis.denominator;

}

// constructor and other methods here

}

public class Fraction {

intnumerator, denominator;

public intnum() {

intnumerator = 0;

returnnumerator;

}

// constructor and other methods here

}

public class Fraction {

intnumerator, denominator;

public intnum() {

intnumerator = 0;

returnnumerator;

}

// constructor and other methods here

}

public class Fraction {

intnumerator, denominator;

public intnum() {

intnumerator = 0;

returnthis.numerator;

}

// constructor and other methods here

}

public class Fraction {

intnumerator, denominator;

public intignoreParamReturnNum(int numerator) {

return numerator;

}

// constructor and other methods here

}

public class Fraction {

intnumerator, denominator;

public intignoreParamReturnNum(int numerator) {

returnthis.numerator;

}

// constructor and other methods here

}

public class Fraction {

intnumerator, denominator;

public intignoreParamReturnNum(int numerator) {

intnumerator = 0;

returnthis.numerator;

}

// constructor and other methods here

}

publicstaticvoid main(String args[])

{

Fraction x = newFraction(3);

Fraction y = new Fraction(1, 5);

}

publicstaticvoid main(String args[])

{

Fraction x = newFraction();

Fraction y = new Fraction(1, 5);

}

publicstaticvoid main(String args[])

{

Fraction x = newFraction();

Fraction y = new Fraction(1, 5);

}

Default constructor assigns default value (probably not what you want) to fields.

publicstaticvoid main(String args[])

{

Fraction x = new Traction(3, 2);

Fraction y = new Fraction(1, 5);

}

publicstaticvoid main(String args[])

{

Traction x = new Traction(3, 2);

Fraction y = new Fraction(1, 5);

}

publicstaticvoid main(String args[])

{

Fraction x = newFraction(3, 2);

Fraction y = new Fraction(1, 5);

}

publicstaticvoid main(String args[])

{

Fraction x;

Fraction y = new Fraction(1, 5);

}

publicstaticvoid main(String args[])

{

Fraction x;

Fraction y = new Fraction(1, 5);

}

Unassigned object variables are given the special value null: you can’t tell a nothing to do something.

publicstaticvoid main(String args[])

{

Fraction x = new Fraction(3, 2);

Fraction y;

}

publicstaticvoid main(String args[])

{

Fraction x = new Fraction(3, 2);

Fraction y;

}

add will call num and denom on y, but y is null

• Plain old data

• Data type definition

• Class only contains instance fields

• Helper classes

• Group procedures into modules

• Class only contains static methods (and possibly static fields)

• Complete objects

• Class contains instance fields and non-static (instance) methods

• Complete the Fractionclass by including the methods for subtracting, multiplying, dividing, and printing Fractions.

• Also create a MathHelpermodule to contain the gcdprocedure.

• Create a separate class to contain the main procedure, which will use and test the Fraction class.

• Write a program to compute the following. Print each answer on a separate line, with the numerator and denominator separated by a /character. Express the answer in lowest terms.

• Compound data types can be built out of compound data types too.

• Hierarchies can be built when combinations have closure.

• Data structures implement data types.

• Literals are symbols which refer to themselves.

• Constants are named literals.

• One problem, possibly many algorithms

• One data type, possibly many data structures

• The same principles work with algorithms and data.

• Scopes can be nested, but the principles remain the same.

• Two ways to get more modularity:

• Group procedures into modules.

• Data Abstraction + Procedural Abstraction = OOP.

• state + behavior = objects

• OOP is about coupling data and procedures.

• OOP is about coupling state and behavior.

• OOP is about changing state.

• The idea of “changing state,” and what re-assignment does to a program

• The difference between primitive types and Object types in Java

• Another way to think about OOP