CS 151: Object-Oriented Design

concepcionsockSoftware and s/w Development

Aug 15, 2012 (4 years and 10 months ago)

321 views

CS 151: Object
-
Oriented Design

February 27 Class Meeting

Department of Computer Science

San Jose State University


Spring 2012

Instructor: Ron Mak

www.cs.sjsu.edu/~mak

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

2

Assignment #1 Results


Section 1


mean 90.0


average 87.3


standard deviation 7.0



Section 2


mean 85.0


average 86.4


standard deviation 6.5

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

3

Quiz #2 Results


Section 1


average: 74.55%



Section 2


average: 72.50%

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

4

Assignment #3


Due Wednesday, March 7



First version of your Rock
-
Paper
-
Scissors game.


Command line only
. No GUI.


The number of throws per match should be a
command
-
line
argument

when you start the application.


At the start of each throw, the application should
prompt the
human player

for his or her choice (rock, paper, or scissors)
which the human should enter, or the human can ask for the
current score or a help message.


For each throw, the computer should compute its choice
entirely
by random
.



Download and use the free NetBeans IDE:
http://netbeans.org/


SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

5

Assignment #3
, cont’d


Apply the
object
-
oriented principles

that you’ve learned.


Make your code reliable, robust, flexible, easy to maintain, etc.


You will be building on this code base in future assignments.


new algorithms for the computer’s choice for each throw


a graphical user interface (GUI)


...



Update your Functional and Design Specifications


Before editing, do an “Accept Change” on all your changes to
the Functional Specification to create a new base document.


Make sure “Track Changes” is on for both documents.

_


Word demo

NetBeans demo

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

6

Assignment #3
, cont’d


What to turn in


A
zip file

containing all your Java source files in the
src

subdirectory that NetBeans creates.


Do not include the
nbproject

and
test

subdirectories.


If your mailer rejects the zip file as an attachment, try renaming it
so that the suffix is something other than
.zip

, such as
.zzz

.


Email the zip file and the updated Functional Specification and
Design Specification to
ron.mak@sjsu.edu

and to
ahmad@yazdankhah.com


CC all your team members.


Subject: ASSIGNMENT #3, team name, section number

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

7

Safer Programming


Last week


Use encapsulation properly


Create objects with a initial valid state


Object fields are private


Accessors do not modify the object state


Mutators preserve the valid object state



Therefore, we are more confident that we are creating
safer classes

to share with other programmers.


Are we confident enough to make a
contract


with other programmers?

_

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

8

Programming by Contract


Metaphor promoted by Bertrand Meyer


Pioneer of object
-
oriented programming


Inventor of the Eiffel programming language



Methods are agents that fulfill a
contract
.



The contract spells out the
responsibilities



of the caller (the class user)


of the implementor (you, the programmer)



Involves
preconditions
,
postconditions
, and
invariants
.

_

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

9

Preconditions


The
MessageQueue

class


What should happen if the class user attempts to
remove a message from an empty queue?


Class
MessageQueue

can declare this to be a runtime error.


Class
MessageQueue

can simply return
null
.


Which is better?

public class MessageQueue

{


public void add(Message msg) { ... }


public Message remove() { ... }


public Message peek() { ... }


public int size() { ... }


...

}

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

10

Preconditions
, cont’d


Excessive error checking is costly.


Returning dummy values can complicate testing.


Contract metaphor:


The service provider (i.e., the class)

must specify preconditions.


If the precondition is true
,

the service provider must work correctly.


If the precondition is not true
,

the service provider can do anything.


throw an exception?


return a default or false answer?


corrupt data?


handle the error gracefully?

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

11

Preconditions
, cont’d

A
precondition

is a condition that
must be true

before the service provider can promise to fulfill

its part of the contract.


If the precondition is not true and the service

is still requested, the provider can choose

any action that is convenient for it
, no matter

how disastrous the outcome may be for the

service requester.

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

12

Preconditions
, cont’d


What happens if the precondition not fulfilled?


The
remove()

method
makes no promises

to do

anything sensible if called on an empty queue.


IndexOutOfBoundsException



Other implementation may have different behavior.

/**


Remove the message at the head.


@return the message at the head


@precondition size() > 0


*/

Message remove()

{


return elements.remove(0);

}

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

13

Example: Queue as a Circular Array


The current
MessageQueue

implementation

removes messages inefficiently.


After the head message (element 0) is removed,

all the remaining messages must shift one position:

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

14

Queue as a Circular Array
, cont’d


Implement a queue as a circular array.


two index variables,
head

and
tail


head
: index of the next message in the queue to be removed


tail
: index of the position where the next new message will go

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

15

Queue as a Circular Array
, cont’d


As messages are added and removed,
head

will chase
after
tail
, and both will wrap around to the beginning
of the array (hence the name “circular”).

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

16

Queue as a Circular Array
, cont’d


What must never happen?


Indexes
head

and
tail

must never cross each other.


Can
head

and
tail

be equal? What does that mean?

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

17

Queue as a Circular Array
, cont’d


What else can go wrong?


count

becomes negative.


After
head

has wrapped around,

remove()

retrieves a previously removed message.


The cost of violating a precondition can be very high!

/**


Remove message at head.


@return the message that was removed from the queue


@precondition size() > 0


*/

public Message remove()

{


Message r = elements[head];


head = (head + 1) % elements.length;


count
--
;


return r;

}

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

18

Assertions


How can we check that a precondition is met?



Use Java’s
assertion feature

to alert a class user

at run time that there is a precondition violation:



assert

condition


or



assert

condition
:

explanation

_

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

19

Assertions,
cont’d

/**


Remove message at head.


@return the message that was removed from the queue


@precondition size() > 0


*/

public Message remove()

{


assert count > 0 : "violated precondition size() > 0"



Message r = elements[head];


head = (head + 1) % elements.length;


count
--
;


return r;

}

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

20

Assertions,
cont’d


If the assertion fails (i.e., the precondition is violated),
the program terminates with an
AssertionError
.



Assertions are normally turned off
,

so you must turn them on when you run
java
:



java

enableassertions MailSystemTest


or



java

ea MailSystemTest

_

assert count > 0 : "violated precondition size() > 0"

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

21

Exceptions as Part of the Contract


The exception is part of the contract.


Now the
remove()

method has no precondition.

/**


Remove message at head.


@return the message that was removed from the queue


@throws NoSuchElementException if size() <= 0



*/

public Message remove()


throws NoSuchElementException

{


if (count <= 0) {


throw new NoSuchElementException(


"violated precondition size() > 0");


}


...

}

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

22

Postconditions

A
postcondition

is a condition that

the service provider promises to fulfill

after the call has completed.


Example: The
add()

method



@postcondition size() > 0



The postcondition of one call (e.g., to add) can imply

the precondition of another call (e.g., to remove):



q.add(m1);


m2 = q.remove();


_

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

23

Postconditions
, cont’d


If a postcondition is not fulfilled,

a method should
not throw an exception
.



Why not?


But the method can use an assertion to check a postcondition.

_


SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

24

Class Invariants

A
class invariant

is a condition

that holds for all objects of a class,

except possibly objects that are

undergoing mutation.


In other words: A class invariant

must be true before and after

every method call, although

it can be temporarily violated

inside a method call.

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

25

Class Invariants
, cont’d


Example: Circular array
MessageQueue

class:



1.
Is it true after every constructor has completed?


Guarantee that
no invalid objects

are ever created.


2.
Is it preserved by every mutator?


If it is true at the start of the mutator,

it must still be
true after the mutator returns
.

_

(0 <= head) && (head < elements.length)

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

26

Class Invariants
, cont’d


The constructor for
MessageQueue



Sets
head

to 0


Add the precondition that
size() > 0


Therefore, the invariant is true after the constructor is called.

_

(0 <= head) && (head < elements.length)

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

27

Class Invariants
, cont’d


Only the
remove()

method modifies
head


The method sets



head
new

= (head
old

+ 1) % elements.length


Because



head
old

+ 1 > 0


Therefore



head
new

= (head
old

+ 1) % elements.length >= 0


And from the definition of

%



head
new

< elements.length



We have proven that every array access of
elements[head]


is always legal and will never throw an array exception.

(0 <= head) && (head < elements.length)

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

28

Interface Invariants vs. Implementation Invariants


Interface invariants


Conditions involve only the public interface of a class.


A class user is interested in these because they

guarantee class behavior
.



Implementation invariants


Conditions involve the details of a particular implementation.


A class implementor is interested in these because they

ensure the correctness of the algorithms
.

_

SJSU Dept. of Computer Science

Spring 2012: February 27

CS 151: Object
-
Oriented Design

©
R. Mak

29

Interface Invariants vs. Implementation Invariants


Which type are the
MessageQueue

invariants?



Day

class invariant:



1 <= getMonth() && getMonth() <= 12



Which type of invariant?


Stated in terms of only the
public interface

of the class.

_