Building Abstractions with Data (Part 3) CS 21a: Introduction to Computing I First Semester,...

Post on 30-Dec-2015

218 views 4 download

Tags:

transcript

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

(Re)Assignment Produces State

Without State

int money = 500;

int moneyAfterDeposit = deposit(money, 1000);

With State

int money = 500;

money = deposit(money, 1000);

(Re)Assignment Produces State

Without State

int money = 500;

int moneyAfterDeposit = money + 1000;

With State

int money = 500;

money = money + 1000;

(Re)Assignment Produces State

Without State

int money = 500;

int moneyAfterDeposit = money + 1000;

With State

int money = 500;

money = money + 1000;

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

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

(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

(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

(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 6

int z = ++x; // now 7

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

Changing Object State By Updating Fields

public class Diet

{

int calories;

public Diet() {

calories = 0;

}

public void recordBurgerEaten() {

calories += 400;

}

}

Changing Object State By Updating Fields

public class Diet

{

int calories;

public Diet() {

calories = 0;

}

public void recordBurgerEaten() {

calories += 400;

}

}Mutator method

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

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

Outline

►Assignment and State►Pass by Value versus Pass by

Sharing►Message Passing and Final Remarks

on OOP

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

Primitive Type Variablesversus Object Variables

►Primitive type variables directly contain valuesint x = 5;

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

5

x

bbalance

0

Primitive Type Variablesand Assignment

int x = 1000;1000

x

Primitive Type Variablesand Assignment

int x = 1000;

int y = x;1000

x

1000

y

Primitive Type Variablesand Assignment

int x = 1000;

int y = x;1000

x

1000

y

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

Primitive Type Variablesand Assignment

int x = 1000;

int y = x;1000

x

1000

y

Pass by value: y gets a copy of 1000

Primitive Type Variablesand Assignment

int x = 1000;

int y = x;

y = y - 100;

println( x );

println( y );

1000

x

900

y

Prints:

1000900

Object Variablesand Assignment

BankAccount b = new BankAccount( 1000 );

bbalance

1000

Object Variablesand Assignment

BankAccount b = new BankAccount( 1000 );

BankAccount c = b;

bbalance

1000

c

Object Variablesand Assignment

BankAccount b = new BankAccount( 1000 );

BankAccount c = b;

bbalance

1000

c

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

Object Variablesand Assignment

BankAccount b = new BankAccount( 1000 );

BankAccount c = b;

bbalance

1000

c

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

Object Variablesand Assignment

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

bbalance

900

c Prints:

900900

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

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!

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

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

What’s a Pointer?

►So when you do…c.withdraw(100);►The balance is changed for the

instance that both b and c share

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.

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

balance

1000

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

balance

1250deposit(250)

The null Pointer

►An object variable that doesn’t point to an actual instance yet has a null pointer (points to nothing)

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)

An Analogy to Clear That Up

Java World Balloon World

Object variable name Hand

Object variable value orPointer

String (not the CS kind)

Object instance Balloon

An Analogy to Clear That Up

Java World Balloon World

Call to constructor Make a new balloon

Return value from constructor

String that ties the new balloon

Assigning to object variable

Make the hand hold the string

An Analogy to Clear That Up

Java World Balloon World

Call to constructor Make a new balloon

Return 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

An Analogy to Clear That Up

Java World Balloon World

Call to constructor Make a new balloon

Return 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

An Analogy to Clear That Up

Java World Balloon World

Using 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

An Analogy to Clear That Up

Java World Balloon World

Using 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

An Analogy to Clear That Up

Java World Balloon World

Using 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

An Analogy to Clear That Up

Java World Balloon World

Using 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

An Analogy to Clear That Up

Java World Balloon World

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

An Analogy to Clear That Up

Java World Balloon World

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

An Analogy to Clear That Up

Java World Balloon World

Null Pointer String with no balloon

balance

b

1500

c

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

An Analogy to Clear That Up

Java World Balloon World

Unassigned variable (doesn’t even matter if Object or primitive)

Hand holding nothing

balance

b

1500

c

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

d

An Analogy to Clear That Up

Java World Balloon World

Garbage Collection Unheld balloons fly away and eventually pop, releasing boxes which can be used again

balance

b

1500

c

b = null;

d

An Analogy to Clear That Up

Java World Balloon World

Garbage Collection Unheld balloons fly away and eventually pop, releasing boxes which can be used again

bFree box cd

What Happens?

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

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

What Happens?

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

What Happens?

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

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

}

What Happens?

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

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

}

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

}

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;

}

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;

}

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

}

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

}

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

}

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.

What Happens?

BankAccount b;println(b.getBalance());

What Happens?

BankAccount b = null;println(b.getBalance());

What Happens?

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

}

How to Avoid the Technical Stuff

►Always assign variables before using them!

►Never rely on default values!

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

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

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.

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!

Outline

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

Remarks on OOP

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.

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

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

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

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

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

With Great Power Comes Great Responsibility

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

terms of abstraction.►Use OOP wisely.

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

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.

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.

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

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

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

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?

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