Monday, December 30, 2013

Observer Design Pattern Example

Observer Design Pattern: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. -- By THE GOF BOOK

When to use? Observer design pattern is useful when we are interested in the state of an object and want to get notified whenever there is any change in the state of the object. In observer pattern, the object that watch the state of another object is called Observer and the object that is being watched is called Subject.

For example: In GUI programming, event-driven is an important concept. Such as, when you do programming in java UI /swing, you may put a button on the stage, then you’ll add a callback function to the button. The function will be called when there is some action play on the button, such as click. This is almost the same with the observer pattern.

Lets make it clear. Firstly, we care the state of the button; we want know when the button was clicked. Secondly, when the button state was changed, we want to do something, that’s the callback function. Actually, you can consider as the function cares the state of the button. When the button state change, the function will do something. So here the button is observable, and the function maybe the observer.

Keep in mind, An observable object can have one or more observers. An observer may be any object that implements interface Observer. After an observable instance changes, an application calling the Observable's notifyObservers method causes all of its observers to be notified of the change by a call to their update method.

Tuesday, November 19, 2013

Adapter Design Pattern Example

Adapter Design Pattern:  The adapter design pattern is a design pattern that translates one interface for a class into a compatible interface.

Adapter converts the interface of a class into another interface which is required or expect by clients. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

Adapter also known as wrapper, an alternative naming shared with the Decorator pattern according to the GoF Design Patterns book.

Situations: During application development some time we face the following situations 

  • Sometimes a toolkit or class library can not be used because its interface is incompatible with the interface required by an application. 
  • We can not change the library interface, since we may not have its source code. 
  • Even if we did have the source code, we probably should not change the library for each domain-specific application.

When to use: The Adapter pattern can be used when

  • You want to use an existing class, and its interface does not match the one you need
  • You want to create a reusable class that cooperates with unrelated classes with incompatible interfaces
Implementation Issues: How much adapting should be done?
  • Simple interface conversion that just changes operation names and order of arguments
  • Totally different set of operations

Thursday, October 31, 2013

Composite Design Pattern Example

Composite Design Pattern: Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. --By GOF BOOK

A composite is an object designed as a composition of one-or-more similar objects, all exhibiting similar functionality and also shows the 1-to-many  relationship or parent child  hierarchy.

Problem: In an application if we need to represent a parent and child, node and leaf hierarchy or a tree structure. Then it is difficult to represent these structures in traditional way.

Solution: By using Composite pattern it is very easy to build these kind of hierarchy or tree structure.

This pattern is very useful, especially when you building a user interface. You can treat display object and display container object the same way, without considering the differences between the two objects. It’s very common in the GUI building environment.

Composite can be used when clients should ignore the difference between compositions of objects and individual objects. If you find that you are using multiple objects in the same way, and they often have nearly identical code to handle each of them, then composite is a good choice for you. it is less complex in this situation to treat primitives and composites as homogeneous (Node)...

Wednesday, October 9, 2013

Prototype Design Pattern Example

Prototype Design Pattern: Prototype design pattern is a creational design pattern and it is a template for creating an object from an already existing object. 

In this design pattern you use an already existing object as a prototype for creating a new object. If creating an object is time consuming, and if your application needs multiple such objects which are exactly the same or slightly different then you can use prototype pattern.

Prototype pattern can be used in transactional system, where in before performing a transaction, a clone of the prototype object is created, transaction is performed on the cloned object and if the transaction is successful  the prototype is replaced with cloned object by making the cloned object as the prototype. In case if transaction fails then the cloned object can be completely discarded.

The prototype object holds certain amount of information and if you need a similar object you can then clone the prototype object to create a similar object. If you application requires similar object but differ slightly then you can clone the prototype object and modify it slightly to fit the need of the application.

Friday, October 4, 2013

Java Developer Tools

Java Developer Tools:

Oracle has released Java 7 update 40, with some major new features in JDK 7 Update 40 (7u40) release. Java Mission Control is bundled with this JDK release a JVM monitoring tool, Rule Sets for Java applets and Web Start applications, and a lots of bug fixes.

Mission Control

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collection framework built into the Oracle JDK. It allows Java administrators and developers to gather detailed low level information about how the Java Virtual Machine (JVM) and the Java application are behaving.

Using the Java SE Advanced and Java SE Suite you can do the following


Wednesday, October 2, 2013

Abstract Factory Design Pattern Example

Abstract Factory Design Pattern: Provide an interface for creating families of related or dependent objects without specifying their concrete classes -- By THE GOF BOOK.

The abstract factory pattern is an extension of the  Factory Method pattern. Both are about creating the new objects, while abstract factory cares more about a family of objects or products to be produced.

In simple words, A normal factory is used to create sets of related or similar objects and an abstract factory is used to return instance of factories. Thus, we can say, an abstract factory is used to return instance of factories that can be used to create similar or related objects.

As there is a ‘abstract’ word in the pattern name don’t mistake and confuse it with java ‘abstract’ keyword. It is not related to that. This abstract is for abstraction from object oriented programming point of view.

Lets understand this with a simple example.
Problem: As in my previous post  Factory Method pattern, we created a media player and a decoder factory to decode the given media file before playing. If we see the code of decoder factory we will notice that there is a problem with the code, as audio and video decoders are mixed in the

Saturday, September 28, 2013

Factory Design Pattern Example

Factory Design Pattern: The factory method pattern is an object-oriented creational design pattern. Factory Pattern deals with the problem of creating objects without specifying the class of object that will be created. 

Creating an object often requires complex processes, which is not appropriate to include within a composing object. The object's creation may lead to a significant code duplication and may not provide a sufficient level of abstraction. In an application if object creation code is spread in whole application, and if you need to change the process of object creation then you need to go in each and every place to make necessary changes.

Factory design pattern handles these problems by defining a separate method for creating the objects.
In simple words, if we have a super class and many sub-classes, and based on data provided, we need to return the object of one of the sub-classes, then we use a factory pattern.

This pattern introduces loose coupling between classes which is the most important principle one should consider and apply while designing the application. Loose coupling can be introduced by using abstract entities rather than concrete implementations.

When to use: The Factory patterns can be used in following cases:
1. When a class does not know which class of objects it must create.
2. A class specifies its sub-classes to specify which objects to create.
3. At run time you need to create an object based on input parameter...

Monday, September 23, 2013

Strategy Design Pattern Example

Strategy Design Pattern: Strategy pattern defines family of algorithms which are encapsulated and are interchangeable at run time depending on a factor that requires a particular algorithm to be executed. Strategy pattern encourages open-close design principle where a class is open for extension but closed for modification.

It is a suitable replacement for a if-else or switch-case statements or complex conditional logic within a method. It also leads to more testable code, especially when coupled with IOC.

When to use: Let us assume that you are a Telecom service provider and you provide prepaid recharge facility to the customer. Depending on the recharge amount you would like to provide free SMS and free Talk time offer.

The Telecom service system can have a TelecomOperator class. On each recharge this class has to determine different offer depending on the recharge amount....

Wednesday, September 18, 2013

Decorator Design Pattern Example

Decorator Design Pattern: The Decorator design pattern adds additional responsibilities to an object dynamically without affecting other objects or existing objects. It is like a wrapper on another object.

In other words, The decorator pattern is used to extend (decorate) the functionality of a certain object statically, or dynamically.

The decorator pattern is an alternative to subclassing. We can write a subclass by extending a class and add behavior at compile time, and the change affects all object instances of the original class. 
But we can achieve this same behavior without extending a class and using a decorator class, since decorating can provide new behavior at run-time for individual objects.

Lets take an example to understand it.
Problem: We need to read a text file and display its content on screen. So we can write a InputReader class which will take a file as input and read the text file and display the content.

Now suppose:
  1. The given file has text with lots of extra white spaces, So using this InputReader how we can read the file and display the text by removing extra white spaces.  i.e "abc       xyz" shoud be displayed as "abc xyz".
  2. The given text file is an encrypted file and before displaying the text on screen it has to be decrypt. So using the InputReader class how we can achieve this?....

Sunday, September 15, 2013

Command Design Pattern Example

Command Design Pattern:  The Command pattern is known as a behavioral pattern and is used to represent and encapsulate all the information required to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters. Command pattern allows the requester of a particular action to be decoupled from the object that performs the action.

The Command Pattern is useful when we need to do the following task:
  • A history of actions is needed
  • You need callback functionality, like listeners in java
  • Calls or Requests need to be handled at different times or in different orders
  • The invoker should be decoupled from the object handling the invocation.

Lets take an example, Suppose we have an electric engine and we want to start and stop this engine on press or click of a button. We will use command patter to do this...

Friday, September 13, 2013

Proxy Design Pattern Example

Proxy Design Pattern: 

Proxy Design Pattern addresses a problem where access to real object needs to be controlled in a manner by which only authorized user can access the real object. Proxy pattern can also be applied to allow only limited access to real object.

Let’s take an example of banking system

Bank as a whole, is a very secure system, the access to which is restricted only to customers who holds an account with the bank. The access to the bank is controlled by bank personal such that if a bank customer wants to perform a transaction, then he will not be allowed to do so. The bank personal ensures that only customer who holds account with the bank is allowed to perform transaction.

The bank personal is in fact the proxy who controls access to the bank to the outside world. This proxy validates the authenticity of the customer before performing any transaction, on behalf of the bank.

If we have a class Bank which represents real Bank then we need to expose this Bank object to the client directly, so without proxy any non-bank client who has a valid account number can perform transaction with the Bank object which is not desirable.

Thursday, September 12, 2013

Facade Design Pattern Example

Facade design pattern: Facade design pattern provides structured way of designing a system by encapsulating sequence of operations required for business operation into a single interface.

In a complex system, performing a business operation would require interacting with different modules of the system, by calling method on each of the different module in a particular sequence. The facade design patterns abstracts all the interaction with different modules into a single simplified method. 

In simple words a single interface to perform multi-step process. So the client or the user has to only use this simplified method or interface to perform the business operation and the method/interface will internally take care of calling methods / steps on different modules. 

This way Facade Pattern defines a higher-level interface that makes the subsystem or sub modules easier to use.

How to use: Lets take an example of music player...

Visitor Design Pattern Example

Visitor Design Pattern: The visitor design pattern is a way of separating an some logic from an object structure on which it operates. Basically it allows you to add new operations on existing classes without modifying them, So visitor design pattern is a great way to provide a flexible design.

Note:  Visitor pattern has some flaws.
If we add a new class, the visitor class needs a new method. Furthermore, it is indeed likely that a new visiting method will need the definition of a new visitor patter, as well as a new accept method in every class of the hierarchy, visitor uses dual dispatching.

When to use: when you have a complex structure, i.e, a hierarchy, tree structure or something else that's not simply linear, you can apply the visitor to simplify the complex structure.

Lets understand it by one hierarchy problem example ...

Tuesday, September 3, 2013

Singleton Design Pattern Example

Singleton Design Pattern: This is the most simplest and most popular design pattern. This is a type of creational design pattern. This help us in creating a single object of a class.

Multiple objects can not be created as we do for any normal class shown here.

If we have a class A then we can say

A a1 = new A();// creates a new object of A
A a2 = new A();// creates a new object of A
A a3 = new A();// creates a new object of A

Each time a new object of class A will be created so a1, a2 and a3 will refer three different instances of class A. But the same is not possible with a singleton class.
You can not create an object of Singleton class using new operator.
  Singleton singleton = new Singleton();// is not possible, compile Time Error:
  //The constructor Singleton() is not visible

Sunday, September 1, 2013

Mediator Design Pattern Example

Mediator Design Pattern: Sometimes we need a mechanism to facilitate the interaction between objects in a manner in that objects are not aware of the existence of other objects. In other words Mediator helps in achieving loose coupling between various objects by keeping objects from referring to each other explicitly, and it makes their interaction independent.

There are some point which we need to keep in mind while choosing this design pattern.

  • Mediator pattern helps to achieve loose coupling.
  • You should know if there is a coupling between the components, in you code
  • Once you identified the coupling between the components, you can think of  using this design pattern.

I will explain it with example how you can decouple your various components from each other with help of a Mediator. Mediator provides us the freedom to do modification in any component without touching other components.

Lets take an example: You want to design a UI Screen which will have many components to display. 

Friday, August 2, 2013

OOPS Design Principles

Why Object Oriented Design Principles(OOPS)?

Software design principles represent a set of guidelines that helps us to avoid having a bad code or design. These are GRASP and SOLID. Programming is full of acronyms like these.
Other examples are : DRY (Don’t Repeat Yourself!) and KISS (Keep It Simple, Stupid!).
But there obviously are many, many more, some of them will be listed here.

Object Oriented Design (OOD) Guidelines:
During the design process, as we go from requirement and use-case to a system component, each component must satisfy that requirement, without affecting other requirements. Following are points to avoid Design hazard during the analysis and design process.
  • Inheritance
  • Coupling Types and Degree
  • Cohesion 
  • Optimization Techniques
  • Restructure (Refactoring) Consideration
It is said that 'Don't be STUPID: Be GRASP & SOLID!'
Ever heard of SOLID code? Probably: It is a term used by Robert Martin for describing a collection of design principles for "good and clean" code. 

To start understanding of these design principles, why not approach the problem from the other side for once? Looking at what makes up bad code.

Sorry, but your code is STUPID!
Nobody likes to hear that their code is stupid. It is offending. Don’t say it. But honestly: Most of the code being written around the globe is an unmaintainable, unreusable mess.

So what characterizes such code? What makes code STUPID?
  • Singleton
  • Tight coupling
  • Untestability
  • Premature Optimization
  • Indescriptive Naming
  • Duplication

So what are the alternatives to writing STUPID code?
The answer is, make it Simple, SOLID and GRASP.

What are SOLID rules?

  • Single responsibility principle
  • Open/closed principle
  • Liskov substitution principle
  • Interface segregation principle
  • Dependency inversion principle

What is GRASP ? 
GRASP stands for General Responsibility Assignment Software Principles / Patterns, which are the following:

  • Information Expert
  • Creator
  • Controller
  • Low Coupling
  • High Cohesion
  • Polymorphism
  • Pure Fabrication
  • Indirection
  • Protected Variations
OOPS design principles are explained in details in next section.

Thursday, August 1, 2013

Understanding Software Design Principles:

Detail Description of OOAD Principles 

DRY (Don't repeat yourself):
The first object oriented design principle is DRY, as name suggest DRY (don't repeat yourself) means don't write duplicate code, instead use Abstraction to abstract common things in one place. If you have block of code in more than two place consider making it a separate method, or if you use a hard-coded value more than one time make them public final constant. Benefit of this Object oriented design principle is in maintenance. It's important  not to abuse it, duplication is not for code, but for functionality . It means, if you used common code to validate OrderID and SSN it doesn’t mean they are same or they will remain same in future. By using common code for two different functionality or thing you closely couple them forever and when your OrderID changes its format , your SSN validation code will break. So beware of such coupling and just don’t combine anything which uses similar code but are not related.

Encapsulate What Changes:
Only one thing is constant in software field and that is "Change", So encapsulate the code you expect or suspect to be changed in future. Benefit of this OOPS Design principle is that Its easy to test and maintain proper encapsulated code. If you are coding in Java then follow principle of making variable and methods private by default and increasing access step by step e.g. from private to protected and not public. Several of design pattern in Java uses Encapsulation, Factory design pattern is one example of Encapsulation which encapsulate object creation code and provides flexibility to introduce new product later with no impact on existing code.

Favor Composition over Inheritance:
Always favor composition over inheritance, if possible. Some of you may argue this, but I found that Composition is lot more flexible than Inheritance. Composition allows to change behavior of a class at runtime by setting property during runtime and by using Interfaces to compose a class we use polymorphism which provides flexibility of to replace with better implementation any time. Even Effective Java advise to favor composition over inheritance.

Delegation principle:
Don't do all stuff  by yourself,  delegate it to respective class. Classical example of delegation design principle is equals() and hashCode() method in Java. In order to compare two object for equality we ask class itself to do comparison instead of Client class doing that check. Benefit of this design principle is no duplication of code and pretty easy to modify behavior.

Single Responsibility Principle (SRP):
"Whenever a software system must support a set of alternatives, ideally only one class in the system knows the entire set of alternatives".
Single Responsibility Principle is another SOLID design principle, and represent  "S" on SOLID acronym. As per SRP, there should not be more than one reason for a class to change, or a class should always handle single functionality. If you put more than one functionality in one Class in Java  it introduce coupling between two functionality and even if you change one functionality there is chance you broke coupled functionality,  which require another round of testing to avoid any surprise on production environment.

Open Closed Design Principle:
The Open-Closed Principle (OCP) says that we should attempt to design modules that never need to be changed. According to OCP rules classes, functions and modules should meet these two criteria
  • Open For Extension - The behavior of the module or class can be extended to meet new requirements.
  • Closed For Modification - The source code of the module is not allowed to change.
In general Classes, methods or functions should be Open for extension (new functionality can be added to them) and Closed for modification.

This design principle prevents some-one from changing already tried and tested code. Ideally if you are adding new functionality only than your code should be tested and that's the goal of Open Closed Design principle. Most of the time it is not possible to have all the modules of a software system satisfy the OCP, but we should attempt to minimize the number of modules that do not satisfy it.
The Open-Closed Principle is really the heart of OO design, and comes under SOLID design principle and OCP represents "O" from 'SOLID' acronym
Conformance to this principle yields the greatest level of reusability and maintainability.

Liskov Substitution Principle (LSP):
"Functions That Use References to Base (Super) Classes must be able to use Objects Of Derived (Sub) Classes without knowing it"
According to Liskov Substitution Principle, Subtypes must be substitutable for super type i.e. methods or functions which uses super class type must be able to work with object of sub class without any issue". LSP is closely related to Single responsibility principle and Interface Segregation Principle. If a class has more functionality than subclass might not support some of the functionality ,and does violated LSP. In order to follow LSP SOLID design principle, derived class or sub class must enhance functionality, but not reduce them. LSP represent  "L" on SOLID acronym.

But we must be careful when we implement subclasses to insure that we do not unintentionally violate the LSP. If a function does not satisfy the LSP, then it probably makes explicit reference to some or all of the subclasses of its superclass. Such a function also violates the Open-Closed Principle, since it may have to be modified whenever a new subclass is created.
  • The LSP makes it clear that the ISA relationship is all about behavior
  •  In order for the LSP to hold (and with it the Open-Closed Principle) all subclasses must conform to the behavior that clients expect of the base classes they use
  • The guarantee of the LSP is that a subclass can always be used wherever its base class is used!
Interface Segregation principle (ISP):
Interface Segregation Principle stats that, a client should not implement an interface, if it doesn't use that. This happens mostly when one interface contains more than one functionality, and client only need one functionality and not other.Interface design is tricky job because once you release your interface you can not change it without breaking all implementation. Another benefit of this design principle in Java is, interface has disadvantage to implement all method before any class can use it so having single functionality means less method to implement. ISP represent  "I" on SOLID acronym.

Programming for Interface not implementation:
Always program for interface and not for implementation this will lead to flexible code which can work with any new implementation of interface. So use interface type on variables, return types of method or argument type of methods in Java. This has been advised by many Java programmer including in Effective Java and head first design pattern book.

Dependency Injection or Inversion principle:
In object-oriented programming, the dependency inversion principle refers to a specific form of decoupling where conventional dependency relationships established from high-level modules to low-level modules, dependency modules are inverted (i.e. reversed) for the purpose of rendering high-level modules independent of the low-level modules implementation details. This SOLID design principle represent "D" on SOLID acronym.

Dependency Injection has been very well implemented in Spring framework, beauty of this design principle is that any class which is injected by DI is easy to test with mock object and easier to maintain because object creation code is centralized in framework and client code is not littered with that. There are multiple ways to implemented Dependency injection.

Applying the dependency inversion principle can also be seen as applying the Adapter pattern, i.e. the high-level class defines its own adapter interface which is the abstraction that the high-level class depends on. The adaptee implementation also depends on the adapter interface abstraction (of course, since it implements its interface) while it can be implemented by using code from within its own low-level module. The high-level has no dependency to the low-level module since it only uses the low-level indirectly through the adapter interface by invoking polymorphic methods to the interface which are implemented by the adaptee and its low-level module.

All these object oriented design principle helps you write flexible and better code by striving high cohesion and low coupling. Theory is first step, but what is most important is to develop ability to find out when to apply these design principle. Find out, whether we are violating any design principle and compromising flexibility of code, but again as nothing is perfect in this world, don't always try to solve problem with design patterns and design principle they are mostly for large enterprise project which has longer maintenance cycle.