Title: cs2340:Design Principles
1cs2340Design Principles
Many of these principles come from Robert Martin
or the NASA design guidelines for OO design.
2Single Responsibility Principle
- Each class should have a single overriding
responsibility (High Cohesion) - Each class has one reason why it should change
3Law of Demeter
- An Object only sends messages to
- Itself (its own instance methods)
- Objects sent as arguments to message m
- Objects created as part of reaction to m
- Objects directly accessible via attributes
Purpose Reduce coupling
4Examples
- g.add(button)
- g.getContentPane().add(button)
- process aString
- aString size.
-
- process aUser
- aUser connection send message.
5Examples
- b User new.
- b name.
- b connection send aMessage.
- myConnection send aMessage
- myConnection socket send aMessage.
6Open Closed
- Objects are open for extension but closed for
modification.
Extension via inheritance, polymorphism.
Related design patterns Template, State, Strategy
7Example
- computePay aCategory
- aCategory salaried ifTrue
- aCategory hourly ifTrue
- aCategory bonus ifTrue
- aCategory volunteer ifTrue
8Liskov Substitution Property
What is wanted is something like the following
substitution property 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.
Liskov88 Subclasses should be substitutable
for their base classes. Consider behavior, not
just is a Square/rectangle problem
9Dependency Inversion Principle
- Depend on abstractions, not concretions
- Program to interfaces not implementations
- Program to most abstract class possible
- ArrayListltintgt list new ArrayListltintgt()
- Listltintgt list new Listltintgt()
- Collectionltintgt coll new Collectionltintgt()
10Interface Segregation Principle
- Dont make large multipurpose interfaces
instead use several small focused ones. - Dont make clients depend on interfaces they
dont use.
11Packaging/Deployment Principles
- ReleaseReuse
- MaintenanceIsolated Changes
- Inverse Reuse
- Share same function/goal
12Acyclic Dependency
- Do not have cyclic dependencies in your packages
- Decomposition into independent modules
13Design Metrics
- Instability measure The more concrete the more
unstable the class is. - Depend on most stable classes
- Ci incoming dependencies (packages that depend
on me) - Co outgoing dependencies (packages that I
depend on) - Instability Co / (Co Ci)
14Design Metrics
- Stable classes are abstract classes
- Na Number of abstract classes
- Nc Number of concrete classes
- Abstractness Na / Nc
15Design Metrics
- So how good is my package?
Distance A I 1 Closer to zero,
better the design
16Design Metrics
- Class Size
- Methods per class
- Lack of Cohesion (count of methods with
dissimilar purpose) - Coupling Between Classes (count of other classes
that this class refers to) - Depth of Inheritance Tree
- Method Complexity