1 csc 131 computer software engineering fall 2012 lecture # 7 object-oriented design & uml class...
TRANSCRIPT
11
CSc 131CSc 131
Computer Software EngineeringComputer Software Engineering
Fall 2012Fall 2012Lecture # 7Lecture # 7
Object-Oriented Design Object-Oriented Design & UML Class Models& UML Class Models
33
ClassesClasses• Object-oriented thinking begins with the definition Object-oriented thinking begins with the definition
of a class often defined as:of a class often defined as:
– templatetemplate
– generalized descriptiongeneralized description
– “ “blueprint” ... describing a collection of similar blueprint” ... describing a collection of similar itemsitems
• A metaclass (also called a superclass) is a collection A metaclass (also called a superclass) is a collection of classes.of classes.
44
What Is a Class?What Is a Class? A class is a description of a set of objects that share the A class is a description of a set of objects that share the
same same attributesattributes, , operationsoperations, , relationshipsrelationships, and , and semantics. semantics.
– An object is an instance of a class.An object is an instance of a class.
A class is an abstraction in that itA class is an abstraction in that it– Emphasizes relevant characteristics.Emphasizes relevant characteristics.– Suppresses other characteristics.Suppresses other characteristics.
55
What is a Class?What is a Class?
external entities
things
occurrences roles
organizational units
places
structures
class name
attributes:
operations:
66
What is an Object? What is an Object? Objects are key to understanding Objects are key to understanding object-oriented
technology. technology.
Many examples of real-world objects: your desk, Many examples of real-world objects: your desk, your computer, your bicycle. your computer, your bicycle.
These real-world objects share two characteristics: These real-world objects share two characteristics: statestate and and behaviorbehavior..
77
ObjectsObjectsSoftware objects are modeled after real-world objects Software objects are modeled after real-world objects
in that they too have in that they too have state and behavior. state and behavior.
A software object maintains its state in one or more A software object maintains its state in one or more variables . .
A software object implements its behavior with A software object implements its behavior with methods.
A method is a function (subroutine) associated with A method is a function (subroutine) associated with an object. an object.
88
Object TypesObject TypesExternal entities: sensors, actuators, control panel, External entities: sensors, actuators, control panel,
devicesdevices
Information items : displays, commands, etc.Information items : displays, commands, etc.
Entities which establishes the context of the Entities which establishes the context of the problem : controller, monitors, schedulersproblem : controller, monitors, schedulers
99
Identifying ClassesIdentifying ClassesAn object may appear as a noun (ex. An object may appear as a noun (ex.
Measurement) or disguised in a verb (to measure)Measurement) or disguised in a verb (to measure)
A method might appear as a verb (ex. Investigate) A method might appear as a verb (ex. Investigate) or disguised in a noun (investigation)or disguised in a noun (investigation)
Attributes describe some kind of characteristics Attributes describe some kind of characteristics for the object (adjectives). for the object (adjectives).
1010
Criteria for Evaluating Candidate ClassesCriteria for Evaluating Candidate ClassesOne or more attributesOne or more attributes
Needed functionality / Services (one or more Needed functionality / Services (one or more methods)methods)
Common attributes (apply to all objects of a Common attributes (apply to all objects of a specific class)specific class)
Common functionality/operations (apply to all Common functionality/operations (apply to all objects of a specific class)objects of a specific class)
1212
Encapsulation/HidingEncapsulation/HidingThe object encapsulatesboth data and the logicalprocedures required tomanipulate the data
Achieves “information hiding”
method # 1
data
method # 2
method # 4
method # 5
method # 6
1313
Class HierarchyClass Hierarchy
chairtable desk
instances of chair
furniture (superclass)
subclasses of thefurniture superclass
1414
MethodsMethods(a.k.a. Operations, Services)(a.k.a. Operations, Services)
An executable procedure that is encapsulated in a class and is designed to operate on one or more data attributes that are defined as part of the class.
A method is invoked via message passing.
1515
Encapsulation and InheritanceEncapsulation and Inheritance A class A class encapsulatesencapsulates data and operations that manipulates the data and operations that manipulates the
data in a single packagedata in a single package
Benefits of encapsulation:Benefits of encapsulation:
– implementation details are hidden (information implementation details are hidden (information hiding)- reduces the propagation of side effects hiding)- reduces the propagation of side effects when changes occur.when changes occur.
– Data structure and operations are in a single entity Data structure and operations are in a single entity (class) – component reuse(class) – component reuse
– Object interfaces are simplified – by message Object interfaces are simplified – by message passing and objects are not concerned with the passing and objects are not concerned with the details of internal data structures.details of internal data structures.
1616
InheritanceInheritance It is a key concept in OO paradigmIt is a key concept in OO paradigm
A subclass inherits all of the attributes and A subclass inherits all of the attributes and operations associated with its superclass.operations associated with its superclass.
It differentiates between conventional and OO It differentiates between conventional and OO development.development.
This implies that all data structures and This implies that all data structures and algorithms that implemented for superclass are algorithms that implemented for superclass are available for the subclass- available for the subclass- Reuse is Reuse is accomplished.accomplished.
1717
Representing Classes in UMLRepresenting Classes in UML
A class is represented using a rectangle A class is represented using a rectangle with compartments.with compartments.
Professor
- name- employeeID : UniqueId- hireDate- status- discipline- maxLoad
+ submitFinalGrade()+ acceptCourseOffering()+ setMaxLoad()+ takeSabbatical()
1818
What Should You Name Your Classes? Name classes to reflect what they represent.Name classes to reflect what they represent. The name should be a noun and not have a prefix or suffix.The name should be a noun and not have a prefix or suffix. Typically, capitalize the first letter in every word in the class Typically, capitalize the first letter in every word in the class
name.name.
Schedule
CourseOffering
Simple Names
1919
What Is Class Responsibility? A responsibility is a A responsibility is a
contract or obligation of the contract or obligation of the class.class.
The class responsibilities The class responsibilities are carried out by the are carried out by the corresponding attributes corresponding attributes and operations.and operations.
Responsibilities translate Responsibilities translate into operations and into operations and attributes as models are attributes as models are refined.refined.
2020
Classes/Objects Need to Collaborate Objects are useless unless they can Objects are useless unless they can
collaborate together to solve a problem.collaborate together to solve a problem.
– Each object is responsible for its own behavior Each object is responsible for its own behavior and status.and status.
– No one object can carry out every responsibility No one object can carry out every responsibility on its own.on its own.
How do objects interact with each other?How do objects interact with each other?– They interact through messages.They interact through messages.
2121
Where Do You Find Classes?
Problem StatementProblem Statement Use-case documentationUse-case documentation Use-case modelsUse-case models GlossaryGlossary Stakeholder RequestsStakeholder Requests Supplementary SpecificationSupplementary Specification Vision documentVision document Any other project documentationAny other project documentation
2222
How Do You Filter Nouns? Traditional filtering nouns approachTraditional filtering nouns approach
– Underline noun clauses in the use-case flow of Underline noun clauses in the use-case flow of eventsevents
– Remove: Remove:
Redundant candidatesRedundant candidates Vague candidatesVague candidates Actors (out of scope)Actors (out of scope) Implementation constructsImplementation constructs OperationsOperations
2323
Pitfalls When Filtering Nouns When identifying nouns, be aware thatWhen identifying nouns, be aware that
– Several terms may refer to the same object.Several terms may refer to the same object.– One term may refer to more than one object.One term may refer to more than one object.– Natural language is very ambiguous. Natural language is very ambiguous. – Any noun can be disguised as a verb and any verb can be Any noun can be disguised as a verb and any verb can be
disguised as a noun.disguised as a noun. Results are dependent on the author’s writing skills.Results are dependent on the author’s writing skills.
Filtering nouns can identify many unimportant objects.Filtering nouns can identify many unimportant objects.
2424
Find Classes from Use-Case Behavior
Identify a candidate set of model elements Identify a candidate set of model elements (classes) which are capable of performing (classes) which are capable of performing the behavior described in use cases.the behavior described in use cases.
The complete behavior of a use case has to The complete behavior of a use case has to be distributed to classes.be distributed to classes.
2525
Use Case Use-Case Realization
Sequence Diagrams Collaboration Diagrams
Distribute Use-Case Behavior to Classes
For each use-case flow of events: For each use-case flow of events: – Identify classes Identify classes – Allocate use-case responsibilities to classesAllocate use-case responsibilities to classes– Model class interactions in interaction diagramsModel class interactions in interaction diagrams
2626
Distribute Use-Case Behavior to Classes Purpose of this step:Purpose of this step:
– To express the use-case behavior in terms of To express the use-case behavior in terms of collaborating classes.collaborating classes.
– To determine the responsibilities of classes.To determine the responsibilities of classes.
2727
What Is an Association Name?
To clarify its meaning, an association may be named.To clarify its meaning, an association may be named. The name is represented as a label placed midway The name is represented as a label placed midway
along the association line.along the association line. An association name is usually a verb or verb phrase.An association name is usually a verb or verb phrase.
SchedulemanagesRegistrationController
2828
Good and Bad Examples of Association Good and Bad Examples of Association NamesNames
Poor examplesPoor examples– A student A student has ahas a schedule schedule– A department A department contains a contains a professorprofessor
Good examplesGood examples– A student A student creates creates a schedulea schedule– A department A department employsemploys a professor a professor
2929
Example: Classes for University Registration System
Student
Professor
CourseOffering
Schedule
Course
CourseCatalogSystem
BillingSystem
GraduationGown
Dormitory Fraternity
3030
What Is Multiplicity?What Is Multiplicity? Multiplicity is the number of instances of one class Multiplicity is the number of instances of one class
relates to one instance of another class.relates to one instance of another class.
For each association, there are two multiplicity For each association, there are two multiplicity decisions to make, one for each end of the association.decisions to make, one for each end of the association.– For each instance of Professor, many Course Offerings may For each instance of Professor, many Course Offerings may
be taught.be taught.– For each instance of Course Offering, there may be either For each instance of Course Offering, there may be either
one or zero Professor as the instructor.one or zero Professor as the instructor.
Professor<<entity>>
CourseOffering<<entity>>
0..1 0..*0..1 0..*
instructor
3131
Multiplicity IndicatorsMultiplicity Indicators
2..4
0..1
1..*
0..*
1
*
Exactly oneExactly one Zero or more (many, Zero or more (many,
unlimited)unlimited) ManyMany One or moreOne or more Zero or one (optional Zero or one (optional
scalar role)scalar role) Specified rangeSpecified range Multiple, disjoint rangesMultiple, disjoint ranges
2, 4..6
3232
What Is Aggregation?What Is Aggregation? An aggregation is a special form of association An aggregation is a special form of association
that models a whole-part relationship between that models a whole-part relationship between an aggregate (the whole) and its parts.an aggregate (the whole) and its parts.– An aggregation “Is a part-of” relationship.An aggregation “Is a part-of” relationship.
Multiplicity is represented like other associations.Multiplicity is represented like other associations.
PartWhole
1..211
3333
AggregationAggregation Aggregation is also a familiar concept Aggregation is also a familiar concept
from real life:from real life:
– a forest is an aggregate of treesa forest is an aggregate of trees
– a flock is an aggregate of sheepa flock is an aggregate of sheep
Aggregation is a group/member Aggregation is a group/member associationassociation
– The aggregate object may potentially The aggregate object may potentially exist without its constituent objects.exist without its constituent objects.
3434
CompositionComposition Composition is a common structure in software Composition is a common structure in software
systems, because many composite objects appear systems, because many composite objects appear in real life:in real life:
– a dog is a composite of a head, a body, a tail a dog is a composite of a head, a body, a tail and 4 legsand 4 legs
– an email is composed of a header and a text an email is composed of a header and a text message; the header is composed of a From: message; the header is composed of a From: line a To: line, etc.line a To: line, etc.
– The composite object does not exists without its The composite object does not exists without its componentscomponents
– At any time, each component may be part of At any time, each component may be part of only one composite.only one composite.
3535
CompositionComposition A solid diamond denotes A solid diamond denotes compositioncomposition, a , a
strong form of aggregation, where strong form of aggregation, where components cannot exist without the components cannot exist without the aggregate. aggregate.
Window
scrollbar title body
Header Panel
2 1 1
Slider
111
3636
What Is Generalization?What Is Generalization? A relationship among classes where one A relationship among classes where one
class shares the structure and/or behavior class shares the structure and/or behavior of one or more classesof one or more classes
Defines a hierarchy of abstractions in which Defines a hierarchy of abstractions in which a subclass inherits from one or more a subclass inherits from one or more superclassessuperclasses– Single inheritanceSingle inheritance– Multiple inheritanceMultiple inheritance
Is an “is a kind of” relationshipIs an “is a kind of” relationship
3737
Example: Single InheritanceExample: Single Inheritance
One class inherits from anotherOne class inherits from another
CheckingSavings
Superclass (parent)
Subclasses
Generalization Relationship
Account
- balance- name- number
+ withdraw()+ createStatement()
3838
– All classes have meaningful, domain-All classes have meaningful, domain-specific names.specific names.
– Each class has a small set of collaborators.Each class has a small set of collaborators.
– There are no “indispensable” classes. There are no “indispensable” classes. – A class that collaborates with everyone A class that collaborates with everyone
needs to be redefined.needs to be redefined.
– The classes can handle a change in The classes can handle a change in requirements.requirements.
Things Are Going Well If:
3939
–A number of classes have no A number of classes have no responsibilities.responsibilities.
–A single responsibility gets assigned to A single responsibility gets assigned to several classes.several classes.
–All classes collaborate with All classes collaborate with all other classes.all other classes.
Things Are Not Going Well If:
4040
QuestionsQuestions
What is Next : More on Sequence diagrams & coupling and More on Sequence diagrams & coupling and
cohesioncohesion Continue with Object Oriented Design & UML Continue with Object Oriented Design & UML
Class ModelsClass Models
Continue with “Design and implementation..”Continue with “Design and implementation..”