Week 4 (September 23)

Download Report

Transcript Week 4 (September 23)

CSC 520 – Advanced Object
Oriented Programming, Fall, 2010
Thursday, September 2, Week 4
Design by Contract, Java Exceptions,
Eventing, Finding the Classes, Design
Patterns and the Kitchen Sink
Design by Contract
•
•
•
•
Preconditions – constraints on the caller
Postconditions – constraints on the called
Invariants – constraints on an object’s state
Preconditions may weaken for derived class methods
that override a base class or interface method.
Why???
• Postconditions may strengthen for derived class
methods that override a base class or interface
method. Why???
Exception constructs already in use
• try {
• attempt to run a block of code
• } catch (Type_A_Exception taex) {
• Do something with taex, e.g., taex.getMessage()
• } catch (Type_A_Exception tbex) {
• Do something with tbex, e.g., print, then throw tbex
• } finally {
• Do this after all of the above, even after a return!
• }
Unchecked and checked exceptions
• javac forces client code to catch checked
exceptions
• unchecked exceptions need not be caught;
they can be
– java.lang.Error
• java.io.IOError – maybe a disk drive goes off line
– java.lang.RuntimeException
• java.lang.NullPointerException
• Other java.lang.Exceptions are checked
Throwing a new exception
• An explicit throw creates a new Exception.
– public int deleteTiles(String tileset) throws
ScrabbleException
• throw new ScrabbleException("Player " + name
•
+ " does not have " + tile.toString()
•
+ " to delete from set of tiles.");
Rethrowing an exception
• A rethrow catches and handles an Exception
object, then throws it again.
• } catch (NumberFormatException nx) {
•
System.err.println(“Exception: “
•
+ nx.getMessage();
•
nx.printStackTrace(); // to System.err
•
throw nx ; // This is the rethrow
An implicit throw
• An implicit throw allows a called method to
throw an Exception via the calling method.
– public String [][] move(String command) throws
ScrabbleException
• Invokes “int used =
players[nextPlayer].deleteTiles(validword);
• But move() does not catch deleteTiles’s exception:
– public int deleteTiles(String tileset) throws ScrabbleException
• The remove() implicitly throws deleteTile’s exception.
A Chained Exception
• A chained Exceptions tacks a detail message
onto an underlying cause Exception.
– } catch (NumberFormatException nx) {
–
throw new Exception(“detail message”, nx);
• Used to prepend a context-specific message to
an Exception thrown from a called method.
• The new Exception must have the appropriate
constructor. It may be a custom Exception.
Custom Exceptions
• A custom Exception inherits, directly or
indirectly, from java.lang.Exception.
– public class ScrabbleException extends Exception
• public ScrabbleException(String text)
– super(text); // Call to base class constructor.
• Client code can explicitly catch a custom
Exception.
An event mechanism = publishers,
subscribers & delivered events
• java.util.EventListener is a tagging interface
that applications implement to create a
listener whose class identity is unknown to the
publisher
• java.awt.event.ActionListener for GUIs
• java.beans.beancontext.BeanContext for Java Bean
tools that automated assembly of components via
graphical tools
• games2010rev5.GameMoveEventListener
Publishers Publish Events
• Publisher classes support subscribe and unsubscribe
methods via which their Event Listeners (see
previous slide) can subscribe and unsubscribe for
event delivery.
• Publishers later deliver events to subscribed listeners
when the events occur.
• There is no standard interface or base class for
publishers in the Java library.
• Any class that creates and delivers an event type is a
publisher.
Event Objects Carry Data
• java.util.EventObject is the library base class
• getSource() returns Object source of the event
– Subclasses use this base class to store the event publisher
• java.awt.event.ActionEvent for GUIs
• java.beans.beancontext.BeanContextEvent
• games2010rev5.GameMoveEvent
– getDescription(), getGameState(), getMoveNumber()
• Publisher passes data contents to the event constructor
– Event class provides getters for these data
• javax.sound.midi.MidiEvent does not implement it
UML Sequence Diagram for Event
Subscription Lifecycle
TwoDimensionalBoardGame
GameMoveEventListener
subscribeToGameMoveEvent
notifyMoveEvent(event:GameMoveEvent) (0..* times)
unsubscribeToGameMoveEvent
Observer Design Pattern
• Gang of Four calls this the Observer Pattern
• “Define a one-to-many dependency between
objects so that when one object changes
state, all its dependents are notified and
updated automatically.”
• http://www.oodesign.com/observer-pattern.html
• The official design pattern does not show the event
object, which typically passes as a parameter to the
event listener-defined method.
Meyer and Design Patterns
22.3 General Heuristics for Finding Classes
• An analysis class describes a data abstraction directly
drawn from the model of the external system.
• ScrabbleBoard
• An implementation class describes a data abstraction
introduced for the internal needs of the algorithms in
the software.
• private char [][] tiles = new char
[RowHeadings.length][ColumnHeadings.length];
• A design class describes an architectural choice.
• Design patterns.
How to Find the Classes
• Tell stories. Underline the nouns.
• Adjectives for deferred classes (comparable, serializable).
• Watch out for natural language nouns!
•
•
•
•
Avoid useless classes.
Avoid Blobs and Grand Central Stations.
Elicit, then reject classes. (Edit!)
Previous designs and class libraries.
• Meyer uses use cases only for validation, not analysis.
• He does not like CRC cards  We use class diagrams.
Some other Design Patterns for
Tonight -- Factories
• Abstract Factory – our map_interface
• The manufacturing interface is abstract.
• The manufactured object interface is abstract.
• A concrete class derived from the manufacturing
interface constructs concrete objects derived from the
manufactured object interface.
• Factory Method
• The manufacturing class has an abstract manufacturing
method.
• Its subclasses manufacture concrete class objects.
Memento Pattern
• Without violating encapsulation, capture and
externalize an object’s state so that the object
can be restored to this state later.
• java.lang.Cloneable, java.io.Serializable
• See Scrabble class data field definitions.
• See ScrabbleGame save and restore methods.
Iterator Pattern
• Provide a way to access the elements of an
aggregate object sequentially without
exposing its underlying representation.
• An iterator is an abstracted pointer.
• See interface java.util.Iterator and ListIterator.
• C++ Standard Template Library supports
forward and reverse iterators.