Friday, July 3, 2015

Object Creation Factory Pattern.

Factory Pattern For Object Creation:

Factory Pattern is a type of Creational Design Pattern. It is a very famous design pattern for creating instance of class. In this pattern a common Factory method is used to Create the instance of the class hence hides all the creational logic from the client and hence creates a new object using a common interface.


Example of Java Library using Factory pattern:
List Collection.UnmodifiableList(List)
uses Factory Method

Benifits of Factory Pattern:
1. Complete Control over instance Creation.
2. Naming for what you are creating objects.
3. Solves the problem that a class can have only one constructor with a given signature.
4. Unlike constructors, factory methods are not required to create a new instance every time they are invoked.

Disadvantage of Factory Pattern:
1. Cannot Directly access Constructor while inheriting.

Parametarized Factory Method:
Factory Pattern can Use Parameters to produce different implementation of an interface. With what parameters have been passed factory can implement logic for what method to call. As in case or Rule Factory we can define rules for different instance to be followed and while creating object different ruleSet can be checked for different object.

Abstract Class VS Interface

Abstract Class:
Abstract Class in Java cannot be instantiated. In Other words an abstract class is a class which cannot be instantiated. In Object Oriented Design these Classes are used to store methods that are common to the subclasses that is going to be inherited from it, so that they can be available to them.
Abstract Methods can be defined in abstract classes. Abstract methods do not have implementation but are forced to implement in their subclasses.

Interface:
Interface has all its methods abstract so basically is a collection of abstract classes. It does not contain any implementation of its method and hence all methods in Interface needs to be Implemented by Inheriting Class unless the inheriting class is an abstract class. I case of abstract class inheriting interface it can again leave some or all unimplemented methods abstract which will then be implemented in  a class inheriting that abstract class.
Interface is implicitly abstract, all its methods are implicitly abstract and public.

Difference between Abstract Class and Interface in Java 7:
1. Abstact class can have both abstract and non abstract methods but interface can only have abstract.
2.Abstract does not allow multiple inheritance but Interface does.
3.Abstract can have static,non static, final and non final variables but Interface can only have Static and Final Variables.
4.Abstract class is inherited but Interface are implemented (Interface is not even a class).
5.Abstract Class can have private, protected and public methods but Interface can have only public.

Similarities Between Abstract Class and Interface:
1. Both cannot be instantiated.
2. Both can be used for Polymorphism.

Example of Interface and abstract Class used together effectively:
List is an example of how interface and abstract classes can be used together effectively.

Advantage of Using Interface:
1.Multiple Inheritance.
2.Clear Picture of all implementation provided.
3.Interfaces function to break up the complex designs and clear the dependencies between objects.
4.Interface makes application loosely coupled

Program to Interface P2I:
This Principle says we should always use abstract class for accomplishing some behavior, It doesn't care what concrete object you use, it just cares that it implements certain behavior. This makes the class much more flexible, as it can be provided with any number of concrete implementations to do its work.

This principle is really about dependency relationships which have to be carefully managed in a large app. – Erich Gamma
To put it in other words, you have to follow the OO concept of Encapsulation; the exposed part of a class is its interface. The important part here is that the interface represents “what” the class can do but not “how” it will do it, which is the actual implementation.

why follow this principle:
By Following this principle we ensures that dependancy to some super class or interface will ensure the implementation of function if there is some change in implementation for some requirement then only that subclass will be changed and or extended and hence others need not worry about the back ground details of all implemetations hence incapsulating the details. This Concept makes program extension manage able.

Evolving API problem:
If a method signature is added to a Interface after its implementation on client. All the subclass implementing this API will have an unimplemented method hence creating error for the user of API and breaks the code of Client which was perfectly working before adding the method signature. This problem is known as Evolving API problem.

Thursday, July 2, 2015

Composition VS Inheritance

Inheritance:
Inheritance in Java is way to define relationship between two classes. Inheritance defines Parent and Child relationship between two classes. Similar to real world where a Child inherit his parents Surname and other qualities, In Java programming language, Child class inherit its Parent’s property and code.
If a Class B inherits from a Class A then A is Super Class of B and B is Sub Class of A. Inheritance is a way to generalize data and behavior of related classes a way to extend the behavior of a particular class.

Rules Concerning Inheritance:
1. A subclass constructor must make use of one of the superclass constructors , but does not need the same signature as any of these constructors

2. A class can have multiple (overloaded) constructors. To call one constructor from another, “this” is used (must be the first line of the constructor).
Example:
public Employee(String name) {
     this(name, 0.00);
}

3. A constructor can call a superclass constructor using “super”. See Manager class (also notice super is used in another way to call a superclass method).

4. To prevent a class from having any subclasses, the class can be declared final..

5. If A is a subclass of class B, when the constructor of A is invoked, there is a specific sequence of steps by which the static/instance variables are initialized and the bodies of the two constructors are executed.

1-Initializes superclass static variable
2-Executes superclass static block
3-Initializes subclass static variable
4-Executes subclass static block
5-Initialzes superclass instance variable
6-Runs superclass object initialization block
7-Runs superclass constructor
8-Runs subclass object initialization block
9-Initialzes subclass instance variable

10-Runs subclass constructor

Benifits of Inheritance:
Inheritance suppports Code Reusability.
It reduces code redundancy
Subclasses are much more succinct (smaller class file) than they would be without inheritance.
You can derive a new class from an existing class even if we don’t own the source code for the latter!

Criteria to Check whether inheritance is appropriate:

IS-A Principle Class C may extend class D if C IS-A D. Example: Manager IS-A Employee Example: Secretary IS-A StaffPerson

Liskov Substitution Principle (LSP): C may extend D if an object of type C may be used during execution where an object of type D is expected without breaking the code. Example: We may use a Manager instance wherever an Employee instance is expected, so having Manager as a subclass of Employee adheres to LSP


Problem while using Inheritance:

Fragility Of Inheritance:
Subclasses of a superclass – even when the IS-A criterion is met – may use the superclass in unexpected ways leading to broken code.
Rectangel Square Problem: Although Square is a rectangle but it has 4 sides all equal in length but rectangle has two different pair of sides. Inheritance in this case can cause the two different side for Square too and is vulnarable for changes.
Inheritence Violates Encapsulation:
If A is a subclass of B, even if A is not modified in any way, a change in B can break A.



Bloch's principle: Either design for inheritance or prevent it
First, the class must document precisely the effects of overriding any method.
In other words, the class must document its self-use of overridable methods.
For each public or protected method or constructor, the documentation must
indicate which overridable methods the method or constructor invokes, in what
sequence, and how the results of each invocation affect subsequent processing.
(By overridable, we mean nonfinal and either public or protected.) More
generally, a class must document any circumstances under which it might invoke
an overridable method.

To support inheritance, a class must document which overridable methods it uses in its own internal operations.
Preventing Inheritance:
Make the class final, OR
Make all constructors private and provide static factory methods to create instances.

Composition:
using instance variables that are references to other objects.

Using composition with inheritance for more flexibility:
To avoid the pitfalls of inheritance, it is always possible to use composition instead of inheritance. To illustrate the technique, imagine two classes, Person and PersonWithJob. Instead of asking PersonWithJob to inherit from Person, you can compose Person in PersonWithJob and forward requests for Person functionality to the composed class. We still get the benefit of reusing Person.

Object Oriented Paradigm

In Object Oriented Paradigm, System is based on objects interacting with other objects.

Benifits of OOP:
     Easy to Maintain
     Easy to Extend and Reuse
     Easy to Understand

In order to achieve this, there are Certain principle in OOP to follow in Design and Implementation of System. Those are following:

     Objects Have State, Behaviour and Identity
     Encapsulation and Datahiding
     Inheritance and Generalization
     Polymorphism and Latebinding
     Delegation and Propagation
     Open Closed Principle
     P2I(Program to Interface)

Object Oriented Analysis and Design:
Analysis: Analysis means to find out what is needed or what are the client requirements. What the     problem is; It is like listening to the problem in some conversation.

Design: Design is to make the needs happen or make the requirements functional reality. It is to find   out the solution for the problem. It is same as giving suggestion after listening to a problem while in conversation

As in real world, objects have relationships same is in case of Objects in OOP.
Type of RelationShip between classes:
     Association
     Dependancy
     Inheritance

Types of Association    
     Unidirectional and Bidirectional
     Aggregation
     Composition
     Reflexive
     Association Classes
     Association "decoration" : name, roles, multiplicities

Static Binding and Late(Dynamic) Binding: 

static binding is a compile time operation while dynamic binding is a runtime. one uses Type and other uses Object to bind. 
static, private and final methods and variables are resolved using static binding which makes there execution fast because no time is wasted to find correct method during runtime.
Overloaded method are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.



Difference Between Procedure Oriented Programming (POP) & Object Oriented Programming (OOP):
Procedure Oriented ProgrammingObject Oriented Programming

Procedural programming uses a list of instructions to tell the computer what to do step-by-step.Object-oriented programming, or OOP, is an approach to problem-solving where all computations are carried out using objects.
ApproachPOP follows Top Down approach.OOP follows Bottom Up approach.



Data MovingIn POP, Data can move freely from function to function in the system.In OOP, objects can move and communicate with each other through member functions.
ExpansionTo add new data and function in POP is not so easy.OOP provides an easy way to add new data and function.
Data AccessIn POP, Most function uses Global data for sharing that can be accessed freely from function to function in the system.In OOP, data can not move easily from function to function,it can be kept public or private so we can control the access of data.
Data HidingPOP does not have any proper way for hiding data so it is less secure.OOP provides Data Hiding so provides more security.
OverloadingIn POP, Overloading is not possible.In OOP, overloading is possible in the form of Function Overloading and Operator Overloading.
Open-Close Principle in JAVA:
Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
This Principle is important in case of dynamic and growing application and hence to save programmers effort as change a previously tested code can cause a lot of overhead hence we should always try to extend the code for new requirements which will fulfill new requirement without changing in the previous working version.
Polymorphism supports use of the Open-Closed Principle: The part of our code that is established and tested is closed to modification (change), but at the same time the system remains open to changes, in the form of extensions.

Propagation and Delegation:
An action can be passed to other classes in OOP this is called Propagation and the actual realization of the responsibility is called Delegation. A class can express functionality in its interface, but it delegates responsibility to an associated class to carry out the action. The responsibility for the action can propagate through a hierarchy.

Diamond Problem:
In programming languages in which multiple inheritance is supported a problem arises when inheriting from multiple classes to one class. Suppose a class D inherits from class B and C which inherits from super class A where both class B and C have a method go() having same signature then there will be a problem while deciding if D will inherit go() from B or C this problem is called Diamond Problem.
As a solution to this problem JAVA (previous than 8) can inherit only from once implementation but can inherit multiple times from types(Interface).