KEMBAR78
06 Class Design | PDF | Class (Computer Programming) | Xml
0% found this document useful (0 votes)
73 views22 pages

06 Class Design

The document outlines guidelines for class design in software development, detailing the transition from analysis classes to design elements. It covers the creation of initial design classes, defining operations, relationships, states, and attributes, as well as class diagrams. Additionally, it discusses strategies for designing boundary, entity, and control classes, along with packaging tips and the importance of encapsulation and visibility in class design.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views22 pages

06 Class Design

The document outlines guidelines for class design in software development, detailing the transition from analysis classes to design elements. It covers the creation of initial design classes, defining operations, relationships, states, and attributes, as well as class diagrams. Additionally, it discusses strategies for designing boundary, entity, and control classes, along with packaging tips and the importance of encapsulation and visibility in class design.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

2

Class Design Overview

Design Classes
ITSS SOFTWARE DEVELOPMENT
Project Specific
6. CLASS DESIGN Guidelines

Class
Design
Design Model

Supplementary
Specifications
Analysis Classes
Some slides extracted from IBM coursewares

1 2

From Analysis Classes to Design Elements


Content Analysis Classes Design Elements
1. Create Initial Design Classes <<boundary>>

2. Define Operations/Methods
<<control>>
3. Define Relationships Between Classes <<subsystem>>
Subsystem

4. Define States
<<entity>>
5. Define Attributes
6. Class Diagram
<<boundary>>
<<subsystem>>
Subsystem

Many-to-Many Mapping
3 4

1
6

Identifying Design Classes Class Design Considerations


• An analysis class maps directly • Class stereotype
to a design class if: • Boundary
• It is a simple class • Entity
• It represents a single logical abstraction • Control
• More complex analysis classes may • Applicable design patterns
• Split into multiple classes
• Become a package
• Become a subsystem (discussed later)
• Any combination …

5 6

7 8

How Many Classes Are Needed? Strategies for Designing Boundary Classes
• Many, simple classes means that each class
• Encapsulates less of the overall system intelligence • User interface (UI) boundary classes
• What user interface development tools will be used?
• Is more reusable
• How much of the interface can be created by the
• Is easier to implement
development tool?
• A few, complex classes means that each class • External system interface boundary classes
• Encapsulates a large portion of the overall system • Usually model as subsystem
intelligence
• Is less likely to be reusable MainWindow SubWindow

• Is more difficult to implement <<subsystem>>


MainForm

A class should have a single well-focused purpose.


Button DropDownList
A class should do one thing and do it well!

7 8

2
9 10

Strategies for Designing Entity Classes Strategies for Designing Control Classes
• Entity objects are often passive and persistent • What happens to Control Classes?
• Performance requirements may force some re-factoring • Are they really needed?
Analysis Design • Should they be split?
<< Entity >> FatClass
FatClass - privateAttr • How do you decide?
- privateAttr
+ getCommonlyUsedAttr1()
- commonlyUsedAttr1
- commonlyUsedAttr2 + getCommonlyUsedAttr2() • Complexity
- rarelyUsed1 + getRarelyUsedAtt1()
- rarelyUsed2 + getRarelyUsedAtt2() • Change probability

1 0..1
• Distribution and performance
FatClassDataHelper FatClassLazyDataHelper • Transaction management
- commonlyUsedAttr1 - rarelyUsedAttr1
- commonlyUsedAttr2 - rarelyUsedAttr2

9 10

Review: Class and Package Group Design Classes in Packages


• What is a class? • You can base your packaging criteria on a
• A description of a set of objects that share the same number of different factors, including:
responsibilities, relationships, operations, attributes, and • Configuration units
semantics Class Name • Allocation of resources among development teams
• Reflect the user types
• What is a package? • Represent the existing products Package C

• A general purpose mechanism for organizing elements and services the system uses
Package B
into groups
Package A
• A model element which can contain other model
elements
Package
Name

11 12

3
Packaging Tips: Boundary Classes Packaging Tips:
If it is likely the system interface If it is unlikely the system interface
Functionally Related Classes
will undergo considerable changes will undergo considerable changes • Criteria for determining if classes are functionally
related:
• Changes in one class' behavior and/or structure
necessitate changes in another class
• Removal of one class impacts the other class
• Two objects interact with a large number of messages
or have a complex intercommunication
• A boundary class can be functionally related to a
particular entity class if the function of the boundary
class is to present the entity class
Boundary classes placed in Boundary classes packaged • Two classes interact with, or are affected by changes in
separate packages with functionally related classes the same actor

13 14

Packaging Tips: Package Dependencies: Package Element Visibility


Functionally Related Classes (continued) PackageA

• Criteria for determining if classes are functionally A


+ Class A1

related (continued): + Class A2

• Two classes have relationships between each other


+ Class A3
• One class creates instances of another class
• Criteria for determining when two classes should B Only public classes
can be referenced
NOT be placed in the same package: PackageB
outside of the owning
• Two classes that are related to different actors should package
Public visibility + Class B1
not be placed in the same package
- Class B2
• An optional and a mandatory class should not be placed Private visibility
in the same package

OO Principle: Encapsulation

15 16

4
Package Coupling: Tips
Example: Registration Package
• Packages should not be A B

cross-coupled
X MainStudentForm MainRegistrarForm

1 1

Upper A
0..1
• Packages in lower layers 0..1
Layer <<boundary>> <<boundary>>
should not be dependent RegisterForCoursesForm CloseRegistrationForm
upon packages in upper X X
Lower
layers Layer
B 1
1 1
<<control>> <<control>>
RegistrationController
• In general, dependencies CloseRegistrationController
C
should not skip layers

X = Coupling violation

17 18

Example: University Artifacts Package: Example: University Artifacts Package:


Generalization Associations
<<entity>>
<<entity>> Schedule
Student 1 0..*

<<entity>> <<entity>> 0..* 0..*


Student ScheduleOfferingInfo

primaryCourses alternateCourses
0..2
<<entity>> 0..4
<<entity>> <<entity>> 0..*
PrimaryScheduleOfferingInfo <<entity>> instructor <<entity>> <<entity>>
FulltimeStudent ParttimeStudent
Professor CourseOffering Course
0..*
0..1 0..* 0..* 1
Prerequisites
0..*
1
CourseOfferingList

19 20

5
22

Example: External System Interfaces


Content
Package
1. Create Initial Design Classes
<<Interface>> <<Interface>>
IBillingSystem ICourseCatalogSystem 2. Define Operations/Methods
3. Define Relationships Between Classes
4. Define States
5. Define Attributes
6. Class Diagram

21 22

23 24

2.1. Define Operations Name and Describe the Operations


• Messages displayed in interaction diagrams • Create appropriate operation names
• Indicate the outcome
:CourseRegistrationController ::SubjectInfo
SubjectInfo • Use client perspective

SubjectInfo • Are consistent across classes


getSubjectPrerequisites() • Define operation signatures
getSubjectPrerequisites() • operationName([direction]parameter: class,..) :
returnType
• Other implementation dependent functionality
• Direction is in (default), out or inout
• Manager functions
• Provide short description, including meaning of all parameters
• Need for class copies
• Need to test for equality

23 24

6
25 26

Program documentation
/** Guidelines: Designing Operation Signatures
* Parse XML data into a DOM representation, taking local resources and Schemas into account.
* @param inputData a string representation of the XML data to be parsed.
* @param validating whether to Schema-validate the XML data • When designing operation signatures, consider if
* @return the DOM document resulting from the parse
* @throws ParserConfigurationException if no parser could be created
parameters are:
* @throws SAXException if there was a parse error
• Passed by value or by reference
* @throws IOException if there was a problem reading from the string
*/ • Changed by the operation
public static Document parseDocument(String inputData, boolean validating) throws
ParserConfigurationException, SAXException, IOException { • Optional
//Change to UnicodeReader for utf-8
...
• Set to default values
} • In valid parameter ranges
• The fewer the parameters, the better
• Pass objects instead of “data bits”

25 26

27

How Is Visibility Noted?


Operation Visibility
• The following symbols are used to specify export
• Visibility is used to enforce encapsulation
control:
• May be public, protected, or private
• + Public access
• # Protected access
Private • - Private access
operations
Class1
- privateAttribute
+ publicAttribute
# protectedAttribute
Public Protected - privateOperation ()
operations operations
+ publicOPeration ()
# protecteOperation ()

27 28

7
29 30

Course Registration CS: Operations for CourseInfo.


Scope and CourseRegistrationController
• Determines number of instances of the
CourseInfo
attribute/operation
• Instance: one instance for each class instance + getCourseInfo(String): CourseInfo.
• Classifier: one instance for all class instances
• Classifier scope is denoted by underlining the
attribute/operation name CourseRegistrationController
Class1 + registerForCourse(String, String): void
- classifierScopeAttr - checkPrerequisiteCondition(): boolean
- instanceScopeAttr
+ classifierScopeOp () - checkTimeAndSubjectConfliction(): boolean
+ instanceScopeOp () - checkCapacityConfliction(): boolean

29 30

31 32

2.2. Define Methods Content


• What is a method? 1. Create Initial Design Classes
• Describes operation implementation
2. Define Operations/Methods
• Purpose
• Define special aspects of operation implementation
3. Define Relationships Between Classes
• Things to consider: 4. Define States
• Special algorithms 5. Define Attributes
• Other objects and operations to be used
6. Class Diagram
• How attributes and parameters are to be implemented
and used
• How relationships are to be implemented and used

31 32

8
33 34

Class Relationships 3.1. What is an Association?


• Association • The semantic relationship between two or more
classifiers that specifies connections among
their instances
• Aggregation • A structural relationship, specifying that objects
of one thing are connected to objects of another
• Composition

<<entity>> <<entity>> <<entity>>


CourseInfo StudyHistory SubjectInfo
• Inheritance
• Dependency

33 34

35 36

Finding Association 3.1.1. What Are Roles?


Communication Diagram
PerformResponsibility • The “face” that a class plays in the association
:Client :Supplier

Link <<entity>> <<entity>> <<entity>>


CourseInfo. Instructor Lecturer Department
Client Supplier Department Head

Class Diagram
Role Name
Client 0..* 0..* Supplier
<<entity>>
PerformResponsibility() SubjectInfo

Association
Prerequisites
Relationship for every link!

35 36

9
37 38

3.1.2. What Is Multiplicity? Multiplicity Indicators


• Multiplicity is the number of instances one class Unspecified
relates to ONE instance of another class.
Exactly One 1
• For each association, there are two multiplicity
decisions to make, one for each end of the Zero or More 0..*
association.
Zero or More *
• For each instance of Professor, many Course Offerings
may be taught. One or More 1..*
• For each instance of Course Offering, there may be either
one or zero Professor as the instructor. Zero or One (optional value) 0..1

instructor Specified Range 2..4


Lecturer CourseInfo.
0..1 0..* Multiple, Disjoint Ranges 2, 4..6

37 38

39 @Nguyễn Thị Thu Trang, trangntt@soict.hust.edu.vn 40

Java
What Does Multiplicity Mean? implementation
• Multiplicity answers two questions:
//InsuranceCompany.java file
• Is the association mandatory or optional? public class InsuranceCompany
{
• What is the minimum and maximum number of // Many multiplicity can be implemented using Collection
private List<InsuranceContract> contracts;
instances that can be linked to one instance?

/* Methods */
<<entity>> <<entity>>
}
0..* 1 // InsuranceContract.java file
CourseInfo. Subject
public class InsuranceContract
0..* {
private InsuranceCompany refers_to;
Prerequisites 0..3
/* Methods */
}

39 40

10
41 42

3.1.3. Association Types Review: What Is Aggregation?


• Association Car Driver
• use-a
• A special form of association that models a
• Objects of one class are associated with objects of whole-part relationship between an aggregate
another class (the whole) and its parts
• Aggregation Car Door • An aggregation is an “is a part-of” relationship.
• has-a/is-a-part • Multiplicity is represented like other associations.
• Strong association, an instance of one class is made up
Whole/aggregate Part
of instances of another class
• Composition
• Strong aggregation, the composed object can’t be
shared by other objects and dies with its composer <<entity>> <<entity>>
CourseInfo. CourseRegistrationInfo
• Share life-time Car Body 0..*
1

41 42

43

Review: What is Composition? “Register for course” Use case


• A special form of aggregation with strong ownership CourseInfo 1 Schedule
and coincident lifetimes of the part with the 0..*
aggregate.
• The whole “owns” the part and is responsible for the
creation and destruction of the part. 1
CourseRegistrationForm CourseRegistrationController
• The part is removed when the whole is removed. 1

• The part may be removed (by the whole) before the whole is
removed.

Whole Part

44

43 44

11
45 @Nguyễn Thị Thu Trang, trangntt@soict.hust.edu.vn 46

Association or Aggregation? Aggregation – Java implementation


• If two objects are tightly bound by a whole-part
class Car {
relationship private List<Door> doors;
• The relationship is an aggregation. Car(String name, List<Door> doors) {
this.doors = doors;
Car Door
}
1 0..2,4
public List<Door> getDoors() {
• If two objects are usually considered as
return doors;
independent, although they are often linked }
• The relationship is an association. }
Car Door

1 0..2,4
When in doubt, use association.

45 46

@Nguyễn Thị Thu Trang, trangntt@soict.hust.edu.vn 47 48

Composition – Java implementation 3.1.4. Navigability


final class Car { • Indicates that it is possible to navigate from an associating
// For a car to move, it need to have a engine. class to the target class using the association
private final Engine engine; // Composition
//private Engine engine; // Aggregation

Car(Engine engine) {
this.engine = engine;
<<control>>
} CourseRegistrationController

// car start moving by starting engine


public void move() {
//if(engine != null)
{
engine.work();
System.out.println("Car is moving "); <<entity>>
} CourseInfo
class Engine {
} // starting an engine
} public void work() {
System.out.println("Engine of car has been started ");
}
}

47 48

12
49 50

Navigability: Which Directions Are Really Example: Navigability Refinement


Needed? • Total number of Schedules is
small, or
• Explore interaction diagrams • Never need a list of the
Schedule + primaryCourses CourseInfo.
Schedules on which the
• Even when both directions seem required, one CourseInfo appears 0..* 0..4
may work
• Navigability in one direction is infrequent • Total number of CourseInfo is
• Number of instances of one class is small small, or
• Never need a list of CourseInfo
Schedule + primaryCourses CourseInfo.
Schedule + primaryCourses CourseInfo on a Schedule
0..* 0..4
0..* 0..4

?
• Total number of CourseInfo and
Schedules are not small
• Must be able to navigate in both
directions Schedule + primaryCourses CourseInfo.
Schedule + primaryCourses CourseInfo Schedule + primaryCourses CourseInfo
0..* 0..4
0..* 0..4 0..* 0..4

49 50

51 52

3.2. Dependency Dependencies vs. Associations


• Associations are structural
• What Is a Dependency?
relationships
• A relationship between two objects
• Dependencies are non-structural
Client Supplier relationships Supplier2

• In order for objects to “know


each other” they must be visible
• Purpose
• Local variable reference
• Determine where structural relationships are NOT Client
required • Parameter reference Dependency
• Global reference
• Things to look for :
• Field reference Association
• What causes the supplier to be visible to the client
Supplier1

51 52

13
53 54

Associations vs. Dependencies in


3.2.1. Local Variable Visibility
Collaborations
• An instance of an association is a link • The op1() operation contains a local variable of
• All links become associations unless they have type ClassB
global, local, or parameter visibility
ClassA
• Relationships are context-dependent
+ op1 ( )
• Dependencies are transient links with:
• A limited duration
• A context-independent relationship
ClassB
• A summary relationship
A dependency is a secondary type of relationship in that it doesn't tell
you much about the relationship. For details you need to consult the
collaborations.

53 54

55 56

3.2.2. Parameter Visibility 3.2.3. Global Visibility


• The ClassB instance is passed to the ClassA • The ClassUtility instance is visible because it is
instance global
ClassA
ClassA
+ op1 ([in] aParam : ClassB) + op1 ( )

ClassB
ClassB

+ utilityOp ( )

55 56

14
57 58

Identifying Dependencies: Considerations 3.3. Generalization


• Permanent relationships — Association (field visibility) • A relationship among classes where one class
• Transient relationships — Dependency shares the structure and/or behavior of one or
• Multiple objects share the same instance more classes.
• Pass instance as a parameter (parameter visibility)
• Make instance a managed global (global visibility)
• Defines a hierarchy of abstractions where a
• Multiple objects don’t share the same instance (local
subclass inherits from one or more superclasses.
visibility) • Single inheritance
• How long does it take to create/destroy? • Multiple inheritance
• Expensive? Use field, parameter, or global visibility • Is an “is a kind of” relationship.
• Strive for the lightest relationships possible

57 58

59 60

Example: Single Inheritance Content


• One class inherits from another 1. Create Initial Design Classes
Ancestor
Account 2. Define Operations/Methods
- balance
Superclass - name 3. Define Relationships Between Classes
(parent) - number

+ withdraw() 4. Define States


+ createStatement()

Generalization 5. Define Attributes


Relationship
6. Class Diagram
Subclasses
(children)
Savings Checking

Descendents

59 60

15
61 62

4. Define States What is a State Machine?


• A directed graph of states (nodes) connected by
• Purpose
transitions (directed arcs)
• Design how an object’s state affects its
• Describes the life history of a reactive object
behavior
Guard Condition
• Develop state machines to model this behavior
Event Activity
• Things to consider:
State1 State2
Event(args)[guard condition]/activity
• Which objects have significant state?
• How to determine an object’s possible states?
Transition
• How do state machines map to the rest of the
State State
model?

61 62

63 64

Pseudo States Identify and Define the States


• Initial state Initial State
• The state entered when an object • Significant, dynamic attributes
is created The minimum number of students per course is 3
State1
• Mandatory, can only have one initial numStudents >=3 numStudents < 3
state Opened Closed
• Choice
Choice
• Dynamic evaluation of subsequent
guard conditions • Existence and non-existence of certain links
• Only first segment has a trigger
Lecturer Link to Professor Link to Professor
• Final state Final State exists doesn’t exist
• Indicates the object’s end
State2 0..1 Assigned Unassigned
of life 0..*
• Optional, may have more than one CourseInfo.

63 64

16
65 66

Identify the Transitions


Identify the Events
• For each state, determine what events cause
• Look at the class interface operations transitions to what states, including guard
conditions, when needed
CourseInfo. 0..*
• Transitions describe what happens in response to
Lecturer
+ addLecturer() 0..1 the receipt of an event
+ removeLecturer()
CourseInfo 0..*
Lecturer
+ addLecturer() 0..1
+ removeLecturer()

Events: addLecturer,
removeLecturer Unassigned

removeLecturer addLecturer

Assigned

65 66

67 68

Add Activities Example: State Machines


• Entry StateA addStudent / numStudents = numStudents + 1

/ numStudents = 0
• Executed when the state
removeStudent [numStudents >0]/ numStudents = numStudents - 1
Entry/anAction
Unassigned
is entered
closeRegistration [numStudents<3]

addLecturer Canceled
cancel
• Do do/ Send cancellation notices

• Ongoing execution removeLecturer [ numStudents = 30 ]


cancel

Full
StateB StateC
Do/anActivity Exit/someAction
• Exit
• Executed when the state addStudent /
numStudents = numStudents + 1
closeRegistration [ has Professor assigned ]

is exited Assigned closeRegistration[ numStudents >= 3 ] Committed


do/ Generate class roster

removeStudent[ numStudents > 0] / numStudents = numStudents - 1

67 68

17
69 70

Which Objects Have Significant State? How Do State Machines Map to the Rest of the Model?

• Objects whose role is clarified by state • Events may map to operations


transitions • Methods should be updated with state-specific
information
• Complex use cases that are state-controlled
• States are often represented using attributes
• It is not necessary to model objects such as:
• This serves as input into the “Define Attributes” step
• Objects with straightforward mapping to
CourseInfo.
implementation
- numStudents
• Objects that are not state-controlled + addStudent()
• Objects with only one computational state
addStudent / numStudents = numStudents + 1
Opened Closed

[numStudents<10] [numStudents>=10]

69 70

71 72

Content Review: What Is an Attribute?


<<stereotype>>
1. Create Initial Design Classes ClassName

2. Define Operations/Methods Attribute : Type = InitValue


Attribute : Type = InitValue
Attribute : Type = InitValue
3. Define Relationships Between Classes
4. Define States <<entity>>
CourseInfo.
5. Define Attributes courseID: String
description: String
6. Class Diagram attribute startDate: DateTime
endDate: DateTime
lecturer: Lecturer
location: String

71 72

18
73 74

5.1. Finding Attributes 5.1. Finding Attributes (2)


• Properties/characteristics of identified • Examine method descriptions
classes • Examine states
• Information retained by identified classes • Examine any information the class itself
• “Nouns” that did not become classes needs to maintain
• Information whose value is the important thing
• Information that is uniquely "owned” by an
object
• Information that has no behavior

73 74

75 76

5.2. Attribute Representations 5.3. Derived Attributes


• Specify name, type, and optional default value • What is a derived attribute?
• attributeName : Type = Default • An attribute whose value may be calculated based on
• Follow naming conventions of implementation the value of other attribute(s)
language and project • When do you use it?
• Type should be an elementary data type in • When there is not enough time to re-calculate the value
every time it is needed
implementation language
• When you must trade-off runtime performance versus
• Built-in data type, user-defined data type, or user-
memory required
defined class
• Specify visibility
• Public: + Private: - Protected: #

75 76

19
77 78

Example: Define Attributes Content


<<entity>> <<boundary>>
Schedule CourseRegistrationForm
<<controll>>
CourseRegistrationController
1. Create Initial Design Classes
- scheduleID: int
- day: String
- courseID: String
- studentID: String
- courseID: String 2. Define Operations/Methods
- studentID: String
- teachingPeriod: int
3. Define Relationships Between Classes
4. Define States
<<entity>> <<entity>> <<entity>>
StudyHistory CourseInfo. SubjectInfo.
5. Define Attributes
- historyNo: int - courseID: String - subjectID: String
- pass: boolean
- description: String
- startDate: DateTime
- subjectName: String
- goal: String
6. Class Diagram
- result: int
- endDate: DateTime - description: String
- studentID: String
- studentName: String - lecturer: Lecturer - numberOfCredits: int
- location: String

77 78

79 80

Class diagram for


6. Class diagram
Register for course UC
• Static view of a system
• When modeling the static view of a system,
class diagrams are typically used in one of
three ways, to model:
• The vocabulary of a system
• Collaborations
• A logical database schema

79 80

20
81

Review: What Is a Package? Review points: Classes


• Clear class names
• A general purpose mechanism for organizing
elements into groups. • One well-defined abstraction

• A model element that can contain other model • Functionally coupled attributes/behavior
elements. • Generalizations were made
• A package can be used: • All class requirements were addressed
• To organize the model under development • Demands are consistent with state machines
• As a unit of configuration management • Complete class instance life cycle is described
• The class has the required behavior
University
Artifacts

81 82

Review points: Operations Review points: Attributes


• Operations are easily understood • A single concept
• Descriptive names
• State description is correct
• All attributes are needed by Use-Case
• Required behavior is offered Realizations
• Parameters are defined correctly
• Messages are completely assigned operations
• Implementation specifications are correct
• Signatures conform to standards
• All operations are needed by Use-Case
Realizations

83 84

21
86

Review points: Relationships Question?


• Descriptive role names
• Correct multiplicities

85 86

87 88

Program documentation
Class design /**
* Parse XML data into a DOM representation, taking local resources and Schemas into account.
* @param inputData a string representation of the XML data to be parsed.
• Attribute design * @param validating whether to Schema-validate the XML data
* @return the DOM document resulting from the parse
• Type, description * @throws ParserConfigurationException if no parser could be created
* @throws SAXException if there was a parse error
• Operation design * @throws IOException if there was a problem reading from the string

• Operation Signature */
public static Document parseDocument(String inputData, boolean validating) throws
• Purpose/description of operation ParserConfigurationException, SAXException, IOException {
//Change to UnicodeReader for utf-8
• Purpose /description of each parameter ...
}
• Description of return value
• Error/Exception (when)
• Method design
• Special algorithm
• How to use parameters

87 88

22

You might also like