Principles of Object Oriented Design
Some of the following are self-explanatory. Others require some explanation.
- Encapsulate what varies. Restrict outside access to the details of routines that might need to change with changing requirements.
- Program to interfaces not implementations.
- Prefer composition over inheritance.
- Strive for loosely coupled designs among objects that interact.
- Only talk to your friends.
- Don't call us; we'll call you.
- Depend on abstractions not on concrete classes.
- Keep classes open to extension and closed to modification.
- A class should have only one reason to change.
Those fit into SOLID principles:
- Single Responsibility
- Liskov Substitution
- Interface Segregation
- Dependency Inversion
Then there are the
- Law of Demeter. This is known as the Principle of Least Knowledge and is often stated as only talk to your friends. For instance, if your friend Suzie introduces you to John, do not ask John to do something for you. Instead, make friends with John before asking him any favours.
s.j.DoSomething()breaks the law;
j.DoSomething()follows the it. When we call
DoSomething()directly thru John, our client code touches fewer components, and by passing thru fewer components, our client code has less if not the least knowledge of the system.
- Design by Contract
- Don't Repeat Yourself