Design principles Flashcards
What is a law
Universal truth
What is a principle
Generic best practice
What is a pattern
Generic solution to frequently occurring design problem
Cohesion
degree to which elements inside a class belong together
Coupling
degree to which two classes are connected to each other
Benefits of high cohesion
Easy to maintain, read, understand, reuse
Single Responsibility Principles
A class should have only one reason to change
How to ensure loose coupling
A class should depend on abstractions (i.e. interface), not implementation
Perils of high coupling
Ripple effects (dependency hell), hard to reuse, hard to test
Content coupling
- One module(e.g., class) uses the code/data from
another module. - Example: class A refers to local data of class B!
- Violates information hiding principle of OOP.
Common coupling
- Two modules have the write-access to the same
global data - Uncontrolled error propagation and side effects.
External coupling
- Two modules depend on a module external to
the software or a specific hardware. - Example: protocol, external file, and device
format.
Control coupling
- One module A controls the flow of another
module B by passing control parameters (e.g.,
what-to-do flag) - Module A must know the internal structure of B.
- Example: A sends comparison(a,b) to sort() in B
Stamp coupling
- Module A passes the whole data structure to B,
but only a fraction of it is used. - Example: printCustomerBilling(Customer)
Data coupling
- Two modules share data through parameters or
data structures that are used in full. - Example: displayTimeOfArrival(flightNumber)
23
Acyclic Dependencies Principle
the dependency graph of packages or
components should have no cycles
Stable Dependencies Principle
- packages should depend in the direction of stability
- Instability = Ce/(Ca + Ce)
- Ce – Efferent coupling (outgoing dependency)
- Ca – Afferent coupling (incoming dependency)
Abstraction
The interface of a component should be independent of its implementation.
Encapsulation
Information hiding (i.e. private attributes)
Modularization
Cohesive and loosely-coupled abstractions
Hierarchy
Hierarchical organization of abstractions. Classification & generalization.
Open-closed principle
Class should be open for extension and closed to modification.
How to implement OCP
Define interface, extend implementation
How to know when to use OCP
Bunch of if statements that check for type and call same method name