You are on page 1of 39

L6 – Design and Implementation

COMP3297 by Leo Yeung L6 – Design and Implementation 1


Topics covered

² Object-oriented design using the UML


² SOLID design principles
² Implementation issues
² Open source development

COMP3297 by Leo Yeung L6 – Design and Implementation 2


Design and implementation

² Software design and implementation is the stage in the


software engineering process at which an executable
software system is developed.
² Software design and implementation activities are
invariably inter-leaved.
§ Software design is a creative activity in which you identify
software components and their relationships, based on a
customer’s requirements.
§ Implementation is the process of realizing the design as a
program.

COMP3297 by Leo Yeung L6 – Design and Implementation 3


Object-oriented design using the UML

COMP3297 by Leo Yeung L6 – Design and Implementation 4


An object-oriented design process

² Structured object-oriented design processes involve


developing a number of different system models.
² They require a lot of effort for development and
maintenance of these models and, for small systems,
this may not be cost-effective.
² However, for large systems developed by different
groups, design models are an important communication
mechanism.

COMP3297 by Leo Yeung L6 – Design and Implementation 5


Process stages

² There are a variety of different object-oriented design


processes.
² Common activities in these processes include:
§ Step 1: Define the context and modes of use of the system;
§ Step 2: Design the system architecture;
§ Step 3: Identify the principal system objects;
§ Step 4: Develop design models;
§ Step 5: Specify object interfaces.

COMP3297 by Leo Yeung L6 – Design and Implementation 6


System overview
Wilderness weather station
1. The government of a country with large areas of wilderness decides to deploy several hundred
weather stations in remote areas.
2. Weather stations includes a number of instruments that measure weather parameters such as
the wind speed and direction, the ground and air temperatures, the barometric pressure and the
rainfall over a 24-hour period. Each of these instruments is controlled by a software system that
takes parameter readings periodically and manages the data collected from instruments.
Basic
1. The weather station system is responsible for collecting weather data, carrying out some initial
data processing and transmitting it to the data management system.
2. The data management and archiving system collects the data from all of the wilderness
weather stations, carries out data processing and analysis and archives the data.
3. The station maintenance system can communicate by satellite with all wilderness weather
stations to monitor the health of these systems and provide reports of problems.
Additional software functionality
1. Monitor the instruments, power and communication hardware and report faults to the
management system.
2. Manage the system power, ensuring that batteries are charged whenever the environmental
conditions permit but also ensuring that generators are shut down in potentially damaging
weather conditions, such as high wind.

3. Support dynamic reconfiguration where parts of the software are replaced with new versions
and where backup instruments are switched into the system in the event of system failure.
COMP3297 by Leo Yeung L6 – Design and Implementation 7
Step 1 - System context and interactions

² Understanding the relationships between the software


that is being designed and its external environment is
essential
² Understanding of the context also lets you establish the
boundaries of the system.

COMP3297 by Leo Yeung L6 – Design and Implementation 8


Context model

² A system context model is a structural model that demonstrates the


different systems in the environment of the system being developed.
Your system

Control
1 system 1

1 1..n
Weather 1 1..n Weather
information station
system
1 1..n

Satellite 1
1

System context for the weather station

COMP3297 by Leo Yeung L6 – Design and Implementation 9


Interaction model

² An interaction model is a dynamic model that shows how the system


interacts with its environment as it is used.
System overview Basic

Additional software functionality

(noun) (verb) System Weather station


Report Use case Report weather
weather
Actors Weather information system, Weather station
Report status
Weather Description The weather station sends a summary of the weather data that has
information been collected from the instruments in the collection period to the
system
weather information system. The data sent are the maximum,
Restart minimum, and average ground and air temperatures; the maximum,
minimum, and average air pressures; the maximum, minimum, and
Shutdown
average wind speeds; the total rainfall; and the wind direction as
sampled at five-minute intervals.
Reconfigure
Stimulus The weather information system establishes a satellite communication
link with the weather station and requests transmission of the data.
Control
Powersave
Response The summarized data is sent to the weather information system.
system
Comments Weather stations are usually asked to report once per hour but this
Remote frequency may differ from one station to another and may be modified
control in the future.
Weather station use cases Use case description - Report weather
COMP3297 by Leo Yeung L6 – Design and Implementation 10
Step 2 - Architectural design

² You identify the major components that make up the system and their
interactions, and then may organize the components using an
architectural pattern such as a layered or client-server model.
² The weather station is composed
of independent subsystems
that communicate by
broadcasting messages on a
common infrastructure.
«subsystem» «subsystem» «subsystem»
Listener Fault manager Configuration manager Power manager Data collection
model
Transmitter Receiver
Communication link

WeatherData
«subsystem» «subsystem» «subsystem»
Communications Data collection Instruments

High-level architecture of the weather station Architecture of data collection system

COMP3297 by Leo Yeung L6 – Design and Implementation 11


Step 3 - Object class identification

² There is no 'magic formula' for object identification. It relies on the


skill, experience and domain knowledge of system designers. Object
identification is an iterative process.
² Approaches to identification:
§ Use a grammatical approach based on a
natural language description of the system.
• Nouns à objects and attributes
• Verbs à operations or services
§ Use a scenario-based analysis. The objects, attributes and methods in
each scenario are identified.
§ Base the identification on tangible things in the application domain.
• object: e.g. aircraft, role: e.g. manager, events: e.g. requests, interactions:
e.g. meetings, locations: e.g. offices, organizational unit: companies
§ Design “implementation objects”, that are used to provide general
services such as searching and validity checking
COMP3297 by Leo Yeung L6 – Design and Implementation 12
Weather station object classes

² Object class identification:

- The basic interface of


the weather station to Encapsulates the
its environment. summarized data
- Reflects interactions from the instruments.
identified in the use-
case model.
Report
weather

Report status
Weather
information
system
Restart
Tips
Shutdown
1. Match use case
model
Reconfigure
2. Show what kinds
Control
system Powersave
of data included
Remote
control Application domain objects that are ‘hardware’ objects 3. Use meaningful
related to the instruments in the system. names
COMP3297 by Leo Yeung L6 – Design and Implementation 13
Step 4 - Design models

² Design models show the objects and object classes and


relationships between these entities.
² There are two kinds of design model:
§ Structural models describe the static structure of the system in
terms of object classes and relationships. (Done in step 2 & 3)
§ Dynamic models describe the dynamic interactions between
objects.
• Sequence models that show the sequence of object
interactions.
• State machine models that show how individual objects
change their state in response to events

COMP3297 by Leo Yeung L6 – Design and Implementation 14


Sequence models

² Show the sequence of object interactions that take place


Weather
information system

:SatComms :WeatherStation :Commslink :WeatherData

request (report)

acknowledge
reportWeather ()

acknowledge get (summary) summarize ()

send (report)

acknowledge
reply (report)

acknowledge

Sequence diagram describing data collection

COMP3297 by Leo Yeung L6 – Design and Implementation 15


State diagrams

² Show how objects respond to different service requests


and the state transitions triggered by these requests.

Weather station state diagram

COMP3297 by Leo Yeung L6 – Design and Implementation 16


Step 5 - Interface specification

² An interface is a description of the actions that an object can do.


² Designers should NOT include details of the data representation in
an interface design, as attributes are not defined in an interface
specification. Designers should only include operations to access
and update data.
² Same objects may have several interfaces.

«interface»
«interface» Remote Control
Reporting

startInstrument(instrument): iStatus
weatherReport (WS-Ident): Wreport stopInstrument (instrument): iStatus
statusReport (WS-Ident): Sreport collectData (instrument): iStatus
provideData (instrument ): string

Weather station interfaces


COMP3297 by Leo Yeung L6 – Design and Implementation 17
SOLID Design Principles

(Ref: Chapter 8-12 - Agile Software Development, Principles, Patterns, and Practices, PNIE, 1st Edition, by Martin, Robert C.,
published by Pearson, 2013)

COMP3297 by Leo Yeung L6 – Design and Implementation 18


What is SOLID?

² Single Responsibility Principle (SRP)


² Open Closed Principle (OCP)
² Liskov Substitution Principle (LSP)
² Interface Segregation Principle (ISP)
² Dependency Inversion Principle (DIP)

Clean Code

COMP3297 by Leo Yeung L6 – Design and Implementation 19


Single Responsibility Principle (SRP)

² “A class should have only one reason to change.”


§ A class should concentrate on doing one thing and one thing only.

More than one responsibility Separated Responsibilities

² Every time you create/change a class, you should ask


yourself:
How many responsibilities does this class have?

COMP3297 by Leo Yeung L6 – Design and Implementation 20


Single Responsibility Principle (SRP)

(Source: Ganesh Samarthyam)


COMP3297 by Leo Yeung L6 – Design and Implementation 21
Examples

² BAD: ² Problems:
§ Two responsibilities:
interface Modem {
public void dial(String pno); • Connection Management
public void hangup(); • Data Communication
public void send(char c);
public char recv();
} à Smell of Rigidity

COMP3297 by Leo Yeung L6 – Design and Implementation 22


Examples

² GOOD:
§ Separate into two interfaces
interface DataChannel {
public void send(char c);
public char recv();
}

interface Connection {
public void dial(String pno);
public void hangup();
}
Caution!
If the application is not changing in ways that cause two responsibilities, no
need to separate them. Otherwise, Smell of Needless Complexity

COMP3297 by Leo Yeung L6 – Design and Implementation 23


Open Closed Principle (OCP)

² “Software entities (classes, modules, functions, etc.)


should be open for extension, but closed for
modification.”
§ If the OCP is applied well, then further changes of that kind are
achieved by adding new code, not by changing old code that
already works.
² Idea: build the classes in a way that we able to extend
them by child classes and inheritance. Once you
created the class, it no longer needs to be changed.

COMP3297 by Leo Yeung L6 – Design and Implementation 24


COMP3297 by Leo Yeung L6 – Design and Implementation 25
Examples

public enum PaymentType = { Cash, CreditCard };


² BAD:
public class PaymentManager{
public PaymentType PaymentType { get; set; }
public void Pay (Money money){
if (PaymentType == PaymentType.Cash){
//some code here - pay with cash
}else{
//some code here - pay with credit card
}
}
}
² Problems:
§ Impossible to add a new Payment, e.g. Check, without modifying
PaymentManager.
§ Adding a new Payment to such an application means hunting for
every place that such switch statements(or if/else chains) exist
and adding the new Payment to each.
COMP3297 by Leo Yeung L6 – Design and Implementation 26
Examples

² GOOD:
§ Open for extension: Payment

public class Payment{


public virtual void pay(Money money){ pay()
// base class
}
}
§ Close for modification:
public class Cash:Payment{ Cash CreditCard Check
public override void pay(Money money){ … … …
// pay with cash pay() pay() pay()
} authorize() authorize()
}
public class CreditCard:Payment{
public override void pay(Money money){
// pay with credit card
}
}

COMP3297 by Leo Yeung L6 – Design and Implementation 27


Liskov Substitution Principle (LSP)

² “If for each object o1 of type S there is an object o2 of type T


such that for all programs P defined in terms of T, the behavior
of P is unchanged when o1 is substituted for o2 then S is a

??
subtype of T.”
?
Subtypes Must Be Substitutable For Their Base Types.

COMP3297 by Leo Yeung L6 – Design and Implementation 28


Examples
Bird

² BAD: ² Problems:
class Bird { Eagle Penguin § Penguin can’t fly.
let name: String
let flySpeed: Double § Doesn’t the IS-A
init(name: String, flySpeed: Double) {
self.name = name relationship hold?
self.flySpeed = flySpeed
}
}
class Eagle: Bird { }
class Penguin: Bird {
let swimSpeed: Double
init(name: String, flySpeed: Double, swimSpeed: Double) {
self.swimSpeed = swimSpeed
super.init(name: name, flySpeed: flySpeed)
}
}
let eagle = Eagle(name: "Eagle", flySpeed: 25)
// let penguin = Penguin(name: "Penguin",
// flySpeed: "can’t fly", swimSpeed: 10)
COMP3297 by Leo Yeung L6 – Design and Implementation 29
Examples (updated)
<<interface>> <<interface>>
CanFly Bird CanSwim
² GOOD:
Eagle Penguin

protocol CanFly { class Eagle: Bird, CanFly {


var flySpeed: Double { let flySpeed: Double
get } init(name: String, flySpeed: Double){
} self.flySpeed = flySpeed
protocol CanSwim { super.init(name: name)
var swimSpeed: Double { }
get} }
} class Penguin: Bird, CanSwim {
class Bird { let swimSpeed: Double
var name: String init(name: String, swimSpeed: Double){
init (name: String) { self.swimSpeed = swimSpeed
self.name = name super.init(name: name)
} }
} }

COMP3297 by Leo Yeung L6 – Design and Implementation 30


Interface Segregation Principle (ISP)

² "Many specialized interfaces are better than one


universal" or
² "Clients should not depend on methods that they do not
use."

COMP3297 by Leo Yeung L6 – Design and Implementation 31


Examples

² BAD: ² Problems:
interface Worker { § RobotWorker does not
void work();
void eat(); eat
}
ManWorker implements Worker { à Smell of Needless
void work() {…}; Complexity
void eat() {30 min break;};
} § Worker is a Polluted
RobotWorker implements Worker { Interface
void work() {…};
void eat() {//Not Appliciable
for a RobotWorker};
}

COMP3297 by Leo Yeung L6 – Design and Implementation 32


Examples
(updated)

² GOOD: <<interface>> <<interface>>


Workable Feedable
§ Split into two interfaces

interface Workable {
void work(); ManWorker RobotWorker
}
interface Feedable {
void eat();
}
ManWorker implements Workable, Feedable {
void work() {…};
void eat() {30 min break;};
}
RobotWorker implements Workable {
void work() {…};
}

COMP3297 by Leo Yeung L6 – Design and Implementation 33


Dependency Inversion Principle (DIP)

² “High-level modules should not depend on low-level


modules. Both should depend on abstractions.” and
² “Abstractions should not depend on details. Details
should depend on abstractions.”

COMP3297 by Leo Yeung L6 – Design and Implementation 34


Examples

² BAD:
class FilesystemStorage { DataHandler
func save(_ data: Data) ‹
// Create file->Save data locally
print("Saving locally")
}
} FilesystemStorage
class DataHandler {
let storage = FilesystemStorage()
func handle(_ data: Data) {
storage.save(data)
}
}
let handler = DataHandler()
handler.handle(Data())
² Problems:
§ DataHandler depends on FilesystemStorage. Dependency is
transitive. DataHandler is sensitive to changes all the way down.
COMP3297 by Leo Yeung L6 – Design and Implementation 35
(updated)

DataHandler
Examples
<<interface>>
² GOOD: Storage

protocol Storage {
func save(_ data: Data) Filesystem Cloud
} Storage Storage
class CloudStorage: Storage {
func save(_ data: Data) {
// Connect to cloud > Save in cloud
print("Saving in cloud")
} class DataHandler {
} let storage: Storage
class FilesystemStorage: Storage { init(storage: Storage){
func save(_ data: Data) { self.storage = storage
// Create file > Save data locally }
print("Saving locally") func handle(_ data: Data){
} storage.save(data)
} }
}
let storage = CloudStorage()
let handler = DataHandler(storage: storage)
handler.handle(Data())
COMP3297 by Leo Yeung L6 – Design and Implementation 36
Dependency Inversion Principle (DIP)

² Inversion of ownership:

Naive layering scheme

² Depend on Abstractions: Inverted Layers


§ No variable should hold a pointer or reference to a concrete class.
§ No class should derive from a concrete class.
§ No method should override an implemented method of any of its
base classes.
Any Exception?
COMP3297 by Leo Yeung L6 – Design and Implementation e.g. Java String 37
Summary for SOLID

Software inevitably changes/evolves over time (maintenance, upgrade)

² Single responsibility principle (SRP)


§ Every class should have only one reason to be changed
§ e.g. If class "A" has two responsibilities, create new classes "B" and "C" to
handle each responsibility in isolation, and then compose "A" out of "B"
and "C"
² Open/closed principle (OCP)
§ Every class should be open for extension (derivative classes), but closed
for modification (fixed interfaces)
§ e.g. Put the system parts that are likely to change into implementations
(i.e. concrete classes) and define interfaces around the parts that are
unlikely to change (e.g. abstract base classes)

38
Summary for SOLID

² Liskov substitution principle (LSP)


§ Every implementation of an interface needs to fully comply with the
requirements of this interface
§ Any algorithm that works on the interface, should continue to work for any
substitute implementation
² Interface segregation principle (ISP)
§ Keep interfaces as small as possible, to avoid unnecessary dependencies
§ Ideally, it should be possible to understand any part of the code in
isolation, without needing to look up the rest of the system code
² Dependency inversion principle (DIP)
§ Instead of having concrete implementations communicate directly (and
depend on each other), decouple them by formalizing their
communication interface as an abstract interface based on the needs of
the higher-level class
39

You might also like