CMSC 132: Object-Oriented Programming IIObject-Oriented DesignDepartment of Computer ScienceUniversity of Maryland, College ParkApplying Object-Oriented Design 1. Look at objects participating in systemFind nouns in problem statement (requirements & specifications)Noun may represent class needed in designRelationships (e.g., “has” or “belongs to”) may represent fields2. Look at interactions between objectsFind verbs in problem statementVerb may represent message between objects3. Design classes accordinglyDetermine relationship between classesFind state & methods needed for each classClassesA class or interface defines and describes a set of objectsIt describes a set of methods or messages that the object responds toNot only the name and signature of the method, but the contract the method respectsClasses also provide/describe fields and method implementations1) Finding ClassesThermostat uses dial setting to control a heaterto maintain constant temperature in roomNounsThermostatDial settingHeaterTemperatureRoomFinding ClassesAnalyze each nounDoes noun represent class needed in design?Noun may be outside systemNoun may describe state in classAnalyzing NounsThermostatCentral class in modelDial settingState in class (Thermostat)HeaterClass in modelRoomClass in modelTemperatureState in class (Room)HeaterThermostatDial SettingRoomTempFinding ClassesDecision not always clearPossible to make everything its own classApproach taken in SmalltalkOverly complex2+3 = 5 vs. NUM2.add(NUM3) = NUM5Impact of designMore classes more abstraction, flexibilityFewer classes less complexity, overheadChoice (somewhat) depends on personal preferenceSingleton classesA Singleton class is a class for which there will only ever be one instanceMakes sense if the class is a subclass of another classFor example, you might have a class Person, and a singleton subclass ElvisAvoid making verbs/functions into classesExamples – class ListSorter, NameFinderUnless you might have multiple verb classes that all implement a common interfaceThe Strategy design pattern2) Finding MessagesThermostat uses dial setting to control a heater to maintain constant temperature in room VerbsUsesControlMaintainFinding MessagesAnalyze each verbDoes verb represent interaction between objects? For each interactionAssign methods to classes to perform interactionAnalyzing VerbsUses“Thermostat uses dial setting…” Thermostat.setDesiredTemp(int degrees)Control“To control a heater…” Heater.turnOn() Heater.turnOff()Maintain“To maintain constant temperature in room” Room.getTemperature()Example MessagesRoomThermostatHeatergetTemperature()turnOn() turnOff()setDesiredTemp()Resulting ClassesThermostatState – dialSettingMethods – setDesiredTemp()HeaterState – heaterOnMethods – turnOn(), turnOff()RoomState – tempMethods – getTemperature()SubtypesIf a class Y extends class X and implements interface Athen Y is a subtype of both X and AIf Q is a subtype of P, then Q satisfies P’s contractAnyone who expects a P can be given a QThis is known as the Liskov Substitution Principle (named for Prof. Barbara Liskov)Not always strictly followed, but an ideal to approachFor example, some iterators don’t support removeWhich could be a subtype?Class B {/** Search for x in a, * return location of first occurrence, -1 if not found */int search(int x, int a[]) { … } }Class C {/** .. same as above…uses binary search for speed; the array a must be sorted */int search(int x, int a[]) { … } }Which could be a subtype?Class B {/** Search for x in a, * return location of first occurrence, -1 if not found */int search(int x, int a[]) { … } }Class C {/** * Search for x in a, * return location of any occurrence, -1 if not found */int search(int x, int a[]) { … } }is-a vs. has-aSay we have two classes, Engine and CarTwo possible designsA Car object has a reference to an Engine objecthas-aThe Car class is a subtype of Engineis-aPrefer Composition to SubtypingGenerally, prefer composition/delegation (has-a) to subtyping (is-a)Subtyping is very powerful, but easy to overuse and can create confusion and lead to mistakesUsing is-a restricts you from having a car with more than one engine, or with no engineTempting to use subclassing in places where it doesn’t really make conceptual sense to avoid having to delegate methodsDon’tForms of Inheritance ExtensionAdds new functionality to subclassIn Java → new methodLimitationRestricts behavior of subclassIn Java → override method, throw exceptionCombinationInherits features from multiple superclassesAlso called multiple inheritanceNot possible in JavaIn Java → implement interface insteadMultiple Inheritance Example CombinationAlarmClockRadio has two parent classesState & behavior from both Radio &
View Full Document