Loading in 5 sec....

Building Abstractions with Data (Part 2)PowerPoint Presentation

Building Abstractions with Data (Part 2)

- By
**emele** - Follow User

- 133 Views
- Uploaded on

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

**An Image/Link below is provided (as is) to download presentation**

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

Last Time…

- Building abstractions for data, analogous to abstractions for procedures
- The idea of types
- Algorithm-centered perspective
- Algorithms are active
- Algorithms manipulate data

Today…

- More layers of abstraction
- A deeper discussion about data types
- Data-centeredperspective
- Data are active
- Data use algorithms

Outline

- Hierarchies of Abstraction
- Data Types and Data Structures
- From Procedural to OOP

Compound Data Types Can Be Made of Compound Data Types

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

Example

class Point {

intx, y;

}

class Circle {

Point center;

intradius;

}

classLineSegment {

Point firstEndPoint, secondEndPoint;

}

What Allows Hierarchies of Abstraction?

- 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

What Allows Hierarchies of Abstraction?

- 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

What Allows Hierarchies of Abstraction?

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

Practice Programming Problem: Facebook Profile

- 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
- E-mail Address
- Hometown
- Location

Outline

- Hierarchies of Abstraction
- Data Types and Data Structures
- From Procedural to OOP

What is a Data Type?

- 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).

What is a 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 Data Has to Obey Certain Properties

- 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

The Data Has to Obey Certain Properties

- 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

The Data Structure Implements the Data Type

- 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.

The Data Structure Implements 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.

A Piece of Data is an Instance of a Type

- 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.

Magic Analogies

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.

Magic Analogies

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.

Magic Analogies

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.

Magic Analogies

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.

Does This Definition Apply to Primitive Types As Well?

- 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.

Literals

- 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.

Literals

- Variables: The name is not the variable is not the value.
- Literals: The name is the literal is the value.

Constants

- 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;

- // inside a procedure

Quick Practice Programming Problem: PI

- Create a procedure that computes the area of a circle given its radius.
- Declare as a constant.

Outline

- Hierarchies of Abstraction
- Data Types and Data Structures
- From Procedural to OOP

Bigger Systems Need More Modularity

- 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

- Example in games
- javapjava.lang.Mathto see how it’s designed

Fractions: Module Version

public class Fraction

{

intnumerator;

intdenominator;

static Fraction makeFraction(intnum, intdenom) {

Fraction f = newFraction();

f.numerator = num;

f.denominator = denom;

return f;

}

Fractions: Module Version

static intnum(Fraction x) {

returnx.numerator;

}

static intdenom(Fraction x) {

returnx.denominator;

}

}

Fractions: Module Version

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)

}

Fractions: Module Version

publicclass Printing {

staticvoid print(Fraction x) {

print(Fraction.num(x));

print("/");

print(Fraction.denom(x));

}

// other operations for printing

// static ComplexNum print(ComplexNum x)

}

Fractions: Module Version

publicclassProgramThatUsesFraction{

publicstaticvoid main(String args[]) {

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

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

Fraction sum = Arithmetic.add(x, y);

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

The Procedural View

- 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.

The Object-Oriented View

- 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.

A Change in Vocabulary

Procedural

Object-Oriented

Method invocation

Accessor method

- Procedure call
- Selector

Fractions: OOP Version

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

Fractions: OOP Version

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.

Fractions: OOP Version (Continued)

public void print() {

print(this.num());

print("/");

print(this.denom());

}

publicFraction add(Fraction x) {

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.

Fractions: OOP Version (Continued)

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!

Using OOP Fractions

publicstaticvoid main(String args[])

{

Fraction x = new Fraction(3, 2);

Fraction y = new Fraction(1, 5);

Fraction sum = x.add(y);

}

Several Differences

- 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.

More Important Differences

- Added public
- 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.

Static versus Non-static

- 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

Static versus Non-static

- 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.

More Important Differences

- 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.

Most Important Differences

- 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.

Most Important Differences

- 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

Practice Programming Problem: OOP Facebook

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

By The Way

- 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.

Will This Work?

public class Fraction {

intnumerator, denominator;

public intnum() {

returnthis.numerator;

}

// constructor and other methods here

}

Will This Work?

public class Fraction {

intnumerator, denominator;

public intnum() {

returnnumerator;

}

// constructor and other methods here

}

Will This Work?

public class Fraction {

intnumerator, denominator;

public intnum() {

returnthis.num;

}

// constructor and other methods here

}

Will This Work?

public class Fraction {

intnumerator, denominator;

public intnum() {

returnthis.denominator;

}

// constructor and other methods here

}

Will This Work?

public class Fraction {

intnumerator, denominator;

public intnum() {

intnumerator = 0;

returnnumerator;

}

// constructor and other methods here

}

Will This Work?

public class Fraction {

intnumerator, denominator;

public intnum() {

intnumerator = 0;

returnnumerator;

}

// constructor and other methods here

}

This phenomenon is called shadowing.

Will This Work?

public class Fraction {

intnumerator, denominator;

public intnum() {

intnumerator = 0;

returnthis.numerator;

}

// constructor and other methods here

}

Will This Work?

public class Fraction {

intnumerator, denominator;

public intignoreParamReturnNum(int numerator) {

return numerator;

}

// constructor and other methods here

}

Will This Work?

public class Fraction {

intnumerator, denominator;

public intignoreParamReturnNum(int numerator) {

returnthis.numerator;

}

// constructor and other methods here

}

Will This Work?

public class Fraction {

intnumerator, denominator;

public intignoreParamReturnNum(int numerator) {

intnumerator = 0;

returnthis.numerator;

}

// constructor and other methods here

}

Will This Work?

publicstaticvoid main(String args[])

{

Fraction x = newFraction(3);

Fraction y = new Fraction(1, 5);

Fraction sum = x.add(y);

}

Will This Work?

publicstaticvoid main(String args[])

{

Fraction x = newFraction();

Fraction y = new Fraction(1, 5);

Fraction sum = x.add(y);

}

Will This Work?

publicstaticvoid main(String args[])

{

Fraction x = newFraction();

Fraction y = new Fraction(1, 5);

Fraction sum = x.add(y);

}

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

Will This Work?

publicstaticvoid main(String args[])

{

Fraction x = new Traction(3, 2);

Fraction y = new Fraction(1, 5);

Fraction sum = x.add(y);

}

Will This Work?

publicstaticvoid main(String args[])

{

Traction x = new Traction(3, 2);

Fraction y = new Fraction(1, 5);

Fraction sum = x.add(y);

}

Will This Work?

publicstaticvoid main(String args[])

{

Fraction x = newFraction(3, 2);

Fraction y = new Fraction(1, 5);

Fraction sum = x.add("YOLO");

}

Will This Work?

publicstaticvoid main(String args[])

{

Fraction x;

Fraction y = new Fraction(1, 5);

Fraction sum = x.add(y);

}

Will This Work?

publicstaticvoid main(String args[])

{

Fraction x;

Fraction y = new Fraction(1, 5);

Fraction sum = x.add(y);

}

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

Will This Work?

publicstaticvoid main(String args[])

{

Fraction x = new Fraction(3, 2);

Fraction y;

Fraction sum = x.add(y);

}

Will This Work?

publicstaticvoid main(String args[])

{

Fraction x = new Fraction(3, 2);

Fraction y;

Fraction sum = x.add(y);

}

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

Three Uses of a Java Class

- 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)

Three Uses of a Java Class

- Complete objects
- Class contains instance fields and non-static (instance) methods

Practice Programming Problem: OOP Fractions

- 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.

Practice Programming Problem: OOP Fractions

- 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.

Summary

- 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.

Summary

- 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.

Summary

- Two ways to get more modularity:
- Group procedures into modules.
- Data Abstraction + Procedural Abstraction = OOP.
- state + behavior = objects

Summary

- OOP is about coupling data and procedures.
- OOP is about coupling state and behavior.
- OOP is about changing state.

Next Time…

- 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

Download Presentation

Connecting to Server..