Professional Documents
Culture Documents
Student: Tạ Bảo Thắng
Student: Tạ Bảo Thắng
“
“A class should have one and only one reason to change,
meaning that a class should have only one job.”
SRP : Single Responsibility Principle
“
SRP is about strong cohesion and loose coupling
Cohesion
Relation of responsibilities
Focused on single task
Coupling
Dependency on other modules
Relationship between modules
Ideal: low coupling + strong cohesion (e.g. a HDD)
Example: of a violation of the SRP.
Student
+ getStudentInfoText() : String
+ getStudentInfoHTML() : String
+ getStudentInfoJson() : String
+ saveToDatabase() : void
+ saveToFile() : void
Student Fomatter
only format
- Name : String display
information
+ getName() : String
+ setName(String): void
+ fomatStudentText(Student) : String
+ fomatStudentHTML(Student) : String
+ fomatStudentJson(Student) : String
only contains
student information
Store
Each class
should have
- db : Database only one job.
+ SaveToDatabase(Student): void
“
“Each class should be open for extensions (sub-classes),
but closed for modifications.”
Open to extension :
New behavior can be added later
Closed to modification
Changes to source or binary code are not required
OCP : Open Closed Principle (2)
“
Change behavior without changing the code?!
o Yes, this is possible, e.g. by inheritance
Method CaculateArea is
only deloyed in sublasses
LSP : Liskov Substitution Principle
“
“Derived classes must be substitutable for their base
class.”
“
Functions that use pointers or references to base classes
must be able to use objects of derived classes without
knowing it.
Bird
Duck Penguin
@overide @overide
+ fly(){ + fly(){
sout(“Duck can
throw new
fly”)}
NoFlyException (); }
ISP : Interface Segregation Principle
“
“Clients should not be forced to depend on methods they do
not use”
Segregate interfaces
Increased coupling
Reduced flexibility
Reduced maintainability
Example: of a violation of the ISP.
<<interface>> Fish
IAnimal
+Eat(){….}
+ Eat(); + Swim(){….}
+ Swim(); +…..
+ Fly(); implement + Fly(){ throw new
Exeption(“Can’t fly”)}
+…..
+ Drink(); Classes having
+ Sleep(); methods they
do not need Bird
+Eat(){….}
+ Fly(){….}
+…..
+ Swim(){ throw new
Exeption(“Can’t swim”)}
Example: Design use ISP.
alwe
intosegregate
small, cohesiveinterface
interfaces as IAnimal
follows:
into small interfaces as follows:
+ Fly(); + Eat();
+ Swim();
+ Sleep();
+ Drink();
“
High level modules should not depend upon
low level modules. Both should depend upon
abstractions.