1 Objects and Classes Fall 2001 Jeffrey T. Edgell Objects and Classes n An object is central to OO design n Objects tend to be so general that they may be hard to define n A class represents the template for creating an object n An object is made of 3 basic elements: n State (current data values) n Operations (what it can do) n Identity (object name which remains static) Class n A collection or grouping of objects n Objects derived from the same class n Support common operations n Have the same possible states n A class must define n Allowable operations n Possible states
12
Embed
Objects and Classes - ASTRONverkout/OOMethod.pdf1 Objects and Classes Fall 2001 Jeffrey T. Edgell Objects and Classes nAn object is central to OO design nObjects tend to be so general
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
1
Objects and Classes
Fall 2001Jeffrey T. Edgell
Objects and Classes
n An object is centralto OO design
n Objects tend to beso general that theymay be hard todefine
n A class representsthe template forcreating an object
n An object is made of3 basic elements:n State (current data
values)
n Operations (what itcan do)
n Identity (object namewhich remains static)
Class
n A collection orgrouping of objects
n Objects derivedfrom the same classn Support common
operations
n Have the samepossible states
n A class must definen Allowable operations
n Possible states
2
Class Example (book)
n Mailboxn Every mailbox
regardless of it’s usewill support the sametype of operationsn Add a mail messagen List all stored
messagesn Delete a messagen Retrieve a messagen Purge the mailboxn Etc.
n The state of the mailboxconforms to the definedbehaviorn Messages are stored by
timen Messages can be stored
for 30 daysn Messages will not
exceed 30 seconds
n No more than 10messages allowed
Classes and Objects
n Any object thatadheres to thedescription of aclass is an instanceof that class
n Example:n Voice mailbox
n E-mailbox
n Etc.
Example
n GUI
n Operationsn Define input devices
n Get input
n Display information
n Adjust size
n Adjust color
n Etc.
n State definitionn Allowable colors
n Allowable inputdevices
n Allowable sizes
3
Example
n Optical targetingsystems
n Operationsn Accept target
n Verify target
n Abort target
n Refine target
n State definitionn No target within 100
miles of civilianpopulation
n Military targets only
n System override bytarget establisheronly
Example
n Automatic pilot
n Operationsn Accept coordinatesn Accept speedn Monitorn Change coordinates
n Change speedn Alert pilotn Watch for trafficn Etc.
n State definitionn Acceptable
coordinates
n Acceptableairspeeds
n Divert course ofaircraft if traffic iswithin 1 mile
Inheritance Revisited
n One of the mostpowerful aspects is tobuild off the similaritiesbetween identifiedclasses
n We see that mostsystems there existsubclasses that are arefined version of amore general class(super class)
n Some slight changes inthe operations and dataexists
n An inherited class iscalled a subclass orderived class
n The parent is known asa super class, baseclass, or parent class
n For a language to beOO it must posses thisfeature
4
Building Software Using OOConceptsn In the software
process we seemany possiblelifecycles
n Most all lifecyclesposses the followingphases:n Analysis
n Designn implementation
n Various lifecycles:n Waterfall
n Spiral
n RAD
n JAD
n ExtremeProgramming
n Code and fix
n Dimensional
Analysis
n We start with ageneralized problemthat we attempt to refine
n A lot of documentationis produced to supportand verify findings
n A requirement or specis typically producedthat will act as acontract
n The spec should be:n Complete and
unambiguousn Contain functional and
non-functional detailn Should not self contradictn Must be reviewed and
verified by allstakeholders
n Can be used to verify thesystem once constructed
n Explain the whats andnot the hows
Design
n We must now pullclasses from thedomain
n There are manymethods to do thisn CRC
n The goal is to crisplydefine classes andrelationships whileminimizing the basiccomplexity
n Design is typicallydecomposed intotwo parts:n High-level
n Detailed
n During design wemay utilizeprototypes
5
Implementation
n Moving the design toreality
n In large systems,adherence to interfacedesign is critical
n During implementationwe often use sub-phasesn Unit testn System testn Integration test
n In traditionalapproaches, theintegration and systemtest is often completedas a “big bang”
n The OO approachemphasizes gradualand steady growthwhich reducesregression efforts andthus cost andcomplexity
Specifics of OO Design
n Look for classes andoperations first
n The first task is to breakthe problem intoclasses
n Once classes areidentified, theoperations of thoseclasses must beestablished
n The first search is forthe nouns in theproblem domain
n Once the basic classesare identified, lessobvious classes will beeasier to discover
OO Design Process
n Grady Boochdefines a simpleprocess that we canuse:n Identify the classes
n Identify thefunctionality of theclasses
n Identify therelationships amongall classes
n Booch is defininggoals and not steps(paradigm)
n The process isiterative as newthoughts will evolvewith the introductionof new classes
6
OO Design Process
n The final result ofthe design will ben A list of classesn Their operationsn Their relationships
n The interface mustbe well thought outand defines
n The class hierarchieswill be defined
n Relationshipsamong classes isoften expressedthrough graphicalnotation
n Design is critical(the last step prior tocoding)
The Class Interface
n Classes are always builtso they may beaccessed in one way
n Data can only beaccessed or changedthrough the interface
n There is norequirements for anyobject to have aninternal understandingof another object
n Example:n Add a message to
the mailbox
n Mailbox(message)
n Set_temperature(temp)
Identifying ClassRelationshipsn Three basic
relationships canexist among classesn Association (uses)
n Aggregation(containment)
n Inheritance(specialization)
n A class is said to useanother class if itmanipulates items ofthe other class in anyway
n Example:n Object airplane initializes
object autopilotn Object user created a
mail message
7
Identifying ClassRelationshipsn If a class can execute
all activities withoutknowledge or use ofanother class, it doesnot use that class
n It is important to keepthe uses relationshipminimized to reducecoupling
n The fewer classes wehave concerned aboutthe actions of anotherclass the less impacthere is with change
n If an object from oneclass contains an objectfrom another class wehave an aggregationrelationshipn Example
n Mailbox object containsmessage objects
n A class object containsstudent objects
n The aggregationrelationship is alsoknown as the “has-a”relationship
Identifying ClassRelationshipsn With aggregation it
is often useful tounderstand thecardinality of therelationshipn 1:m
n 1:1
n m:m
n Mailbox has 1greeting
n Mailbox contains nmessages
n Plane has oneautopilot
n Class has nstudents
Identifying ClassRelationshipsn Inheritance is often
identified as the “is-a” relationship
n Inheritance is moredifficult to identifythan the aggregationrelationship
n A Maxima is aNissan is a car
n A 747 is a jet is acommercial aircraftis aircraft
8
Traditional Design Approach
n Task-orientedbottom-up or top-down approach
n Typically acombination of thetwo approaches areused
n We look for verbs toidentify procedures
n 2 drawbacks exist withthis approachn Procedures are designed
to be small and solvenontrivial problems
n Procedures do not hideor protect data
n Classes are larger innature and hideinformation
Design Hints
n Do not use a classto describe a singleobject
n It should be our goalto use a class tocollect objects of acommon set ofoperations
n We should makeclasses broadenough to capturemany objects
n Classes should benarrow enough to bemeaningful
Object Oriented Design
Fall 2001Jeffrey T. Edgell
9
The CRC Method
n A very useful tool inidentifying classes,their operations, andrelationships toother classes
n Allows for tryingvarious designs
n Provides a simpletechnique to validateand modify design
n Typically use 3’’x5”index cards
n 1 card for eachclass
Why cards are good
n The space is limitedthus reducing what canbe put into a singleclass
n The cards can beshuffled andreorganized easily tocontemplated differentdesigns
n Easy to modify anddiscard
n Durable and portable
The CRC Process
n Make a single card foreach identified class
n List the operations onthe left side of the card
n List collaboratingclasses on the right ofthe card
n List data fields on theback
Class Name
Operations Collaborators
n It is easy and efficient touse the card to role playand walk throughvarious sequences tosolve a task
10
Tips for using CRC Cards
n It is a good idea to keepthe cards close togethern The visual aspect allows
us to visualizerelationships
n The cards are dynamicand we often change ortear them up
n It is unlikely that yourfirst several attempts atarranging and assigningresponsibilities will besomewhat incorrect
n The process is iterativen Getting started
n Identify several objectsand associatedoperations
n Allow each person toassume the role of anobject
n Perform walk throughs ofvarious tasks
n One person shouldanalyze the walk throughcritically
n The analyst role shouldbe rotated
Tips for using CRC Cards
n Any modifications orsuggestions shouldbe openly discussed
n Once all non-trivialactions can beperformed withconcurrence by thegroup, you havereached a basicdesign
n This method canwork with a singledesigner, although itis challenging withonly a singleperspective
Tips for using CRC Cards
n We should becareful at this pointnot to addoperations justbecause they canbe performed
n Do what is neededand what makessense (KISS)
n No implementationdetails should beplaced on a card
n However, the designis strengthened ifone can provemultipleimplementations canbe performed for asingle design
11
Class categories
n It is impossible toidentify all of thepossible categoriesand uses of classes
n However, there aresome commoncategories that mostfall into (designpatterns)
n Tangible itemsn Things easily identifiable
in the problem domain(nouns)
n System interfaces anddevicesn We typically find these
after identifying thetangible classes
n These capture systemresources and theinteraction of the systemn Display window, input
reader, output file, etc.
Class categories
n Agentsn Sometimes it is useful to
convert an operation of aclass to an agent class
n It has characteristicsaround the action itcarries out
n Often we use agents todecuple operations froma class
n Events and transactionsn Typically used to retain
information from the pastn The last mouse position,
the last set ofcoordinates for a plane,the last keystroke
n Also used to deal withscheduled eventsn Customer arrival class
that specifies whenwhere, and what kind ofcustomer
n An event scheduler forsimulations
Class categories
n User Rolesn Used to establish
different users withdifferent roles andpermissions of a system
n Systemsn Typically the control
harness for the entiresystem
n Used to initiate andterminate the system
n Containersn Used to retain
information for thegeneral application
n Examples:n Mailbox (holds
messages)n Invoice (holds orders)
n Address book (holdsaddresses)
12
Class categories
n Foundation classesn These are typically
generic fundamentalclasses
n At the beginning weshould assume they exist
n Examplen Date, stack, rectangle
n They encapsulate datatypes with well definedproperties and actions
n These classes are thehighest focus for reuse
n Collaborationpatternsn Grouping classes to
achieve a goal
n Examplen Container and iteratorn Model and view
Recognizing classrelationshipsn Associationn Easiest to identify
n Any class thatcollaborates withanother class isassociated
n CRC cards will tell usthis
n Aggregationn “has-a”
n If an object of oneclass contains or isthe sole manager ofobjects generated ofanother class
Recognizing classrelationshipsn Inheritance
n “is a”n If a class has every data
type and operation ofanother class and more
n Sometimes inheritance ishard because the baseclass has not beenidentified