0% found this document useful (0 votes)
21 views

11 Design Principles

Uploaded by

dung08122003
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)
21 views

11 Design Principles

Uploaded by

dung08122003
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/ 13

12/12/23

1 2

Review: Design levels

Architectures/Framework
ITSS SOFTWARE DEVELOPMENT (Financial System, J2EE,…)
11. DESIGN PRINCIPLES OOD Patterns

Nguyen Thi Thu Trang OOD Principles


trangntt@soict.hust.edu.vn
Specific Data Structures
Algorithmic Approaches

General + OO Concepts

1 2

S.O.L.I.D Principles of OOD SOLID Principles – Why necessary?


• SRP: The Single Responsibility Principle • S.O.L.I.D. is useful as reference while
• OCP: The Open Closed Principle designing applications
• LSP: The Liskov Substitution Principle • Managing dependencies makes
maintainability easier
• ISP: The Interface Segregation Principle
• Various principles and techniques
• DIP: The Dependency Inversion Principle
available for diagnose problems with
designs

3 4

1
12/12/23

5 6

Content Review: Tight/High Cohesion


1. SOLID: Single Responsibility Principle • Cohesion
2. SOLID: Open-Close Principle • Measure of how strongly-related or focused
3. SOLID: Liskov Substitution Principle the responsibilities of a single module are
• The degree to which all elements of a module
4. SOLID: Interface Segregation Principle are directed towards a single task/
5. SOLID: Dependency Inversion Principle responsibility
6. Case study: Reminder program • Highest cohesion (Cohesive)
• Modules have a single and clear responsibility
• Elements in a module are functionally related

5 6

7 8

SRP: Single Responsibility Principle SRP: Single Responsibility Principle


There should never be • Simplest principle, hardest to get right
more than one reason • Every module should do just one thing and
for a class to change do it well
• Finding and separating responsibilities
Or may be hard to do
• How much is enough?
A class should have • Measured by Cohesion (and Coupling)
one, and only one
• When violated: Fragile design that breaks
type of responsibility
in unexpected ways when changed

7 8

2
12/12/23

9 10

SRP: Single Responsibility Principle SRP: Single Responsibility Principle

• How much is enough for “one” responsibility? • What is a Responsibility?


• A reason for change
SystemManagerService NetworkManagement
+ SelectNetworkSettings()
+ UpdateNetworkSettings(...) • “Modem” sample
SystemManagerService
+ SelectNetworkSettings() • dial & hangup functions for managing connection
DateTimeManagement
+ UpdateNetworkSettings(...)
+ CurrentDateTime { get; set; }
+ CurrentDateTime { get; set; }
+ AllTimeZones() • send & recv functions for data communication
+ AllTimeZones() + SelectTimeZone()
+ SelectTimeZone() + UpdateTimeZone(...)
+ SelectNetworkTimeData()
è Should separate into 2 modules!
+ UpdateTimeZone(...) + UpdateNetworkTimeData(...)
+ SelectNetworkTimeData()
+ UpdateNetworkTimeData(...)
+ ControlServices() ServiceManagement
+ ControlServices()
+ CreateUserAndAssignGroup(...)
+ ChangeUserCredentials(...)
+ DeleteUser(...) UserManagement
+ RetrieveUsers() + CreateUserAndAssignGroup(...)
+ ChangeUserCredentials(...)
+ DeleteUser(...)
+ RetrieveUsers()

9 10

11 12

SRP: Example
• Often we need to sort students by their
name, or ssn.
è Make Class Student implement the
Java Comparable interface

class Student implements Comparable{



int compareTo(Object o){ … }

};

11 12

3
12/12/23

13 14

SRP: Example (2) Java Comparable


• Each time students are ordered differently, the
Student

Register
SSN
Name
Comparable compareTo() method needs to be changed and
int compareTo()
add(Course d, Student s); getSSN()
getName() Students needs to be recompiled and also its
major
getMajor() clients
int compareTo()
• Student is a business entity, it does not know in
When a new requirement needs to
what order it should be sorted since the order of
sort students in a different order, sorting is imposed by the client of Student.
Student, Register, and AClient all AClient
need to be recompiled, even Register
op() { ;}
• Cause of the problem: we bundled two separate
has nothing to do with the new responsibilities (i.e., a business entity and
ordering of Students. It invokes
Collections.sort(aListofStudents); ordering) into one class – a violation of SRP

13 14

15 16

The single-responsibility principle Content


Register
1. SOLID: Single Responsibility Principle
add(Course d, Student s); Comparator
int compare(Object o1, Object o2) 2. SOLID: Open-Close Principle
Student
SSN 3. SOLID: Liskov Substitution Principle
Name
getSSN()
getName()
StudentByName
int compare(Object o1, Object o2) ClientA 4. SOLID: Interface Segregation Principle
major op() { ;}
getMajor()

StudentBySSN
5. SOLID: Dependency Inversion Principle
int compare(Object o1, Object o2)
6. Case study: Reminder program
The solution is to separate the
two responsibilities into two ClientB
separate classes and use another op() { ;} It invokes
Collections.sort(aListofStudents,
version of Collections.sort(). StudentBySSN);

15 16

4
12/12/23

17 18

OCP: Open-Close Principle OCP: Open Closed Principle


“Software entities (classes, modules, functions,
etc.) should be open for extension, but closed
for modification”
Bertrand Meyer, 1988
Or
“You should be able to extend a classes
behavior, without modifying code”

è Extend behavior instead of changing old


code that already works
Open chest surgery is not needed when putting on a coat

17 18

19 20

OCP: Open Closed Principle OCP: Abstraction is the KEY


• Open for Extension • Client & Supplier classes are concrete
• The behavior of the module/class can be extended • If the Supplier implementation/class is changed,
• The module behaves in new and different ways as the Client also needs change.
requirements changes, or to meet the needs of new
applications
è How to resolve this problem?
à Reusability and maintainability
• Closed for Modification
• The source code of an existing module is inviolate Supplier
• No one is allowed to make source code changes to it
à When violated: Cascading changes to dependent
modules during changes

19 20

5
12/12/23

21 22

OCP: Abstraction is the KEY (2) Violation of the OCP

Abstract Employee
+int EmpType
Supplier

Faculty Staff Secretary Engineer


+getOffice() +getDept() +getTypeSpeed() +getEngTYpe()
• The Concrete Supplier class implements the
Abstract Supplier class / Supplier Interface void printEmpRoster(Employee[] emps) {
What if we
• The Supplier implementation is changed, for (int i; i<emps.size(); i++) {
Supplier need to add
if (emps[i].empType == FACULTY)
• the Client is likely not to require any change. Engineer??
printfFaculty((Faculty)emps[i]);
else if (emps[i].empType ==STAFF)
printStaff((Staff)emps[i]);
è The Abstract Supplier class here is closed for
else if (emps[i].empType == SECRETARY)
modification and the Concrete class implementations here printSecretary((Secretary)emps[i]);
are Open for extension }
}
21

21 22

23 24

OCP – Dynamic Polymorphism OCP – Dynamic Polymorphism


Employee • Three versions of SORT
+ printInfo()
• sort(List list)
Faculty Staff Secretary Engineer • Elements of list must implement Comparable interface
+printInfo () +printInfo() +printInfo() +printInfo()
• sort(List list, StringComparator sc)
void printEmpRoster(Employee[] emps) {
• Elements of list are not required to implement Comparable
for (int i; i<emps.size(); i++) {
emps[i].printInfo(); • StringComparator orders objects of String only
} • sort(List list, Comparator comp)
}
• Elements of list are not required to implement Comparable
When Engineer is added, printEmpRoster() does not even • Comparator may compare objects of any type.
need to recompile. • Open to extension since it can sort objects of any type at
è printEmpRoster() is open to extension, closed for any order specified in the second parameter.
modification.

23 24

6
12/12/23

25 26

OCP – Static Polymorphism Practice: Checking S & O in codebase


• Generics in Java: The container can take • Checking if all classes donot follow the
objects of any type SRP & OCP in code base
public class LinkedList<E> {
boolean add(E e);
boolean add(int index, E e);
boolean addFirst(E e);
boolean addLast(E e);
void clear();
E get(int index);
...
}

25 26

27 28

Content LSP: Liskov Substitution Principle


1. SOLID: Single Responsibility Principle • “Functions that use pointers or references to base classes must
be able to use objects of derived classes without knowing it.”
2. SOLID: Open-Close Principle • Or
3. SOLID: Liskov Substitution Principle “Subclasses should be substitutable for their
4. SOLID: Interface Segregation Principle base classes.”
5. SOLID: Dependency Inversion Principle
• Every implementation of an interface needs to fully
6. Case study: Reminder program comply with the requirements of this interface
• Any algorithm that works on the interface, should
continue to work for any substitute implementation

22

27 28

7
12/12/23

29 30

LSP: Liskov Substitution Principle (2) LSP: Liskov Substitution Principle (3)
• Demand no more: The subclass would accept any • Why LSP is so important? If violates LSP:
arguments that the superclass would accept.
• Class hierarchy would be a mess and if subclass
• Promise no less: Any assumption that is valid
instance was passed as parameter to methods method,
when the superclass is used must be valid when
the subclass is used. strange behavior might occur.
• Unit tests for the Base classes would never succeed for
the subclass.
• Interface Inheritance: LSP should be conformed to
• Implementation (or Class) Inheritance: è LSP is just an extension of Open-Close
• Multi-layer inheritance hierarchy: Provide more Principle!!!
abstraction levels for subclasses
• Use composition instead of inheritance (in Java) or use
private base classes (in C++)

29 30

31 32

LSP: An Example LSP: More example


class Square extends Rectangle {
• Ostrich is a Bird (definitely!!!) public void setWidth(int width) {
Bird
super.setWidth(width); Rectangle
• Can it fly? No! => Violates the LSP super.setHeight(width); -int width;
-int height
} +getWidth()
èEven if in real world this seems
public void setHeight(int height) { +setWidth()
+getHeight()
+ fly()
natural, in the class design, Ostrich super.setHeight(height); +setHeight()
+area();
should not inherit the Bird class super.setWidth(height);
}
is-a
èThere should be a separate class }
void clientOfRectangle(Rectangle r) { Square
for birds that can’t really fly and r.setWidth(10); +getWidth()
+setWidth()
Ostrich inherits that KingFisher Ostrich r.setHeight(20); +getHeight()
+setHeight()
print(r.area());
}
Rectangle r = new Square(…);
clientOfRectangle(r); // what would be printed?

31 32

8
12/12/23

33 34

LSP: Implementation Inheritance Content


• Implementation inheritance 1. SOLID: Single Responsibility Principle
• When you use List to implement Queue (in Java),
use composition, not inheritance. 2. SOLID: Open-Close Principle
• The intention is that you use only List’s 3. SOLID: Liskov Substitution Principle
implementation
4. SOLID: Interface Segregation Principle
<foundation>
List List
+insert()
+delete()
List
+insert()
+insert()
+delete()
5. SOLID: Dependency Inversion Principle
+find() +delete() +find()
+find()
MyList 6. Case study: Reminder program

Queue Queue Queue


+enqueue() +enqueue() +enqueue()
+dequeue() +dequeue() +dequeue()
+isEmpty() +isEmpty() +isEmpty()

33 34

35 36

ISP: Interface Segregation Principle ISP: Interface Segregation Principle (2)

• “Client should not be forced to depend upon {Applying ISP}

interface that they do not use.”


Or
• “Many client specific interfaces are better than
one general purpose interface.”

35 36

9
12/12/23

37 38

ISP – A Bad Design ISP – A Good Design


Segregated Interfaces

Fat Service with integrated interface ServiceA


Client A ServiceImpl
Methods
Service For ClientA Methods
Client A Methods For ClientA
For ClientA
ServiceB
Methods
Methods Client B Methods
For ClientB
Client B For ClientB
For ClientB
Methods
ServiceC
Methods For ClientC
Client C Methods
For ClientC
Client C For ClientC

• Changes introduced by one client (e.g., Client A) may require


The problem is that any change in Service introduced by one client its designated interface (ServiceA) and the service
(e.g., Client A) causes Service and the other clients (Client A and implementation to change.
Client C) to be recompiled. • However, other clients (Client A & Client C) and their Interfaces
(ServiceB & ServiceC) are not required to change or recompile.

37 38

39 40

ISP: Interface Segregation Principle (3) Content


• Interfaces with too many methods (fat interfaces) 1. SOLID: Single Responsibility Principle
are less re-usable
2. SOLID: Open-Close Principle
• Unnecessary complexity and reduces
maintainability or robustness in the system 3. SOLID: Liskov Substitution Principle
• Unnecessary coupling among the clients due to 4. SOLID: Interface Segregation Principle
additional useless methods 5. SOLID: Dependency Inversion Principle
• When one client causes the interface to change, all
other clients are forced to recompile 6. Case study: Reminder program

è Interfaces have their own responsibility and


thus they are re-usable.

39 40

10
12/12/23

41 42

DIP: Dependency Inversion Principle


“High level modules should not depend upon
low level modules. Both should depend upon
abstractions”
Or
“Abstractions should not depend upon details.
Details should depend upon abstraction.”
Or
“Depend upon Abstractions. Do not depend
upon concretions.”

41 42

43 44

DIP: An Example DIP: Dependency Inversion Principle


• Low-level modules are more likely to change
• High-level modules (business policies) are more
likely to remain stable (i.e. purpose of the system)
à They should:
• Depend upon abstraction of low level modules
• Force low level modules to change
• When violated: Lower level module changes can
force high level modules to change

Would you solder a lamp directly to the electrical wiring in a wall?

43 44

11
12/12/23

45 46

DIP: Dependency Inversion Principle DIP: Dependency Inversion Principle


Dependency Inversion: Lower-level layers
High-level modules make calls Policy
is dependent upon upper-level layers.
Policy Layer
to low-level modules
Policy
Layer Mechanism

Mechanism Mechanism
<<interface>>
Layer Policy
Layer
Service Utility

The upper-level layer is dependent Utility Layer <<interface>>


Utility
upon lower-level layers Mechanism
Service Layer

è Depending upon interfaces or abstract functions and


Ownership Inversion: The client (upper-level layer)
classes, rather than upon concrete functions and classes
owns the interface, not the lower-level layers

45 46

47 48

DIP and OCP Practice: Checking L ,I & D in codebase


• High-level concepts are more stable than • Checking if all classes donot follow the
low-level implementation LSP, ISP & DIP in codebase
• Concrete things change often and abstract
things change less often.
• Abstractions are “hinge points”, places
when the design can provide different
implementations

47 48

12
12/12/23

50

Content Chương trình “Nhắc nhở nghỉ giải lao”


1. SOLID: Single Responsibility Principle • Bạn hãy thiết kế và viết mã nguồn minh hoạ cho
chương trình "Nhắc nhở nghỉ giải lao” như sau:
2. SOLID: Open-Close Principle
• Chương trình định kỳ kiểm tra thời gian
3. SOLID: Liskov Substitution Principle
• Cứ sau 1 khoảng thời gian nhất định, chương trình:
4. SOLID: Interface Segregation Principle • Nhắc hoặc hoặc yêu cầu (bắt buộc) người dùng cần
5. SOLID: Dependency Inversion Principle nghỉ ngơi. Thậm chí, chương trình có thể không cho
người dùng sử dụng máy tính (bắc buộc nghỉ ngơi)
6. Case study: Reminder program trong vòng 1 số phút nghỉ ngơi đó.
• Gợi ý làm 1 việc gì đó trong thời gian nghỉ ngơi:
• Nghe nhạc
• Tập thể dục tại chỗ theo hướng dẫn
• ...

49 50

51

Design exercise
• Write a typing break reminder program
• Offer the hard-working user occasional reminders of the
health issues, and encourage the user to take a break
from typing
• Naive design
• Make a method to display messages and offer
exercises
• Make a loop to call that method from time to time
(Let's ignore multi-threaded solutions for this
discussion)

51

13

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy