Method Chaining

[tweet-dzone]Method chaining is a simple programming technique that can be implemented in almost any programming language. In simple words, it means that a method performs some operations on “this” object and then returns it so it can be used further more. It allows us to invoke several methods one after another, on one or different objects, usually written in the same line.

For example we can build a rectangle class using using the Method Chaining for setters. You can see the setters are a little bit different than regular setters:

class ChainedRectangle
    protected int x;
    public ChainedRectangle setX(int x) { this.x = x; return this; }

    protected int y;
    public ChainedRectangle setY(int y) { this.y = y; return this; }

    protected int width;
    public ChainedRectangle setWidth(int width) { this.width = width; return this; }

    protected int height;
    public ChainedRectangle setHeight(int height) { this.height = height; return this; }

    protected String color;
    public ChainedRectangle setColor(String color) { this.color = color; return this; }

Then if we need to build a rectangle we can write a single line for setting all the required values:

new         Rectangle().setX(10).setY(10).setWidth(13).setHeight(15).setColor("red");

Along with autocomplete option in most of todays IDEs method chaining might provide a suggestive way of doing some actions in less code.
Continue reading

Using Visitor Patterns on non Visitable Structures

The visitor pattern can be used on structures of objects which implements a specific interface defining a method called accept. In practice, in many cases, the structures are already created and we have to visit structures of already created objects. Changing hierarchies of classes for adding a new method is not a viable solution.

We need somehow to extend the structure of objects for accepting the visitors without changing them. A way of doing it would be to add a wrapper for the hierarchy classes which accepts visitors and duplicates the structure.

Drawbacks of Marker Interface Design Pattern.

A marker interface is a design pattern consisting in an interface with no methods declared. All the classes implementing this interface don’t have to implement a method for the interface(since it doesn’t have an interface), but we can say that the classes implementing the interfaces are marked. For example in Java we have the Serializable interface. It is a Marker Interface, when we create a class in order to mark it as a serializable class, it will implement the serializable, so everyone using it will know that the class is serializable.
Continue reading