Protect your dear ones

Many times you encounter code that reads as follows:


public class OuterClass{

private ContainedClass containedClass;

public ContainedClass getContained(){

return containedClass;

}

}

public class ContainedClass{

public void someMethod(){

// Do something

}

}

Typical usage:


// Usage of the class

OuterClass outerObj = new OuterClass();

ContainedClass containedObj = outerObj.getContained();

containedObj.someMethod();

This is a very common pattern and you’d have surely witnessed it in some form or another. There is something essentially wrong with it. Before I begin, Let me tell you a real life instance first:

Imagine you have a girlfriend. Hmm.. for most of us this is easy. We’ve always only imagined a girlfriend 🙂

Back to the point. Lets say you have a girlfriend. A buddy of your calls one day and asks you for her details.

Your obvious response would be “What do you need to do with her?”

He says he has nothing wrong in mind, he just needs to check on something.

Your response “Tell me what you want checked.. I’ll check and let you know”.

This would be a very typical case of how you’d react on that kind of a request. What are you doing here? You’re trying to protect her from exposing it outside, fearing it may harm her or cause her some trouble. You abstract her out from your friend and act as her messenger at times.

Now lets look back at our piece of code above.

1. The OuterClass contains an instance of ContainedClass.

2. It exposes it completely through the method getContained()

But thats not the kind of thing you did in real life.. didn’t you. You abstracted out the details from the friend who called you up.

You need to follow a similar approach here. Lets have a look at this piece of code. (With the ContainedClass remaining same)


public class OuterClass{

private ContainedClass containedClass;

public void someMethod(){

return containedClass.someMethod();

}

}

Typical usage:


// Usage of the class

OuterClass outerObj = new OuterClass();

outerObject.someMethod();

Here you have abstracted out ContainedClass from rest of the world. It can only be accessed through the OuterClass.

It is also referred to as ‘Law of Demeter”

It has many advantages:

1. It helps build more cohesive units and loosely coupled components.

2. The implementation details are hidden from outer world and can be easily modified if needed.

3. The dependencies on the calling objects are limited. It only depends on OuterClass now.

4. Testing is far easier, since you have less dependencies to satisfy.

Hope you found it useful. Do share if you have any thoughts on the above.

Object Builder alternative

Its a fairly common discussion and usually solved by

1. Constructors

MyObject(String name, String blog){
   this.name = name;
   this.blog = blog;
}

Usage:

new MyObject("Satya", "onSoftwareAndStuff");

There is a small issue with it. During creation of the object, the parameters “Satya” and “onSoftwareAndStuff” do not say what they are.  One of the alternatives with dynamic languages is (with Groovy)

 new MyObject(name : "Satya", blog : "onSoftwareAndStuff");

This is much more readable as it says.. name is Satya and blog is onSoftwareAndStuff.

2. Setters

MyObject(){
}
public void setName(String name){
     this.name = name;
}
public void setBlog(String blog){
     this.blog = blog;
}

Usage:

MyObject obj = new MyObject();
obj.setName("Satya");
obj.setBlog("onSoftwareAndStuff");

This is more readable but spreads into multiple lines and repetition of variable “obj” and method ‘set*’ is uncomfortable.

3. Alternatives

To achieve the readability equivalent to the groovy construction, lets try the following alternative:

MyObject(){
}
public MyObject name(String name){
     this.name = name;
     return this;
}
public MyObject blog(String blog){
     this.blog = blog;
     return this;
}

Usage:

MyObject obj = new MyObject().name("Satya").blog("onSoftwareAndStuff");

Probably for a 2 parameter constructor this is an overkill.. but if there are more parameters, this looks a fairly feasible solution.

Any thoughts?

Inherit or compose.. Hmm..

When designing your domain/classes, this is one decision that always results in conflicts within teams. Whether to inherit from a class or to compose that class. This is fairly subjective but here are few pointers for discussion..

Lets take this code for example:

public class GiftCollection extends HashSet {

    public Gift getRandomGift(){
        List giftList = new ArrayList(this);
        Collections.shuffle(giftList);
        return giftList.get(0);
    }
}

It is a collection of gifts that is represented as a set. The additional behavior from a set is that it can give you a random gift. It looks fairly straight-forward and would work in a even more straight-forward manner. Lets look at a usage of this..

public class GiftSelector {

    GiftCollection giftCollection;

    public GiftSelector(GiftCollection giftCollection) {
        this.giftCollection = giftCollection;
    }

    public Gift selectRandomGift(){
          return giftCollection.getRandomGift();
    }

}

This is a basic usage of the GiftCollection provided earlier. If one looks closely, though the two classes look very similar and doing similar things, there are basic differences between the two.

GiftCollection inherits a HashSet and extends to the behaviour by adding another method getRandomGift to it. However GiftSelector decided to contain a GiftCollection and delegate few calls to it.

I’ve always preferred the latter approach for following reasons:

1. The classes (both superclass and subclass) are much more flexible to change.

In this case, if GiftCollection decides to change the signature of the method getRandomGift(), it would not have an effect on the callers of GiftSelector, since it wraps the method call.

But any change to the Set implementation would affect the api of the GiftCollection class, without its knowledge. The users of GiftCollection have to change their code, though there has been no apparent change to the class. This is not an ideal scenario.

2. Easier to test.

It clearly shows that GiftSelector is much easier to test than GiftCollection. One can easily mock the dependency of the class and unit test the code. Whereas, in the case of inheritance, most mocking libraries do not provide a way to mock super classes. So its difficult to test in isolation.

3. Polymorphism through Interfaces is more flexible

One of the reasons for inheritance has been to reduce code and take advantage of polymorphic behaviour. Interfaces provide a more flexible way to achieve the same result. Composition coupled with Interfaces present a better alternative to achieve polymorphism.

This is not to say that one should not use Inheritance.

When modeling your domain, Inheritance should be used in case of a direct ‘is-a’ relationship. It should not be used only to achieve code-reuse or polymorphism.

Prefer composition over inheritance, unless you have good reasons to not do so..

Would love to hear your thoughts on this..