Get rid of Inheritance Forest: Part 1

Get rid of Inheritance Forest

While doing code review, I have seen many times that there is a potential danger of creating a lot of inherited classes, meaning a simple change in business requirements may make things unmanageable. So, surely, this is a serious code smell, and we must take action.

One of the business cases comes in my mind is.

Business Case
If criteria are interlinked, the outcome product can be any combination of those criteria.
To put it simply, say the requirement is:

 "We have to create a ball, and the ball can glow-in-the-dark, and/or it can be printed with a smiley, and/or it can be scented, etc."

So here, the two main criteria would be:

  1.  A ball can be decorated with (glow-in-the-dark properties, a smiley, scented, etc.)
   2. It can have any combination of the above properties like (a Disco-Light smiley ball, a smiley Sandalwood scented  ball, a glow-in-the-dark Rosy scented ball, etc.)

According to the requirements, If we try to solve the problem by create interfaces for each decoration:
IGlowinthedark
ISmiley
IScent
And then create a concrete product that implements either or all of the interfaces as per requirements and then implement the each interfaces method.

The design seems to be right in naked eye, as it maintains the "coding to an interface" principle and welcomes the future changes as well!

Fig 1: Multiple Inheritance

But, is it well designed?
Put your thinking cap on, before reading the next part of the article. 

In my opinion, most of the time this would not be considered a good design for this application. So, let me explain my reasoning...

The Problem
This design very poorly handles decorations. Why? Say we have n number of decorators (Glow-in-the-dark, Smiley, Scented, etc).  each has m number of implenetation So, there will be Cn(C(m)) possible combinations.

Each decorator has multiple implementation like 

IGlowinthedark can have Disco Lights, Led Light etc
ISmiley can have Happy meme,ROFL meme etc
IScent has different fragrances like Sandalwood,Rose etc.

When n and m is small, there is a relatively small number of combinations. But what if n and m is a large number? How many combinations are there then?

We'd need to create a concrete class for each possible combination, so if the total number of combinations of (n,m) are 1,000, then we have to create 1,000 concrete classes to satisfy all these different combinations, like a Disco-light smiley ball, a smiley Sandalwood scented  ball, a glow-in-the-dark Rosy scented ball, etc.  etc.)

This is a massive failure of our chosen design. Our code base will be large and unmanageable. Somehow, we need to deal with the combination problem—we need to change our design.

GOF to the Rescue
Can you guess which GOF patterns will rescue us? Take a look at the picture below for reference.

Can you find the pattern?

If you guessed Decorator then congratulations, you are correct! This pattern will rescue us from this scenario. There are many other Solution by which we can get rid of this problem in later tutorials I will discuss about other solutions.

But before we get to that, let's discuss why our previous design fails.

If we read the requirements minutely, we would understand that the complexity lies in creating the many different combinations of the decorators of the ball. Through inheritance, one concrete class describes only one possible combination, as its implements either or all (IGlowinthedark and ISmiley or IScent) so it is static in nature.

The combination is proportional to the number of concrete classes, so concrete classes linearly increase as the combination increases. Our main failure lies in failing to dynamically create combinations. As it is, the outcome creates an Inheritance Forest, which is ever-expanding as these combinations/individual implementation grow in number.

It is like printing 1,000 array elements manually without using any loop.

To solve this riddle we are searching for a way to create a dynamic combination to expel the Inheritance Forest. So, all problems boil down to the following question: How can we push combination/behavior runtime dynamically?

The Decorator Pattern
The intent of the Decorator pattern is to add responsibility/behavior at runtime to an Object. That's exactly the answer we're searching for.

How Decorator Works
In the Decorator pattern, we encapsulate the main/core object inside a wrapper interface. In this case, the main Object is Ball and the interface is IBall. Now, every responsibility/behavior/criteria also implements the same Interface IBall. In our case, Glow-in-the-dark, Smiley, Scent implement IBall as well. And we have a composition with the same interface (IBall), which acts as a Wrapper Object.

Through this technique, we can achieve two things:

1. Any component that implements IBall has a (HAS-A) relationship with another component that also implements IBall. Through this, we can associate any component with another and achieve dynamic behaviors.

2. One component performs its work, then delegates the work to its associated (HAS-A) component. Again, that component follows the same pattern, which creates a delegator chain. At last, it produces a concrete product made by any combination.



Let see the Diagram of Decorator
Fig 2: Decorator Pattern





.
Coding :

Enough theory now see How to achieve run time behaviors through decorator





Decorator Interface:

public interface IBall {
   
    public void createBall();

}


Core Component :
Now create the core component which is the base, on top of it will add behavior as wrapper Object.



package com.example.decorator;
public class CoreBall implements IBall{

    IBall wrappeBall;
    public CoreBall(IBall wrappeBall){
        this.wrappeBall=wrappeBall;
    }

    @Override
    public void createBall() {
    System.out.println("Ball creation End");
    if(wrappeBall !=null)
    wrappeBall.createBall();
    }

}


Wrapper Components:

Now we will create main wrapper Component like Colors of Ball (Red,Blue,Green) and materials of the ball (Rubber,Polythene,Plastic etc.) So we can create any combinations by using them.

Light.java
package com.example.decorator;

public class Light implements IBall {
    IBall wrappeBall;
    public Light(IBall wrappeBall) {
        this.wrappeBall = wrappeBall;
    }
    @Override
    public void createBall() {
        System.out.println("Decorate with Disco Light");
        if(wrappeBall !=null)
        wrappeBall.createBall();
    }
}
Smiley.java

package com.example.decorator;
public class Smiley implements IBall{
    IBall wrappeBall;

    public Smiley(IBall wrappeBall) {
        this.wrappeBall = wrappeBall;
    }

    @Override
    public void createBall() {
        System.out.println("Decorate with Happy Smiley");
        if(wrappeBall !=null)
        wrappeBall.createBall();
    }
}




Test:

No we will create Multiple combinations on the fly as each component implements IBall interface and expect a IBall interface as argument of constructor so we can pass any components into any other components.


Main.java

package com.example.decorator;

/**
* @author Shamik Mitra
*
*/
public class Main {
    public static void main(String args[]) {
        IBall ball = new Smiley(new Light(new Ball(null)));
        ball.createBall();
        System.out.println("*********");
       }
}

Output :

Decorate with Disco Light

Decorate with Smiley

Ball creation End

*********


TIP: we have learned that Decorator can create multiple combinations by delegating responsibilities so if there is a requirement where two or more constraints can combine with each other to make a new product we can think of Decorator and not going for Multiple Inheritance.




















An Interview Question on Spring Singleton

Spring Singleton


While taking interview on Spring core, Often I ask a question

What do you mean by Spring Singleton scope?

Most of the time I got an answer like Spring singleton scope manages only one object in the container.

Then after getting this answer I will ask the next question,

Please tell me what will be the output of the following program



Spring.xml file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
   
    <bean id="scopeTest" class="com.example.scope.Scope" scope="singleton">
    <property name="name" value="Shamik Mitra"/>    
    </bean>    
    <bean id="scopeTestDuplicate" class="com.example.scope.Scope" scope="singleton">
          <property name="name" value="Samir Mitra"/>    
    </bean>
</beans>


Scope.java

package com.example.scope;
public class Scope {
   private String name;

   public String getName() {
      return name;
   }

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

   @Override
   public String toString() {
      return "Scope [name=" + name + "]";
   }

}

Main class

package com.example.scope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {

   public static void main(String[] args) {
      ApplicationContext ctx = new ClassPathXmlApplicationContext(
              "configFiles/Scope.xml");

      Scope scope = (Scope) ctx.getBean("scopeTest");
      Scope scopeDuplicate = (Scope) ctx.getBean("scopeTestDuplicate");      
      System.out.println(scope==scopeDuplicate);
      System.out.println(scope  + "::"+ scopeDuplicate);
     

   }

}


Here I create two beans of Scope class and make spring scope as singleton now checking the references.


Now Interviewee got confused, and I will get three types of answer

This code will not compile throw error at runtime, as you can not define two spring beans of the same class with scope singleton in XML. (Very rare).
References check will return true, as container maintains one object so both bean definition will return the same object so memory location would be same.(Often)
They said References check will return false and Spring singleton is not worked as they have told earlier.(few)



The third answer is the correct answer, Spring singleton is not worked as Java Singleton.

If we see the output of the program we will understand that it will return two different instances, So in a  container, there may be more than one object in spite of the scope is the singleton.




Output:

Reference Check ::false
Scope [name=Shamik Mitra]::Scope [name=Samir Mitra]


So again Question is What do you mean by Spring Singleton Scope?

According to Spring documentation

When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.
To put it another way, when you define a bean definition and it is scoped as a singleton, then the Spring IoC container will create exactly one instance of the object defined by that bean definition. This single instance will be stored in a cache of such singleton beans, and all subsequent requests and references for that named bean will result in the cached object being returned.


So it is clear that for a given id Spring container maintains only one shared instance in singleton cache.

In my example, I use two different ids (scopeTest, ScopeTestDuplicate) so Spring container creates two instances of the same class and bound it with respective ids and stores it in singleton cache.

You can think Spring Container manage Key-value pair where Key is the id or name of the bean and value is bean itself , so for a given key, it maintains singleton. So if we use that key as a reference of other beans the same bean will be injected to other beans.





In a one words , Spring guarantees exactly one shared bean instance for the given Id per IoC container unlike Java Singleton where Singleton hard codes the scope of an object such that one and only one instance of a particular class will ever be created per ClassLoader.

Picture taken from Spring docs