Saturday, August 24, 2019

Iterator Design Pattern

Iterator design pattern provides us a way to access the elements in a collection sequentially without exposing internal implementation/representation details to the client.

Programming languages provide a wide variety of collections/aggregates for storing the objects. List, Set, Arrays, Maps etc are very commonly used aggregates used by programmers. We employ different  aggregates for different scenarios and use-cases. But traversing through these aggregates always remains a requirement and is a very basic need in any kind of software program.

As these basic aggregate classes vary in underlying data structures, hence ways of traversing them also varies. We can naively provide methods in aggregates to access the elements, but this can easily expose internal details. Moreover, client code would also need to deal differently with different aggregates even though their need is same(accessing elements sequentially) and hence their are huge chances of code duplication.

Iterator pattern provides a solution to these basic aggregates traversing problems. We basically do two things when we implement iterator pattern.

First, we move the responsibility of traversing the aggregate elements to another class called Iterator. An iterator provides an interface for clients which they can use to traverse the elements. All iterator implementations thus provide this interface.

Second, we make aggregates to provide a simple interface to enable users to get hold of the iterator. Aggregates just need to instantiate appropriate iterator and provide it to client.

These simple structural changes mean several benefits. Aggregate is now only concerned about its core responsibility of storing the elements, while it is now Iterator's responsibility to traverse the elements in the aggregate. It greatly simplifies aggregate interface and also helps in achieving S of SOLID principles. Aggregate just provides interface which clients use to get hold of the iterator. Aggregate has now just two uniform interfaces to deal with irrespective the type of aggregate.

Code structure


Code structure is relatively simple.


Aggregate implements a simple interface which clients invoke to get Iterator instance. Aggregate just needs to instantiate appropriate concrete iterator implementation. Iterator provides clients the ways to traverse though the aggregate elements.

Java Iterators


Java collection classes implement Iterable interface. It maps to Aggregate in aobve UML diagram. This interface has three methods, one of which needs to be implemented by the concrete class(other two have default implementations). This method is named 'iterator' and it returns an Iterator.

Iterator is a simple interface having three basic methods for traversing collection elements:

  • hasNext: returns true is iteration has more elements
  • next: returns next element in iteration
  • remove: removes last element visited
remove has also a default implementation of throwing UnsupportedOperationException. So if a collection class doesn't want to support this method and hence doesn't implement it, exception is thrown to let client know about it.

There are several concrete implementations of Iterator available, like ListIterator. Concrete collection classes instantiates appropriate iterator implementations and return it as implementation of 'iterator' method.

Saturday, August 17, 2019

Template Method Design Pattern

Template Method Pattern is a behavioral pattern. It basically involves defining a method called Template method which defines steps/skeleton of an algorithm and hence controls the overall execution of the algorithm. These individual steps are either implemented in same class or declared abstract so that sub-classes can provide suitable implementation. Template method is made final so that sub-classes can't temper with the structure of the algorithm.

Template method design pattern is heavily employed in development of frameworks. This design pattern helps a lot in avoiding code duplication. Also, algorithm is implemented at a single place and hence it is mush easier to make any changes. This gives much better control over any future modifications.

Code structure



Code setup consists of an abstract class and concrete classes extending the abstract class. Abstract class contains skeleton of the algorithm expressed in terms of a sequence of method calls with each method corresponding to a step in algorithm execution. Some of these methods may be implemented in abstract class and are final so that sub-classes can't change them. Other methods are declared abstract and sub-classes their implementation as per their needs. Template method too is declared final so that sub-classes can't change skeleton of the algorithm.

Some hook methods can also be provided. These are concrete methods but are either empty or provide default implementation. Sub-classes can override them if they want to. Hook methods are heavily used in frameworks, for example as life-cycle methods of various frameworks.

The Hollywood Principle and Template Method

The Hollywood Principle helps to avoid dependency rot in a software system. It basically means that low level components hook into a system but its high level components which decide when and how are low level components are needed. It is popularly phrased as "Don't call us, we will call you".

Template method design pattern also exhibits similar behavior. Parent class controls the flow of the algorithm and invokes sub-class methods whenever needed. Clients interact with parent class abstraction rather than a sub-class implementation. Sub-classes' role is just to provide specific implementations of the steps in algorithm while flow control is determined by parent class only.


Saturday, August 3, 2019

Facade Pattern

Facade pattern is a structural pattern. Like Adapter pattern, it also alters an interface but with the purpose of simplifying it.

Many times we have to work with a complex software system which consists of various parts. These individual parts have their interfaces for clients to work with. We need to use system as a whole to get some work done and this work is done by interacting with different individual parts of the system. Interacting with so many subparts and hence so many interfaces makes our task quite complex and involves many steps.

We can make use of Facade pattern in such situations to simplify interaction with a complex system. We design a simple interface, called as Facade, for client to work with, and Facade internally interacts with different parts of the complex system. So now all the complex implementation of interacting with various interfaces of the complex system is within the Facade and client just needs to interact with this simple interface. Facade doesn't restrict access to low level functionalities of the system and client can still access low level classes if needed. 

Code structure

To implement a Facade, we design a class which is composed of different subparts of the complex system we plan to provide simple interface for. This class is our Facade for that complex system.


Facade is composed of different subparts of the complex system needed to get some work done. Client just interacts with Facade.

Facade pattern is also a way to implement OO design principle of least knowledge(also known as Law of Demeter) in a system. This principle seeks to reduce number of classes an object interacts with as much as possible so that our system is less fragile and less complex to understand. With Facade pattern, client now only interacts with Facade instead of all those subparts in the complex system.


Adapter Pattern

Adapter pattern is a structural pattern. It enables us to make classes work together which otherwise can't because of incompatible interfaces.

Suppose we have an existing software, and we are making use of a third party library to get some work done. Library has an interface exposed to work with it, and hence we have designed our software to be compatible with this interface. But down the line, there is a new library available and it performs better than our current library. So we decide to replace older one with this new super library.  But there is hurdle. New library exposes an interface which is different from interface we have designed our software to. We don't want to change our existing design, and of-course we can't change new library's interface.
Adapter pattern comes to our rescue. It enables us to design a class which sits between our software and new library and acts as a mediator and adapts the new library interface into what our software expects. This mediator class is called Adapter. It basically receives requests from a client and transform them into requests which a receiver can understand.

Code structure

Adapter pattern enables us to encapsulate the changes which we need to do when ever interface we need to work with undergoes a change. This decouples client code from the interface changes, and its the adapter class which undergoes that change and hence client doesn't need to be modified whenever client needs to work against a different interface.


Client only knows of interface it is designed to work with. We call it Target. Adapter class implements Target. It is composed of Adaptee which has the interface Client is not compatible with. but it has the action that Client wants to perform. So Client invokes request on Adapter which delegates the request to Adaptee.
If Adaptee changes, changes we need to make are only in Adapter and hence Client is decoupled from Adaptee.

Adapter pattern is heavy with good OO design principles. Client is bind to an interface, rather than an implementation. Also, Adapter uses composition to wrap the Adaptee. Moreover, we can now use Adapter with subclasses of Adaptee.

Object and class adapter

In Adapter pattern discussion so far we have wrapped Adaptee object inside an Adapter. This is object based approach and it uses composition. We can also have a class based approach wherein Adapter subclasses an Adaptee class. So in class based approach, we use inheritance instead of composition. This reduces flexibility as object based approach enables us to work with subclasses of Adaptee. But in class based approach we can override Adaptee's behaviour.

Example

Older types of Java collections like Vector and Stack provides Enumeration interface to work with these collections. Enumeration has methods to step through the collection, like hasMorElements, nextElement().Later Java versions introduced Iterator interface to iterate step through the new types of Collections, like List. 

If we want to make use of Iterator interface in our code, but are still working with legacy code which exposes Enumeration interface, we can make use of Adapter pattern.

Our code becomes Client, Iterator becomes Target interface, Enumeration class becomes Adaptee. We need to design Adapter class to make our code work with Iterator while underneath Adapter interacts with Enumeration. Two methods in Enumeration directly maps to Iterator methods(hasNext(), next()), but Enumeration doesn't have any method which corresponds to remove() in Iterator. So we make a compromise here, and throw UnsupportedOperationException in our implementation of remove() in Adapter class.



What we may not like

As requests are delegated, so there is an overhead.