Upload
randy-connolly
View
11.568
Download
2
Embed Size (px)
DESCRIPTION
Course material from my Object-Oriented Development course.This presentation covers the design phase and focuses on a variety of software design principles.
Citation preview
DESIGNExamining the software design workflow
6
2
ANALYSIS5
INTRODUCTION1METHODOLOGIES2MODELS AND UML3OBJECT CONCEPTS4
SOFTWARE DESIGN6
Our Process3
Reminder of object-oriented development process we are following in this course is that there are four phases: Inception Elaboration Construction Transition
Each phase consists of one or more iterations of the following workflows: Requirements Analysis & Design Implementation Test
In this section, we are going to examine the design workflow principally in the context of the Elaboration and construction phases.
Inception Elaboration Construction Transition1 2 3 4 5 6 7 8
Requirements
Analysis
Design
Implementation
Test
Design Workflow4
In the analysis workflow, the requirements are analyzed in more detail, so as to begin the description of the internal structure and behavior of the proposed system.
In the design workflow, we more fully describe and model how the internal structure and behavior will be implemented. The design workflow is the primary modeling
activity of the last part of the elaboration and first half of the construction phases.
Source: Arlow and Neustadt, UML and the Unified Process (Addison-Wesley, 2002), p. 249-50.
Object-Oriented Design5
Our analysis model defines what we need to build. It doesn’t define how the system will be build
Object-oriented design determines how to build. Object-oriented design bridges the gap between
analysis and implementation. In the design phase, you :
add detail about user interface, specify data storage, add layers, re-evaluate the responsibilities spelled out in interaction
diagrams, add detail to class diagrams so as to create design classes,
and re-evaluate and re-factor your initial analysis model using best-practice
solutions and heuristic principles called patterns.
Source: Bennett, McRobb, and Farmer, Object-Oriented Systems Analysis and Design (McGraw Hill, 2002), p. 301.
Analysis versus Design6
The boundary between analysis and design can be quite vague; they often overlap.
Some software processes merge the analysis and design stages. In real iterative projects, after an initial design
model is created, the analysis model tends to become redundant and is no longer maintained.
for smaller projects (under 200 classes), the design model may be small enough to be understandable, so a separate analysis model may be unnecessary.
Source: Arlow and Neustadt, UML and the Unified Process (Addison-Wesley, 2002), p. 252-3.
System Design and Detailed Design
7
Design of systems takes place at two levels: System design
Also called software architecture design. Concerned with the overall architecture of the
system Detailed design
Also called class design Concerned with designing individual
components to fit this architecture.
Source: Bennett, McRobb, and Farmer, Object-Oriented Systems Analysis and Design (McGraw Hill, 2002), p. 305.
What is Software Architecture?
8
The system design of an application is also referred to as software architecture.
Software architecture is a shared understanding of a system's design by the developers on a project. Commonly this shared understanding is in the form of
the major components of the system and how they interact.
Two key aspects: It is the highest-level breakdown of a system into its
parts. It is about early decisions that are hard to change
after the system is implemented.
Source: Martin Fowler, Patterns of Enterprise Application Architecture (Addison-Wesley, 2003), p. 2.
System Design9
In system/architectural design, you define the larger parts of the system and how they relate. That is, system design is focused on
making high-level decisions concerning the overall structure of the system.
This is accomplished by identifying layers (also called sub-systems) and allocating classes to them.
Layering10
Layering is perhaps the most common way to architect a software system.
Layering is a way of organizing your software design into groups of classes that fulfill a common purpose.
Source: Frank Buschmann et al, A Pattern of Systems (Wiley, 1996), p. 31-51.
Layering11
The goal of layering is to distribute the functionality of your software among classes, so that the coupling of a given class is minimized. While a layer may have dependencies to
another layer’s interface, it should be independent of other layer's implementation.
We want to avoid having late changes to a class "ripple" (cause changes) to a host of other classes.
Layering can thus increase the modularity (and thus maintainability) of your system. Different layers can be constructed by different
team members.
Source: Frank Buschmann et al, A Pattern of Systems (Wiley, 1996), p. 31-51.
Layering12
The essential principle of layering is that any element within a layer depends only on other elements "beneath" it. The top layers typically contain either the
most abstraction, or the most variable elements.
Each layer should be loosely coupled to the layers underneath.
Source: Eric Evans, Domain-Driven Design (Addison-Wesley, 2003), p. 69.
Layer 1
Layer 2
Layer 3
Layer 4
Open versus Closed Architecture
13
Layer architectures may be open or closed. Closed architecture minimizes the
dependencies between layers and makes for more independent layers. That is, each layer is strongly encapsulated.
Source: Bennett, McRobb, and Farmer, Object-Oriented Systems Analysis and Design (McGraw Hill, 2002), p. 326.
Open versus Closed Architecture
14
Open architecture is more efficient but less maintainable due to the increased dependencies.
Theoretically, a closed layer architecture is best, but open-layer architectures are much easier to create.
Layer 1
Layer 2
Layer 3
Layer 4
Layer 1
Layer 2
Layer 3
Layer 4Arrows indicate message flow
Source: Bennett, McRobb, and Farmer, Object-Oriented Systems Analysis and Design (McGraw Hill, 2002), p. 326.
Closed layer architecture Open layer architecture
Common Layer Architectures
15
Presentation
Source: Bennett, McRobb, and Farmer, Object-Oriented Systems Analysis and Design (McGraw Hill, 2002), p. 328-30.
Business Logic
Three layer architecture
Data Access
Presentation
Application
Four layer architecture
Domain
Data Access
View
Controller
MVC architecture
Model
Boundary
Control
BCE architecture
Entity
Common Layer Architectures I
16
Presentation Layer Responsible for showing information to the user
and interpreting the user's commands. Business Layer
Contains all business logic. Data Access/Persistence Layer
Responsible for interacting with external data sources. All database related code should reside here.
Data Access
Business
Presentation
Common Layer Architectures II
17
Boundary Boundary layer refer to any classes that interact
directly with the actors. Should only communicate with Control layer classes
Entity Entity layer contain classes that represent objects
in the problem domain. Should have no knowledge of Boundary or Control
classes. Control
Control layer classes coordinate between the boundary and entity layers.
Represent the application logic Often, each use case will have a control class
Entity
Control
Boundary
ViewCustomerList
«boundary»ViewCustomerList
Customer
«entity»Customer
«control»CustomerListController
CustomerListController
Common Layer Architectures III
18
Presentation Layer Responsible for showing information to
the user and interpreting the user's commands.
Application Layer Defines the job the software is supposed
to do and directs the domain objects. Domain Layer
Responsible for representing concepts of the business.
Infrastructure Layer Provides technical capabilities that
support the higher layers (e.g., persistence, web services, general widget drawing, security, etc).
Source: Eric Evans, Domain-Driven Design (Addison-Wesley, 2003), p. 70.
Infrastructure
Domain
Application
Presentation
Common Layer Architectures IV
19
Presentation Layer Responsible for showing information to the
user and interpreting the user's commands.
Presentation Helper Layer This layer hides all the complexity of the
application layer and it is adapted to the specific presentation layer implementation .
Service Layer The service layer provides a layer of
services to the presentation layer that it can use.
Domain Layer Responsible for representing concepts of
the business. This layer focuses on concepts or entities rather than use cases.
Persistence/Data Access Layer The persistence layer encapsulates the
data tier.Source: Jimmy Nilsson, "A Pure Object-Oriented Object Model," www.vb2themax.com
Persistence
Domain
Service
Presentation Helper
Presentation
Common Layer Architectures V
20
UI Component Layer Responsible for showing information to the user and
interpreting the user's commands using UI components (windows forms, web pages, user controls, etc)
UI Process Layer Handles validation and navigation between UI components.
Business Process Layer Business processes reflect the macro-level activities that the
business performs. Examples include order processing, customer support, and procurement of materials. These business processes are encapsulated by business workflow components that orchestrate one or more domain objects to implement a business process.
Domain/Business Objects Layer Data Access Components
Data access components isolate the business layer from the details of the specific data storage solution. Each DAC might provide CRUD (create, retrieve, update, and delete) capabilities for its data source.
Data Access Helper Common helper classes used by the DACs.
InfrastructureSource: Jimmy Nilsson, "A Pure Object-Oriented Object Model," www.vb2themax.com
Data Access Helper
Business Process
UI Process
UI Component
Domain
Data Access ComponentsIn
frast
ruct
ure
Diagramming Layers21
«layer»User Interface
«boundary»Client List
«boundary»Portfolio List
«boundary»Client Details
«traces»
«layer»Controllers
Class Design22
Concerned with the detailed design of the classes in the layers and their interactions.
The result will be a detailed specification of the attributes and operations of all the classes.
Customer
-m_name: String-m_address: String-m_phone: String#numCustomers: int
+getName(): String+getPhone(): String+setName(name: String): void+setPhone(phone: String): void#getNumCustomers(): int
Customer
Analysis class
Design class
Class Design23
The static class diagram is always at the focus of our analysis and design activities, since it indicates what will be implemented. As part of the analysis phase, one may have
created several interaction diagrams for most of the important scenarios in each use case.
As these interaction diagrams are developed, we need to add the behaviors necessary to model the responsibilities in these scenarios. This may be done as part of the analysis model Or it may be done now in the design phase
Class Design24
A newly-developed system will be extended many times over its life. Thus, merely designing an implementation
that meets current requirements is not sufficient.
The design must be flexible enough to permit extension and reuse.
Source: Charles Richter, Designing Flexible Object-Oriented Systems with UML (Macmillan, 1999), p. 127.
Symptoms of Poor Design25
Rigidity The design is hard to change
Fragility The design is easy to break
Immobility The design is hard to reuse
Repetition The design is only practical using copy and
paste
Source: Robert C. Martin, Agile Software Development (Prentice Hall, 2003), p. 85.
Class Design Principles26
Completeness and Sufficiency Primitiveness High Cohesion Low Coupling
Completeness and Sufficiency
27
Completeness refers to giving users of a class the services they expect. Users tend to make assumptions about the
services from the name and semantics of a class. e.g., a Client class will be expected to have methods
for accessing/setting a client’s name, while a BankAccount class will be expected to have a Withdrawal method.
Sufficiency refers to the fact all methods of a class are entirely focused on realizing the intent behind the class. A class should not surprise a user. It should
contain the expected methods and no more. Sufficiency is thus about keeping a class as
simple and focused as possible.
Source: Arlow and Neustadt, UML and the Unified Process (Addison-Wesley, 2002), p. 261.
Primitiveness28
Methods should be designed to offer a single primitive, atomic and unique service. A class should not offer multiple ways of
doing the same thing. Your aim is that classes should make
available the simplest and smallest possible set of methods necessary to implement the behavior required by class.
Source: Arlow and Neustadt, UML and the Unified Process (Addison-Wesley, 2002), p. 262.
+deposit(in value)
BankAccount
+deposit(in value)+depositTwice(in value1, in value2)
BadBankAccount
BankAccount ba = new BankAccount();ba.deposit(300);ba.deposit(1200);
BadBankAccount ba = new BadBankAccount();ba.depositTwice(300, 1200);
Yes! No!
High Cohesion29
Cohesion is a measure of the diversity of an class's features. The less diverse its features are, the more
cohesive the class. A highly cohesive class represents a single
abstraction / concept / activity / responsibility. Each class in a design should be as
cohesive as possible. That is, its responsibilities should be as strongly-
related and focused as possible. Cohesive classes are generally easier to understand,
reuse and maintain.
Source: Charles Richter, Designing Flexible Object-Oriented Systems with UML (Macmillan, 1999), p. 128.
Cohesion30
A class with low cohesion tends to cause these problems: More difficult to understand Harder to reuse, and maintain More possibilities for bugs since more affected by change
Source: Charles Richter, Designing Flexible Object-Oriented Systems with UML (Macmillan, 1999), p. 129.
+getName()+getPhone()+printName()+calculatePension()+calculateTax()+displayChildren()+displayBenefits()
Employee low cohesionHow many abstractions does this class contain?
-accountNo-lastname-firstname-address-balance
CustomerAccount low cohesionHow many abstractions does this class contain?
Cohesion31
In classes with low cohesion, there is an assumption that two (or more) abstractions in the class are always in a one-to-one-relationship, which can cause problems later. Similar to rule against transitive
dependencies in database normalization. You may have to specialize the class along
different dimensions based on the different abstractions.
-accountNo-lastname-firstname-address-balance
CustomerAccount
Separate the two abstractionsAccountCustomer
1..*1
Low Cohesion and Inheritance
32
Account
Cash Account Margin AccountInidividualAccount
InstitutionalAccount
Account
Cash Account Margin AccountInidividualAccount
InstitutionalAccount
Individual CashAccount
Individual MarginAccount
InstitutionalMargin Account
Institutional CashAccount
Problems when we further specialize the classes
How many abstractions does each subclass contain?
High Cohesion and Inheritance
33
AccountCustomer
1..* *
AccountCustomer
1..* *
Cash Account Margin AccountInidividualAccount
InstitutionalAccount
Separate the two abstractions
Then specialize the two abstractions
Low Coupling34
Coupling is a measure of the interconnectedness of a class to other classes. That is, coupling occurs when one class
depends on another in some way. The greater the coupling, the greater the
interdependence among classes. When classes are highly coupled, changes in one
class affect all the other classes. As coupling is reduced, a design will become
more maintainable and extensible. “coupling is your worst enemy” [Arlow & Neustadt,
p. 263]
Source: Charles Richter, Designing Flexible Object-Oriented Systems with UML (Macmillan, 1999), p. 128.
Coupling35
:Menu :House : Room
<< create >>
initialize()
:Menu :House : Room
<< create >>
initialize()
Menu is coupled to two other classes
Now Menu is coupled to just one class
Coupling Example36
: Register p : Payment : Sale
2: addPayment() 3: new()1: makePayment()
lower coupling
: Register p : Payment
: Sale
2: new()
3: addPayment()
1: makePayment()
higher coupling
Coupling37
Of course, some coupling is necessary; otherwise the classes don’t interact.
There is no rule for how much coupling is too much. One thing you can look for is “finger”
effects in your sequence diagram (see next slide); better to have “stair” effects.
Stair vs Finger in Sequence Diagrams
38
Object1 Object2 Object3 Object4 Object5 Object6
Message1
Message2
Message3
Message4
Message5
Object1 Object2 Object3 Object4 Object5 Object6
Message1
Message2
Message3
Message4
Message5
Finger
Stair
Indicative of high coupling
Indicative of low coupling
Types of Coupling39
Some of the forms of coupling are: interaction coupling identity coupling representational coupling subclass coupling
Source: Charles Richter, Designing Flexible Object-Oriented Systems with UML (Macmillan, 1999), p. 133.
Interaction Coupling40
A measure of the number of message types an object must send to another object and the number of parameters passed with those messages. Should try to reduce interaction coupling in order to
increase object reusability and to reduce number of potential changes in other classes if a class’s interface changes.
Source: Bennett, McRobb, and Farmer, Object-Oriented Systems Analysis and Design (McGraw Hill, 2002), p. 352-3.
MyDataAccess da = new MyDataAccess();
da.setName("wine");da.setExtension("mdb");da.setType("Microsoft Access");da.setDriverAccess("odbc");da.setDriverType("access");
da.runSql(strSQL, READ_ONLY, READ_FORWARD, DYNAMIC_CURSOR, REPLICATION_ON, LOGGING_YES, USE_OLAP)
* Illustrates high interaction coupling if all these messages must be sent before runSql message
**
Illustrates high interaction coupling if all these parameters must be used as part of the runSql message
Identity Coupling41
Refers to the level of connectivity of a design If one object holds a reference / pointer to
another object, that object knows the identity of the other, and therefore, exhibits identity coupling.
You can reduce identity coupling by : eliminating unnecessary associations from your
class diagram by implementing associations in only one
direction if bidirectional associations are unnecessary.
Source: Charles Richter, Designing Flexible Object-Oriented Systems with UML (Macmillan, 1999), p. 133.
Identity Coupling42
+addRoom()+getRoom()
-m_rooms : Vector
House
+setHouse()
-m_house : House
Room
1 *
has
This example has higher identity coupling. House knows the identity of rooms (it has a room collection) and room knows the identity of its house (it has a pointer to house).
We may need this identity coupling (perhaps we also have a master list of Rooms that we need to examine independently of their house containers),But if we don't then we should eliminate bidirectional association.
+addRoom()+getRoom()
-m_rooms : Vector
House Room
1 *
hasThis example has less identity coupling. House knows the identity of rooms (it has a room collection) but room does not know the identity of its house.
Higher coupling
Lower coupling(preferred)
Representational Coupling43
Classes should not depend on the specific representation / implementation details of another class. e.g., accessing public attributes of a class results in a
very high-degree of representational coupling. Low representational coupling enables:
prototyping using frameworks and stubs easier standardization (easier to standardize interfaces
than implementations) Extensibility
Representational coupling can be reduced by making attributes private, and using accessor and mutator methods (getters and setters) for those attributes.
Representational Coupling44
+name : String+quantity : int
Item
+getName() : String+setName() : void+getQuantity() : int+setQuantity() : void
-name : String-quantity : int
Item
Item abc = new Item();abc.name = "towel";abc.quantity = 3;
Item abc = new Item();abc.setName("towel");Aabc.setQuantity(3);
High coupling
Low coupling(preferred)
Subclass Coupling45
Inheritance is the strongest form of coupling! When an object refers to a subclass object through a
subclass reference, rather than through a more general superclass reference, you have subclass coupling.
A client should try to refer to the most general class possible, thereby decoupling the client from the specific subclasses.
Source: Charles Richter, Designing Flexible Object-Oriented Systems with UML (Macmillan, 1999), p. 134.
Client Superclass
Subclass 1 Subclass 2
Client Superclass
Subclass 1 Subclass 2
High coupling Low coupling(preferred)
Subclass Coupling46
Obviously you do need to create instances of subclasses. Later, we will learn about the Factory pattern
as a way to reduce subclass coupling. As well, you should aim to structure your
code so that only a small portion of the application deals with the subclass references (such as those to instantiate the subclasses), whereas the rest of the application deals only with general superclass types.
Subclass Coupling47
...public void addRoom(Room r){ m_rooms.addElement(r);}
...public Room createRoom(int roomType, ...){ if (roomType == Room.KITCHEN) return new Kitchen( ... ); else if (roomType == Room.BEDROOM) return new Bedroom( ... );}
HouseControlRoomCreator
...public void newRoom(int roomType, ...){ ControlRoomCreator crc = new ControlRoomCreator(); Room r = crc.createRoom(roomType) ; m_house.addRoom( r );}
ControlHouse
+addRoom()
-m_rooms
House
Room
Kitchen BedroomControlHouse
BoundaryHouse ControlRoomCreator
Coupling Review48
It is not high coupling per se that is so problematic, but high coupling to classes that are unstable (i.e., change frequently). high coupling to stable and pervasive
elements such as the standard Java libraries for string manipulation, collections, etc is not that problematic.
Thus, in particular, avoid high coupling for classes that change their interface or implementation frequently.
Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 231
Additional Class Design Guidelines
49
Mapping responsibilities using Information expert and creator Avoid public fields Prevent misuse by client Establish invariants in constructor Refactor duplicate code Separate interface from implementation Minimize interface size Program to interface Controllers Replace Conditionals with Polymorphism Improve Cohesion or Coupling by Pure Fabrication Indirection Don’t Talk to Strangers Be Cautious with Inheritance Favour object composition over class inheritance
Design Guideline: Information Expert
50
Problem: how to assign responsibilities to objects?
Solution: Assign a responsibility to the class that has
the information necessary to fulfill the responsibility.
Larman calls this the Information Expert principle
Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 221-2
Who is the Information Expert?
51
-m_date-m_time
Sale
-quantity
Sales Detail
-description-price
Product
1
*
contains
* 1
described by
Who should have responsibility for calculating the grand total of the sale?
Who is the Information Expert?
52
: Sale : Sales DetailgetTotal()
: Product
getSubTotal()
getPrice()
+getTotal()
-m_date-m_time
Sale
+getSubTotal()
-quantity
Sales Detail
+getPrice()
-description-price
Product
1
*
contains
* 1
described by
Now each object is responsible for providing the data it owns.
Multiple Information Experts53
The fulfillment of a responsibility often requires information that is spread across different classes of objects Thus there are often several partial
information experts who will collaborate on the task of fulfilling the responsibility.
Design Guideline: Creator54
Problem: Who should be responsible for creating an object?
Solution: Assign class B the responsibility to create an
instance of class A if one or more of the following is true: B aggregates A objects B contains instances of A objects B has the initializing data that will be passed to A
when it is created. B thus is the creator of A objects
Larman calls this the Creator principle
Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 226
Who is the Creator?55
-m_date-m_time
Sale
-quantity
Sales Detail
-description-price
Product
1
*
contains
* 1
described by
Q: Who should have responsibility for creating the Sales Detail objects?
A: Since Sale aggregates Sales Detail, Sale should be the creator.
Design Guideline: Avoid Public Fields
56
There should not be non-final public data members Use properties/accessors and mutators
(getters and setters) instead. In languages that support properties (VB.NET,
C#), use properties rather than getters and setters.
For boolean values, use naming convention IsAttr() instead of getAttr()
Design Guideline: Prevent misuse by client
57
A well designed class should not allow a class to be misused by its clients. That is, mutators must ensure that data is being set
correctly. Parameters need to be checked for validity.private ArrayList _room;...public Room getRoomByIndex(int index){ return (Room)_rooms.get(index);}
private ArrayList _room;...public Room getRoomByIndex(int index){ if (index >= 0 && index <= _rooms.size()) return (Room)_rooms.get(index); else return null;}
How can this class be misused?
Solution #1
Using Assertions58
For languages (Java 1.4, C#) that support them, to help catch future bugs, use assertions to detect violations at run-time. An assertion is a boolean condition that must evaluate
to true. If the assertion is false, then an assertion exception is
thrown. Most environments allow you to turn assertion checking on or
off.private ArrayList _room;...public Room getRoomByIndex(int index){ assert index >= 0 && index <= _rooms.size(); if (index >= 0 && index <= _rooms.size()) return (Room)_rooms.get(index); else return null;}`
Solution #2
Design Guideline: Establish invariants in constructor
59
Invariants are data members that should not be modified in a class after they have been established/initialized. If a class uses mutators (setters) to establish an invariant, then
it is possible that future calls to the mutators will change the invariant.
Use a constructor to establish invariants.
Design Guideline: Establish invariants in constructor
60
public class Employee{ private int _key;
public void setKey(int key){ _key = key; }}
public class Employee{ private int _key;
public Employee(int key){ _key = key; }
public int getKey() { return _key; }}
Establish invariant using constructor (java)
Using mutator to establish invariant is unreliable.
public class Employee{ private int _key;
public Employee(int key){ _key = key; }
public int Key() { get { return _key; }}
Establish invariant using constructor (C#)
Design Guideline: Refactor Duplicate Code Segments
61
Duplicate code segments are a maintenance nightmare. Code needs to be refactored so that code
segments occur only once.
Design Guideline: Refactor Duplicate Code Segments
62
Approaches: Method invocation (duplication within single
class) Add a new method in same class that contains
duplicate code Inheritance (duplication within multiple
classes) Place duplicate code in a method in superclass. Won't work if classes already have separate
existing inheritance hierarchies. Delegation (duplication within multiple classes)
Create separate class with public method that contains duplicate code.
Design Guideline: Separate interface from implementation
63
When the functionality in a class can be implemented in different ways, separate the interface from the implementation.
Design Guideline: Separate interface from implementation
64
That is, use an interface to describe the interface; use a class to describe the implementation. This way, we could provide an alternate
implementation without disrupting existing code.
public interface List{ public int size(); public boolean isEmpty(); public void add(object item); public object get(int index); ...}
public class ArrayList implements List{ public int size() { return ... } public boolean isEmpty() { ... } ...}
public class Vector implements List{ public int size() { return ... } public boolean isEmpty() { ... } ...}
Design Guideline: Minimize Interface Size
65
Try to design a class so that it provides the functionality you need but whose public interface is as small as possible. Large numbers of methods and parameters
often indicate high levels of coupling and complexity.
Use objects to encapsulate a long list of parameters to a method.
Design Guideline: Minimize Interface Size
66
public Connection connectToDB(string driver, string connString, int accessRight, int ...){...}
public Connection connectToDB(ConnectionInfo ci){...}
public class ConnectionInfo{ private string _driver; private string _connString; private int _accessRight; ...}
Just right!
Too big!
Design Guideline: Program to interface
67
When an interface is available, program to it rather than to a particular concrete implementation. This way, if in the future, a different
implementation is used, fewer changes will be required.
Design Guideline: Program to interface
68
private ArrayList _room = new ArrayList();...public ArrayList getRooms(){ return _room;}...
public interface List{...}
public class ArrayList implements List{...}
public class LinkedList implements List{...}
private List _room = new ArrayList();...public List getRooms(){ return _room;}...
Programming to implementation – will require more changes if we modify implementation in the future
Programming to interface – more adaptable if we decide to use different implementation in the future.
Design Guideline: Replace Conditionals with Polymorphism
69
Problem: How to handle alternative responsibilities based on type
(i.e., conditional variation using if-then-else or case statements) ?
Problem with using conditional variation is that if a new variation arises, it requires modification of the if-then-else structures, usually in several places.
Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 326
m_roomType
getRoomType()
Room
// constructorpublic Room(int roomType) { m_roomType = roomType}public String getRoomType() { if (m_roomType == 1) return "Bedroom"; if (m_roomType == 2) return "Kitchen";}
Room abc = new Room(1);System.out.println( abc.getRoomType() );
less ideal
Design Guideline: Replace Conditionals with Polymorphism
70
Solution: When related alternatives or behaviors vary by type (class),
assign responsibility for the behavior, using polymorphism, to the types for which the behavior varies.
Thus, do not test for the type of an object and use conditional logic to perform varying alternatives based on type.
Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 326
getRoomType()
Room
getRoomType()
Bedroom
getRoomType()
Kitchen
...public String getRoomType() { return "Bedroom";}
...public String getRoomType() { return "Kitchen";}
public abstract String getRoomType();
Kitchen abc = new Kitchen();System.out.println( abc.getRoomType() );
better
Design Principle: Improve Cohesion or Coupling by Pure Fabrication
71
Problem: What object should have the responsibility, when
the solution offered by the Information Expert (for example) principle violates High Cohesion or Low Coupling (or some other) principles?
Solution: Assign a highly cohesive set of responsibilities to
an artificial class with low coupling that does not represent a problem domain concept.
Such a class is a pure fabrication of the designer's imagination: it does not relate to anything in the problem domain.
Larman calls this the Pure Fabrication principle.
Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 329
Pure Fabrication72
Suppose in our virtual street example, we wished to save our Houses, Rooms, Persons and Items that the user input in a database.
According to the information expert principle, who should be responsible for saving, for instance, the Rooms entered by the user?
According to the information expert principle, we should assign a responsibility to the class that has the information necessary to fulfill the responsibility.
Thus, according to the information expert principle, the Room class should be responsible for saving its information to a database, and the House class should be responsible for saving its information to a database, etc.
Pure Fabrication73
To save the information to a database may very well require a large number of supporting database operations or methods, none related to the concept of Room-ness or House-ness. Thus, each of our domain classes become much less cohesive.
As well, each of our domain classes will become coupled to the database interface (e.g., Java JDBC or Microsoft ADO). Thus, each of our domain classes become highly coupled to
something external. To solve the problem, we need to make up (that is, to
fabricate) a new class that will handle the database tasks.
Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 329
House Room Item
PersistantStorage
Design Principle: Indirection74
Problem: How to assign responsibility so as to avoid
direct coupling between two or more things. How to de-couple objects so that low coupling
is supported and reuse potential is high? Solution:
Assign the responsibility to an intermediate object to mediate between other components so that they are not directly coupled.
The intermediary creates an indirection between the other components.
Larman calls this the Indirection principle.
Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 332
Indirection75
In our last example, the PersistantStorage fabrication acts as an intermediary between the domain objects and the database.
Many of the other patterns we will look at are specializations of indirection.
"Most problems in computer science can be solved by another level of indirection." however, "Most problems in performance can
be solved by removing another layer of indirection" !
Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 333
Design Principle: Don't Talk to Strangers
76
Problem: How to design classes that are protected from
changes in other class's interfaces? That is, if an object has knowledge of the internal
structure of other objects, then it suffers from high coupling. How can an object use a service from an indirect object without being coupled to the internal structure of that object.
Solution: Don't rely on another class's knowledge of other
objects. Instead, assign the responsibility to a client's direct
object to collaborate with an indirect object. Larman calls this the Don't Talk to Strangers
principle.
Source: Craig Larman, Applying UML and Patterns , 1st Edition (Prentice Hall, 1998), p. 400
Don't Talk to Strangers77
// Returns the total number of holdings for the clientpublic int getNumHoldings(Client c){ int num = 0; for (int i=0; i<size(); i++) { Holding holding = m_holdings.get(i); if ( c.getID() == holding.getClient().getID() ) num++; } return num; }
m_stock: Stockm_client: Client
getClient(): ClientgetStock(): Stock
Holding
m_symbol: Stringm_value: double
getSymbol(): StringgetValue: double
Stock
m_id: intm_name: String
getID(): intgetName(): String
Client
m_holdings: Vector
getNumHoldings(): int
HoldingController
familiar object(Holding) stranger object
(Client)
itemName = house.getRoom(0).getItem(0).getName();
familiar object(house)
Message being sent to
stranger object(room) stranger object
(item)
Don't Talk to Strangers78
Observe the following constraints on what objects you should send messages to within a method: the this object a parameter of the method an attribute of this an element of a collection which is an attribute of this
an object created within the method The intent of these constraints is to avoid
coupling a client to knowledge of indirect objects and the object connections between objects.
Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 336
If not to strangers, then who?
79
Following these constraints requires adding new public operations to the "familiars" of an object.
Of course, this may not seem worth the bother. Certainly, try to avoid talking to a stranger of a stranger (e.g., second example on last slide).
// Returns the total number of holdings for the clientpublic int getNumHoldings(Client c){ int num = 0; for (int i=0; i<size(); i++) { Holding holding = m_holdings.get(i); if ( c.getID() == holding.getClientID() ) num++; } return num; }
Design Principle: Be Cautious with Inheritance
80
Inheritance is a powerful way to use polymorphism and reduce code duplication.
However, some potential problems with inheritance are It is the strongest form of coupling Encapsulation is weak within an generalization
hierarchy (changes in superclass ripple down to modify the subclasses).
Inheritance relationships are fixed at run-time. Sometimes aggregation is a better choice than
an ill-thought out inheritance hierarchy.
Example of Inheritance Problem
81
Employee
Manager Programmer
This looks okay, but it contains a semantic error. Can you see it?
Employee
Manager Programmer Randy : Programmer
«instance» Hint: What happens if we want to change Randy’s class to Manager at run-time?
Answer: is an employee just their job, or is a job a role that an employee has? That is, an employee has a job. A job is a role that an employee has, it is not a “kind of” employee. “Has a” indicates an aggregation relationship.
Source: Arlow and Neustadt, UML and the Unified Process (Addison-Wesley, 2002), p. 265-6.
Employee Job
Manager Programmer
1 *
has a
Now we can promote an employee simply by changing its job link at run-time.
Design Principle: Delegation over class inheritance
82
One way to deal with the problem of inheritance (weak encapsulation of subclasses) is to favour object composition and delegation over class inheritance if code reuse is your only goal in using inheritance. Use inheritance if there is a strong is a relationship;
otherwise, look at using object composition instead.
Is there a strong “is a” relationship between Rectangle and Window?
What happens when a new attribute, such as fill color, is added to Rectangle? Window will then inherit a characteristic which a Window does not have.
+open()+close()
Window
+calculateArea()
-width-height
Rectangle
This uses object delegation instead to handle the calculateArea request; it is somewhat analogous to letting the superclass handle the request, except here the request is delegated to another object it contains.
+calculateArea()
-width-height
Rectangle
+open()+close()+calculateArea()
-m_rect : Rectangle
Window
1
public int calculateArea() { return m_rect.calculateArea();}
What Next?83
At this point, you should have detailed interaction diagrams along with a detailed class diagram in which responsibilities have been mapped to class methods.
Depending upon the software process being used, the next step might be: implement the classes defined in the class diagram
and test. Then refine the classes using design patterns as separate iteration.
refine the classes in a second iteration through the design phase using design patterns, then implement and test.
Mapping Design to Code84
Your class diagram shows which methods and attributes need to be implemented. That is, by just looking at your class diagram,
you can create the attributes and the method stubs.
Your interaction diagrams show the messages that are sent between objects in response to a method invocation. That is, they show how a given method or
methods will be implemented. The sequence of these messages translates to
a series of statements in a method definition.
Order of Implementation85
Classes need to be implemented (and ideally, fully tested) from least-coupled to most-coupled. This will typically mean that you will
implement your basic domain classes first.
Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 311
Test-First Programming86
On of the precepts of Extreme Programming (XP) method is test-first programming, in which class testing code is written before the code to be tested. This ensures that testing gets done, but it
also helps clarify the design of the interfaces of a class.
This also creates a library of unit tests, which helps to verify correctness of a system.
Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 311