- Identify aspects of an application that vary and separate them form what stays the same. Later you will be able to alter or extend the parts that vary without affecting other parts, resulting in fewer unintended consequences from code changes and more flexibility in a system - Encapsulate. E.g.: use separate classes to delegate behavior - instanced by
the class using those behaviors. This way it is also easy to change
behavior on run time (getter, setter).
class Dog(){ // (FightBehavior is an interface - multiple Behavior //
patterns may be implemented)
same goes for PlayBehavior FightBehavior fBehavior; PlayBehavior pBehavior; void fight(); void play(); }
- Program to an interface, not an implementation. Exploit polymorphism by programming to a supertype. e.g.: do not use:
instead use:Dog d = new Dog(); d.bark();
interface Animal(); // having a method makeNoise Dog d = new Animal(); // Dog implements Animal d.makeNoise();
- Favor composition (has-a relationships) over inheritance.
- Strive for loosely coupled designs between objects that interact. Such objects can interact, but have very little knowledge of each other. This allows for flexible OO systems that can handle change because they minimize the interdependency between objects.
- Classes should be closed to change, yet open to extensions. Thereby it is easy to incorporate new behavior without modifying existing code (correct, tested, bug free code should stay unaltered - lowering chances of introducing new bugs or unintended side effects) - Open-Closed principle.
- Depend upon abstractions. Do not depend upon concrete classes. It suggests that high-level components (like an abstract class PizzaStore) should not dpend on low-level components (ConcretePizza) - Dependency Inversion Principle
Wednesday, June 4, 2014
OO Principles
These are all principles for object oriented programming in one post (will be regularly updated along with the design patterns that use them):
Labels:
design principles,
programming
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment