+ All Categories
Home > Documents > Building Abstractions with Data (Part 3)

Building Abstractions with Data (Part 3)

Date post: 19-Feb-2016
Category:
Upload: liluye
View: 25 times
Download: 0 times
Share this document with a friend
Description:
Building Abstractions with Data (Part 3). CS 21a: Introduction to Computing I First Semester, 2013-2014. Outline. Assignment and State Pass by Value versus Pass by Sharing Message Passing and Final Remarks on OOP. Two Different Kinds of Systems. Without State. With State. - PowerPoint PPT Presentation
Popular Tags:
88
Building Abstractions with Data (Part 3) CS 21a: Introduction to Computing I First Semester, 2013-2014
Transcript
Page 1: Building Abstractions with Data  (Part 3)

Building Abstractions

with Data (Part 3)

CS 21a: Introduction to Computing I

First Semester, 2013-2014

Page 2: Building Abstractions with Data  (Part 3)

Outline►Assignment and State►Pass by Value versus Pass by Sharing►Message Passing and Final Remarks

on OOP

Page 3: Building Abstractions with Data  (Part 3)

Two Different Kinds of Systems

Without State With State

Page 4: Building Abstractions with Data  (Part 3)

(Re)Assignment Produces State

Without Stateint money = 500;

int moneyAfterDeposit = deposit(money, 1000);

With Stateint money = 500;

money = deposit(money, 1000);

Page 5: Building Abstractions with Data  (Part 3)

(Re)Assignment Produces State

Without Stateint money = 500;

int moneyAfterDeposit = money + 1000;

With Stateint money = 500;

money = money + 1000;

Page 6: Building Abstractions with Data  (Part 3)

(Re)Assignment Produces State

Without Stateint money = 500;

int moneyAfterDeposit = money + 1000;

With Stateint money = 500;

money = money + 1000;

Assignment operator (=) not to be confused with mathematical equals (==).

Page 7: Building Abstractions with Data  (Part 3)

By The Way, Shortcuts!money += 1000; // money = money + 1000;

money++; // money += 1;

money -= 500; // there are also *= and /=

money--; // doesn’t make sense to have ** and //

Page 8: Building Abstractions with Data  (Part 3)

(Re)Assignment Produces State

Without State► Input and output values

have different names► Make a new thing out of

an existing thing

With State► Same name for both

“input” and “output”► Changing an existing

thing

Page 9: Building Abstractions with Data  (Part 3)

(Re)Assignment Produces State

Without State► Variables are names

attached to values► Doesn’t make sense to

change what something means

With State► Variables are boxes

whose contents can be changed

► Makes sense if what a name refers to is a changing, dynamic entity

Page 10: Building Abstractions with Data  (Part 3)

(Re)Assignment Produces State

Without State► Applying the same

operations to the same variables always produces the same results.

► Operation can be understood by plain substitution

int x = 5;

int y = x + 1; // 6

int z = x + 1; // still 6

With State► Operations can produce

side effects (aside from producing output, also changes state)

► Result of operation is dependent on time, history, environment

int x = 5;int y = ++x; // now 6int z = ++x; // now 7

Page 11: Building Abstractions with Data  (Part 3)

Pre-increment versusPost-increment

►See example here►Difference in evaluation…► Is used a lot in older programs► Is useful for some accepted idioms►Should not be abused to make

ambiguous programs►Use these expressions often for side

effects, sparingly for the value

Page 12: Building Abstractions with Data  (Part 3)

Changing Object State By Updating Fields

public class Diet{

int calories;public Diet() {

calories = 0; }public void recordBurgerEaten() {

calories += 400;}

}

Page 13: Building Abstractions with Data  (Part 3)

Changing Object State By Updating Fields

public class Diet{

int calories;public Diet() {

calories = 0; }public void recordBurgerEaten() {

calories += 400;}

}Mutator method

Page 14: Building Abstractions with Data  (Part 3)

Changing Object State By Updating Fields

Diet myDiet = new Diet(); // myDiet has 0 calories

myDiet.recordBurgerEaten();

println(myDiet.calories); // myDiet has 400 calories

myDiet.recordBurgerEaten();

println(myDiet.calories); // myDiet has 800 calories

Page 15: Building Abstractions with Data  (Part 3)

When to Use Mutators?►Only where it makes sense (updating

bank account, calorie count, etc.)►Example where it does not make

sense: Fraction’s add

Page 16: Building Abstractions with Data  (Part 3)

Outline►Assignment and State►Pass by Value versus Pass by

Sharing►Message Passing and Final Remarks

on OOP

Page 17: Building Abstractions with Data  (Part 3)

Two Kinds of Types in Java►Primitives types

► int, double, long, short, byte, float, char, boolean

►A variable holds a valid value►Object types► Java built-ins: String, Scanner►User-defined: Fraction, BankAccount► A variable holds a pointer to an object

Page 18: Building Abstractions with Data  (Part 3)

Primitive Type Variablesversus Object Variables

►Primitive type variables directly contain valuesint x = 5;

►Object variables contain pointers to instancesBankAccount b = new BankAccount();

5x

bbalance

0

Page 19: Building Abstractions with Data  (Part 3)

Primitive Type Variablesand Assignment

int x = 1000;1000

x

Page 20: Building Abstractions with Data  (Part 3)

Primitive Type Variablesand Assignment

int x = 1000;int y = x;

1000x

1000y

Page 21: Building Abstractions with Data  (Part 3)

Primitive Type Variablesand Assignment

int x = 1000;int y = x;

1000x

1000y

Pass by value: y gets a copy of the value of x

Page 22: Building Abstractions with Data  (Part 3)

Primitive Type Variablesand Assignment

int x = 1000;int y = x;

1000x

1000y

Pass by value: y gets a copy of 1000

Page 23: Building Abstractions with Data  (Part 3)

Primitive Type Variablesand Assignment

int x = 1000;int y = x;y = y - 100;println( x );println( y );

1000x

900y

Prints:

1000900

Page 24: Building Abstractions with Data  (Part 3)

Object Variablesand Assignment

BankAccount b = new BankAccount( 1000 );

bbalance

1000

Page 25: Building Abstractions with Data  (Part 3)

Object Variablesand Assignment

BankAccount b = new BankAccount( 1000 );BankAccount c = b;

bbalance

1000c

Page 26: Building Abstractions with Data  (Part 3)

Object Variablesand Assignment

BankAccount b = new BankAccount( 1000 );BankAccount c = b;

bbalance

1000c

Pass by sharing: c gets a copy of the value of b

Page 27: Building Abstractions with Data  (Part 3)

Object Variablesand Assignment

BankAccount b = new BankAccount( 1000 );BankAccount c = b;

bbalance

1000c

Pass by sharing: c gets a copy of a pointer to the bank account. NO NEW OBJECT INSTANCE IS CREATED.

Page 28: Building Abstractions with Data  (Part 3)

Object Variablesand Assignment

BankAccount b = new BankAccount( 1000 );BankAccount c = b;c.withdraw( 100 );println( b.getBalance() );println( c.getBalance() );

bbalance

900c Prints

:900900

Page 29: Building Abstractions with Data  (Part 3)

What’s a Pointer?►It’s really a memory address!►Try this:BankAccount b = new BankAccount( 1000 );println(b);BankAccount c = new BankAccount( 1000 );println(c);println(c == b);c = b;println(c);println(c == b);

Page 30: Building Abstractions with Data  (Part 3)

What’s a Pointer?►It’s really a memory address!►Try this:BankAccount b = new BankAccount( 1000 );println(b);BankAccount c = new BankAccount( 1000 );println(c);println(c == b);c = b;println(c);println(c == b);

Doesn’t matter if the two bank accounts have the same balance. They’re different accounts!

Page 31: Building Abstractions with Data  (Part 3)

What’s a Pointer?►It’s really a memory address!►Try this:BankAccount b = new BankAccount( 1000 );println(b);BankAccount c = new BankAccount( 1000 );println(c);println(c == b);c = b;println(c);println(c == b);

Copies the memory address stored in b to c

Page 32: Building Abstractions with Data  (Part 3)

What’s a Pointer?►It’s really a memory address!►Try this:BankAccount b = new BankAccount( 1000 );println(b);BankAccount c = new BankAccount( 1000 );println(c);println(c == b);c = b;println(c);println(c == b);

c now points to the same object as b does

Page 33: Building Abstractions with Data  (Part 3)

What’s a Pointer?►So when you do…c.withdraw(100);►The balance is changed for the

instance that both b and c share

Page 34: Building Abstractions with Data  (Part 3)

What Happens to the Second Bank Account?

►Garbage collection is a feature of a programming language, where objects that can no longer be accessed are automatically destroyed.

Page 35: Building Abstractions with Data  (Part 3)

Method Calls►A method is invoked on an object

variable but acts on the object that the variable is pointing to

BankAccount b = new BankAccount(1000);

b

balance1000

Page 36: Building Abstractions with Data  (Part 3)

Method Calls►A method is invoked on an object

variable but acts on the object that the variable is pointing to

BankAccount b = new BankAccount(1000);b.deposit( 250 );

b

balance1250deposit(250)

Page 37: Building Abstractions with Data  (Part 3)

The null Pointer►An object variable that doesn’t point

to an actual instance yet has a null pointer (points to nothing)

Page 38: Building Abstractions with Data  (Part 3)

null

Method Calls on null►Calling a method on an object

variable whose value is null results in an error (NullPointerException)

BankAccount b = null;b.deposit( 250 );

b

???deposit(250)

Page 39: Building Abstractions with Data  (Part 3)

An Analogy to Clear That UpJava World Balloon WorldObject variable name HandObject variable value orPointer

String (not the CS kind)

Object instance Balloon

Page 40: Building Abstractions with Data  (Part 3)

An Analogy to Clear That UpJava World Balloon WorldCall to constructor Make a new balloonReturn value from constructor

String that ties the new balloon

Assigning to object variable

Make the hand hold the string

Page 41: Building Abstractions with Data  (Part 3)

An Analogy to Clear That UpJava World Balloon WorldCall to constructor Make a new balloonReturn value from constructor

String that ties the new balloon

Assigning to object variable

Make the hand hold the stringnew BankAccount(500); balance

500

some memory address

Page 42: Building Abstractions with Data  (Part 3)

An Analogy to Clear That UpJava World Balloon WorldCall to constructor Make a new balloonReturn value from constructor

String that ties the new balloon

Assigning to object variable

Make the hand hold the stringBankAccount b = new BankAccount(500); balance

b

500

Page 43: Building Abstractions with Data  (Part 3)

An Analogy to Clear That UpJava World Balloon WorldUsing the dot operatorCalling a methodAccessing a field

Getting the balloon attached to the string and operating on it

b.deposit(500);

Three parts:1. What’s b?2. What’s the pointer pointing to?3. Apply operation to object

balance

b

500

Page 44: Building Abstractions with Data  (Part 3)

An Analogy to Clear That UpJava World Balloon WorldUsing the dot operatorCalling a methodAccessing a field

Getting the balloon attached to the string and operating on it

b.deposit(500);

Three parts:1. What’s b?2. What’s the pointer pointing to?3. Apply operation to object

balance

b

500

Page 45: Building Abstractions with Data  (Part 3)

An Analogy to Clear That UpJava World Balloon WorldUsing the dot operatorCalling a methodAccessing a field

Getting the balloon attached to the string and operating on it

b.deposit(500);

Three parts:1. What’s b?2. What’s the pointer pointing to?3. Apply operation to object

balance

b

500

Page 46: Building Abstractions with Data  (Part 3)

An Analogy to Clear That UpJava World Balloon WorldUsing the dot operatorCalling a methodAccessing a field

Getting the balloon attached to the string and operating on it

b.deposit(500);

Three parts:1. What’s b?2. What’s the pointer pointing to?3. Apply operation to object

balance

b

1000

Page 47: Building Abstractions with Data  (Part 3)

An Analogy to Clear That UpJava World Balloon WorldPass by sharing Share the balloon by

attaching a new string (a copy of the old string) and making the new hand hold the new string balance

b

1000

c

BankAccount c = b;

Page 48: Building Abstractions with Data  (Part 3)

An Analogy to Clear That UpJava World Balloon WorldPass by sharing Share the balloon by

attaching a new string (a copy of the old string) and making the new hand hold the new string balance

b

1500

c

c.deposit(500);

Page 49: Building Abstractions with Data  (Part 3)

An Analogy to Clear That UpJava World Balloon WorldNull Pointer String with no balloon

balance

b

1500

c

c = null;// c.deposit(500); -> NullPointerException

Page 50: Building Abstractions with Data  (Part 3)

An Analogy to Clear That UpJava World Balloon WorldUnassigned variable (doesn’t even matter if Object or primitive)

Hand holding nothing

balance

b

1500

c

BankAccount d;// d.deposit(500); -> compile error

d

Page 51: Building Abstractions with Data  (Part 3)

An Analogy to Clear That UpJava World Balloon WorldGarbage Collection Unheld balloons fly away

and eventually pop, releasing boxes which can be used again

balance

b

1500

c

b = null;

d

Page 52: Building Abstractions with Data  (Part 3)

An Analogy to Clear That UpJava World Balloon WorldGarbage Collection Unheld balloons fly away

and eventually pop, releasing boxes which can be used again

bFree box cd

Page 53: Building Abstractions with Data  (Part 3)

What Happens?BankAccount b = new BankAccount( 1000 );println(b == null);println(b.getBalance());

Page 54: Building Abstractions with Data  (Part 3)

What Happens?BankAccount b = new BankAccount( 1000 );BankAccount c = new BankAccount( 500 );println(b.getBalance());println(c.getBalance());c = b;println(b.getBalance());println(c.getBalance());

Page 55: Building Abstractions with Data  (Part 3)

What Happens?BankAccount b = new BankAccount( 1000 );println(b.getBalance());b = null;println(b == null);println(b.getBalance());

Page 56: Building Abstractions with Data  (Part 3)

What Happens?public static void main(String args[]) {int x = 0;increment(x);println(x);

}public void increment(int x) {x++;

}

Page 57: Building Abstractions with Data  (Part 3)

What Happens?public static void main(String args[]) {int x = 0;x = increment(x);println(x);

}public int increment(int x) {x++;return x;

}

Page 58: Building Abstractions with Data  (Part 3)

What Happens?public static void main(String args[]) {BankAccount x = new BankAccount(500);increment(x);println(x.getBalance());

}public void increment(BankAccount x) {x = new BankAccount(x.getBalance() + 1);

}

Page 59: Building Abstractions with Data  (Part 3)

What Happens?public static void main(String args[]) {BankAccount x = new BankAccount(500);x = increment(x);println(x.getBalance());

}public BankAccount increment(BankAccount x) {x = new BankAccount(x.getBalance() + 1);return x;

}

Page 60: Building Abstractions with Data  (Part 3)

What Happens?public static void main(String args[]) {BankAccount x = new BankAccount(500);increment(x);println(x.getBalance());

}public void increment(BankAccount x) {x.balance = x.getBalance() + 1;

}

Page 61: Building Abstractions with Data  (Part 3)

A Better Versionpublic static void main(String args[]) {BankAccount x = new BankAccount(500);increment(x);println(x.getBalance());

}public void increment(BankAccount x) {x.setBalance(x.getBalance() + 1);

}

Page 62: Building Abstractions with Data  (Part 3)

An Even Better Versionpublic static void main(String args[]) {BankAccount x = new BankAccount(500);x.increment();println(x.getBalance());

}

Page 63: Building Abstractions with Data  (Part 3)

An Even Better and Useful Version

public static void main(String args[]) {BankAccount x = new BankAccount(500);x.setCompoundInterestRate(0.06);x.applyInterest();println(x.getBalance());

}

Page 64: Building Abstractions with Data  (Part 3)

Some Technical Stuff► Fields have default values. Local variables

don’t.► An object type field has a null pointer by

default if the constructor doesn’t assign anything else to it.► Does not cause a compile error if you try to invoke

a method on it► An unassigned object type local variable does

not have even a null pointer.► Compile error if you try to invoke a method

on it.

Page 65: Building Abstractions with Data  (Part 3)

What Happens?BankAccount b;println(b.getBalance());

Page 66: Building Abstractions with Data  (Part 3)

What Happens?BankAccount b = null;println(b.getBalance());

Page 67: Building Abstractions with Data  (Part 3)

What Happens?static BankAccount b;public static void main(String args[]) {println(b.getBalance());

}

Page 68: Building Abstractions with Data  (Part 3)

How to Avoid the Technical Stuff

►Always assign variables before using them!

►Never rely on default values!

Page 69: Building Abstractions with Data  (Part 3)

Why the Trouble with Passing?

►Three sub-questions:►Why pass only copies of the value

(whether it’s a primitive or a pointer)?►Avoid accidental reassignment, unwanted

side effects

Page 70: Building Abstractions with Data  (Part 3)

Why the Trouble with Passing?

►Three sub-questions:►Why pass pointers for object types?

►To allow controlled side effects through mutator methods

►For efficiency’s sake: no new copy of the actual object (which may be big) is created

►If you really want a new copy, there are ways

Page 71: Building Abstractions with Data  (Part 3)

Why the Trouble with Passing?

►Three sub-questions:►Can it be otherwise?

►Yes! Java chooses to evaluate variables this way, but other languages have different evaluation strategies.

Page 72: Building Abstractions with Data  (Part 3)

How to Avoid the Trouble with Passing?

►Most of the time, two strings share a balloon only because you have an object type parameter.

►Never reassign parameters!

Page 73: Building Abstractions with Data  (Part 3)

Outline►Assignment and State►Pass by Value versus Pass by Sharing►Message Passing and Final

Remarks on OOP

Page 74: Building Abstractions with Data  (Part 3)

Message Passing►Original view of OOP in the earlier

languages like Smalltalk.►Constructors: pass a message to tell

an object to begin with a certain state.

►Accessors: pass a message to ask about an object’s state.

►Mutators: pass a message to tell an object to change its state.

Page 75: Building Abstractions with Data  (Part 3)

Message Passing►Each method invocation is a message

for an object.►The object responds in one of two

ways:►Reply with a value►Act to change its state►Possibly both

Page 76: Building Abstractions with Data  (Part 3)

Message Passing►Big difference from functional view!►Functional view: same input, same

output►OO view: same input (message),

possibly different output (state) depending on time

Page 77: Building Abstractions with Data  (Part 3)

Group Discussion►Using the idea of message passing,

explain how the web works (how you can access and modify data on the internet through your web browser).

Page 78: Building Abstractions with Data  (Part 3)

Group Discussion► Hint: There are only

5 crucial parts. Identify which is the object, the driver program, the input to the driver program, the accessor message, the mutator message.

►URL► Browser►GET request► POST request► Internet

Page 79: Building Abstractions with Data  (Part 3)

OOP is Modeling►Not the one with the catwalks and

platforms!►OOP is modeling real world objects?

► Not really►You don’t write classes for dogs, chairs, etc.

► OOP is modeling real world concepts.►You write classes for social network profiles,

geometric figures, and… bank accounts►Although you can argue that dog, chair, etc. are

concepts too

Page 80: Building Abstractions with Data  (Part 3)

With Great Power Comes Great Responsibility

►Abstraction gives you power.►OOP > Procedural > imperative in

terms of abstraction.►Use OOP wisely.

Page 81: Building Abstractions with Data  (Part 3)

With Great Power Comes Great Responsibility

►Abstraction is your tool for achieving a goal.

►Abstraction is not your goal!►Always focus on the problem, not on

the abstraction!►Appropriate level of abstraction – one

that allows you to efficiently solve the problem

Page 82: Building Abstractions with Data  (Part 3)

With Great Power Comes Great Responsibility

►Remember:►Write for humans►Write for computers►Write generally, but not too generally

►If 10 layers of abstraction will allow you to do this, don’t go for 50.

►Don’t over-engineer.

Page 83: Building Abstractions with Data  (Part 3)

Summary►OOP is about coupling data and

procedures.►OOP is about coupling state and

behavior.►OOP is about changing state.►OOP is about message passing.►OOP is a powerful abstraction tool

that takes time to master and must be used with care.

Page 84: Building Abstractions with Data  (Part 3)

Mega Summary►What are algorithms?

► Concerned with computers and performance? ► Imperative: sequences of statements

► Concerned with science and generality? ►Declarative/Functional: compositions of

functions or expressions► Concerned with humans and modularity?

►Procedural: sequences of chunks of statements►Object-oriented: system of interacting objects

Page 85: Building Abstractions with Data  (Part 3)

Mega Summary►Remember the fundamental

distinctions to avoid confusion►Thinking the Algorithm►Writing the Program►Running the Computation►Use versus Definition► Instance versus Idea►Scope versus Environment

Page 86: Building Abstractions with Data  (Part 3)

Mega Summary►Benefits of Abstraction:►Readability

►Separating code into chunks►Reusability

►Allowing chunks to be reused►Robustness

►Allowing chunks to be changed easily without affecting other chunks

Page 87: Building Abstractions with Data  (Part 3)

Mega Summary►The history of programming is the

history of abstraction.►Machine Language (1s and 0s)►Assembly Language (not discussed

here)► Imperative►Procedural and Functional►OOP►The next big thing?

Page 88: Building Abstractions with Data  (Part 3)

Next Time…►We’ve tackled the first beast:

complexity►Next, we’re going to tackle infinity►But before that, a short discussion of

two useful pre-defined objects and Lab


Recommended