Friday, October 8, 2010

Design Patterns

OO principles

1. Encapsulate what varies.

Take what varies and "encapsulate" it so it wont affect the rest of your code.

2 . Program to interface not an implementation. [ program to super type can be abstract class also]

Ex : Animal d = new Dog();

Animal g = getAnimal() - better { could be injected at run time even better , can plug new implementation without change of code}

3. Favour composition(HAS-A) over inheritance(IS-A)

Advantages of Composition over Inheritance

1. Refactoring becomes very easy [No need to change super class]
In an inheritance relationship, super classes are often said to be "fragile," because one little change to a super class can ripple out and require changes in many other places in the application's code.

back-end class - Super class

front end class - Sub class

It is easier to change the interface of a back-end class (composition) than a super class (inheritance). [Only subclass functionalities which directly depends on super class can be changed , other implementation classes using teh sub class need not change.]

It is easier to change the interface of a front-end class (composition) than a subclass (inheritance). We can't add to a subclass a method with the same signature but a different return type as a method inherited from a superclass. Composition, on the other hand, allows you to change the interface of a front-end class without affecting back-end classes.

2. Composition gives high flexibility.[Change behavior at run time]

Composition allows you to delay the creation of back-end objects until (and unless) they are needed, as well as changing the back-end objects dynamically throughout the lifetime of the front-end object.

With inheritance, you get the image of the superclass in your subclass object image as soon as the subclass is created, and it remains part of the subclass object throughout the lifetime of the subclass.

3. The explicit method-invocation forwarding (or delegation) approach of composition will often have a performance cost as compared to inheritance's single invocation of an inherited super class method implementation [but very negligible]

  • Don't use inheritance just to get code reuse If all you really want is to reuse code and there is no is-a relationship in sight, use composition.

  • Don't use inheritance just to get at polymorphism If all you really want is polymorphism, but there is no natural is-a relationship, use composition with interfaces.

Ref :

Free Domain Names @!