Design thoughts on Open/Close Principle

Open close principle


According to Bertrand Meyer
 “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification

Read it the first time one can think the definition is a bit abstract as design principals are.
But the aforesaid statement is very powerful and can save you from fragile design and wired bugs.

The statement says that Design should be done such a way so it can welcome new changes
but without tampering the old implementation. Because your old implementation is tested and run fine in production, to welcome new changes it is not good to break old ones. So this principal says welcome new changes on top of old changes.

Let take an example, suppose requirement is to create a class which determines the area of a Rectangle.

This is very easy to develop for an OO Developer

Initial code like
package com.example.openclose;

public class AreaBuilder {
      
       public void calculateRectangleArea(int length,int breadth)
       {
              System.out.println("Area of Rectangle is " + length*breadth);
       }
      
       public static void main(String[] args) {
             
              AreaBuilder builder = new AreaBuilder();
              builder.calculateRectangleArea(20, 10);
             
             
       }

}

The code is tested and then deployed.  But after some day new feature request raise now this class should able to compute the area of the square also.

Inexperienced developer will incorporate the requirements in following way

package com.example.openclose;

public class AreaBuilder {
      
       private void calculateRectangleArea(int length,int breadth)
       {
              System.out.println("Area of Rectangle is " + length*breadth);
       }
      
      
       private void calculateSquareArea(int length)
       {
              System.out.println("Area of Square is " + length*length);
       }
      
       public void getArea(String type,int length,int breadth)
       {
              if("square".equalsIgnoreCase(type))
              {
                     calculateSquareArea(length);
              }
              else if("rectangle".equalsIgnoreCase(type))
              {
                     calculateRectangleArea(length,breadth);
              }
       }
       public void getArea(String type,int length)
       {
              getArea(type,length,length);
       }

      
      
      
       public static void main(String[] args) {
             
              AreaBuilder builder = new AreaBuilder();
              //builder.calculateRectangleArea(20, 10);
              builder.getArea("square", 10);
              builder.getArea("rectangle", 10,5);
             
             
       }

}

Certainly, it will meet the requirements but break the Open close principal. Also, this code has some shortcomings

1.    To incorporate new changes, we will modify the old class so it breaks the statement “closed for modification”.
2.    The new code can break old functionality if the implementation is wrong, so we not only fail to deliver new code but also break the old functionality which is not intended.
3.    For every new shape added in the system, we need to modify this class and make the class more complex and less cohesive.

To overcome aforesaid problems, we try to follow the principal refactor the code.

“Open for extension closed for modification”
In java, the extension can achieve through inheritance. So we can create an interface called “shape” and a method called area() in it so every shape can implement area method and provide its implementation.
So if a new shape is coming we just create a new class and implement shape interface if anything goes wrong only that shape class will be impacted not the previous implementations thats why the Open close principal is so important in design.

Refactor code:
package com.example.openclose;

public interface shape {
      
       public void area();

}

package com.example.openclose;

public class Rectangle implements shape{
       private int length;
       private int breadth;
       Rectangle(int length,int breadth)
       {
              this.length=length;
              this.breadth=breadth;
       }

       @Override
       public void area() {
              System.out.println("Area of Rectangle is " + length*breadth);
             
       }

}

package com.example.openclose;

public class Square implements shape{

       private int edge;
       public Square(int edge)
       {
              this.edge=edge;
       }
       @Override
       public void area() {
              System.out.println("Area of Square is " + edge*edge);
             
       }

}

package com.example.openclose;

public class ShapeManager {
      
       private static ShapeManager manager = new ShapeManager();
      
       shape shape;
      
       private ShapeManager()
       {
             
       }
      
       public static ShapeManager getInstance()
       {
              return manager;
       }
      
      
       public void getArea() throws IllegalArgumentException
       {
              if(shape ==null)
              {
                     throw new IllegalArgumentException("please provide a Shape");
              }
              shape.area();
       }
      
      
       public shape getShape() {
              return shape;
       }



       public void setShape(shape shape) {
              this.shape = shape;
       }



       public static void main(String[] args) {
             
              shape rect = new Rectangle(10,20);
              shape square = new Square(10);
             
              ShapeManager instance = ShapeManager.getInstance();
              instance.setShape(rect);
              instance.getArea();
             
              instance.setShape(square);
              instance.getArea();
             
             
       }

}

Output :

 Area of Rectangle is 200
Area of Square is 100


Hooray, we refactor the code and it is maintaining the principal. We can incorporate any number of shape by adding new classes and without modifying the old classes.

The client is happy now they want to introduce a brand new feature Now shape can be drawn on a paper.
So inexperinced developer thought it is easy task to do just add a new method call drawShape() on shape interface it will meet client needs and not breaking the Open Close principle
Let’s do that,

package com.example.openclose;

public interface shape {
      
       public void area();
      
       public void drawShape();

}

package com.example.openclose;

public class Rectangle implements shape{
       private int length;
       private int breadth;
       Rectangle(int length,int breadth)
       {
              this.length=length;
              this.breadth=breadth;
       }

       @Override
       public void area() {
              System.out.println("Area of Rectangle is " + length*breadth);
             
       }

       @Override
       public void drawShape() {
             
              System.out.println("drawing recangle on paper" );
             
       }

}
 package com.example.openclose;

public class Square implements shape{

       private int edge;
       public Square(int edge)
       {
              this.edge=edge;
       }
       @Override
       public void area() {
              System.out.println("Area of Square is " + edge*edge);
             
       }
       @Override
       public void drawShape() {
              System.out.println("drawing square on paper" );
             
       }

}

package com.example.openclose;

public class ShapeManager {
      
       private static ShapeManager manager = new ShapeManager();
      
       shape shape;
      
       private ShapeManager()
       {
             
       }
      
       public static ShapeManager getInstance()
       {
              return manager;
       }
      
      
       public void getArea() throws IllegalArgumentException
       {
              if(shape ==null)
              {
                     throw new IllegalArgumentException("please provide a Shape");
              }
              shape.area();
       }
      
       public void draw() throws IllegalArgumentException
       {
              if(shape ==null)
              {
                     throw new IllegalArgumentException("please provide a Shape");
              }
              shape.drawShape();
       }
      
      
       public shape getShape() {
              return shape;
       }



       public void setShape(shape shape) {
              this.shape = shape;
       }



       public static void main(String[] args) {
             
              shape rect = new Rectangle(10,20);
              shape square = new Square(10);
             
              ShapeManager instance = ShapeManager.getInstance();
              instance.setShape(rect);
              instance.getArea();
              instance.draw();
             
              instance.setShape(square);
              instance.getArea();
              instance.draw();
             
             
       }

}

Output :
Area of Rectangle is 200
drawing recangle on paper
Area of Square is 100
drawing square on paper

So far so good. But is it really maintains Open/close principle? In bare eyes, yes but if we put our thinking cap, there is clue in client needs which can break this principal
Clients want shape can be drawn on a paper but it can be drawn on Computer or in canvas also.

So in future, if clients want to draw on the computer. To incorporate this change Open close principal will be broken. As again we need to put if /else check on each shape drawshape() method.



Now we will discuss How judiciously we can design open close principle?
1.    I classified Objects properties in two ways a. primary properties b. Composition properties.
2.    If any functionality(method) depends on only primary properties i.e which are the sole properties of that domain object.  You can declare them in the interface or abstract class from which this class inherited.
3.    If a functionality depends on an external entity always use composition rather than inheritance. (Here draw functionality depends on paper an external entity so we should use composition rather than inheritance)

Now refactor the code again to support draw function.
package com.example.openclose;

public interface shape {
      
       public void area();
      
       public void drawShape();

}

package com.example.openclose;

public interface drawAPI {
      
       public String draw();

}

package com.example.openclose;

public class PaperDraw implements drawAPI{

       @Override
       public String draw() {
              return "paper";
             
       }

}

package com.example.openclose;

public class ComputerDraw implements drawAPI{

       @Override
       public String draw() {
              // TODO Auto-generated method stub
              return "computer";
       }

}

package com.example.openclose;

public class Rectangle implements shape{
       private int length;
       private int breadth;
       drawAPI api;
       Rectangle(int length,int breadth,drawAPI api)
       {
              this.length=length;
              this.breadth=breadth;
              this.api=api;
       }

       @Override
       public void area() {
              System.out.println("Area of Rectangle is " + length*breadth);
             
       }

       @Override
       public void drawShape() {
             
              String medium = api.draw();
              System.out.println("drawing recangle on " + medium);
             
       }

      

}

package com.example.openclose;

public class Square implements shape{

       private int edge;
       drawAPI api;
       public Square(int edge,drawAPI api)
       {
              this.edge=edge;
              this.api=api;
       }
       @Override
       public void area() {
              System.out.println("Area of Square is " + edge*edge);
             
       }
       @Override
       public void drawShape() {
              String medium=api.draw();
              System.out.println("drawing square on "+medium );
             
       }

}

package com.example.openclose;

public class ShapeManager {
      
       private static ShapeManager manager = new ShapeManager();
      
       shape shape;
      
       private ShapeManager()
       {
             
       }
      
       public static ShapeManager getInstance()
       {
              return manager;
       }
      
      
       public void getArea() throws IllegalArgumentException
       {
              if(shape ==null)
              {
                     throw new IllegalArgumentException("please provide a Shape");
              }
              shape.area();
       }
      
       public void draw() throws IllegalArgumentException
       {
              if(shape ==null)
              {
                     throw new IllegalArgumentException("please provide a Shape");
              }
              shape.drawShape();
       }
      
      
       public shape getShape() {
              return shape;
       }



       public void setShape(shape shape) {
              this.shape = shape;
       }



       public static void main(String[] args) {
             
              shape rect = new Rectangle(10,20,new ComputerDraw());
              shape square = new Square(10,new PaperDraw());
             
              ShapeManager instance = ShapeManager.getInstance();
              instance.setShape(rect);
              instance.getArea();
              instance.draw();
             
              instance.setShape(square);
              instance.getArea();
              instance.draw();
             
             
       }

}

Output :
Area of Rectangle is 200
drawing rectangle on computer
Area of Square is 100
drawing square on paper


Now draw() method is in shape class as we assume every shape is drawable and we create  composition between  shape family and drawAPI family.

But to maintain Open close principal we need to create a lot of classes. Make code complex.
I throw an open question,

 If a client is reluctant for change or development time is short or for a system where change requests are very less, then should we always maintain open/close principle or break that rule and make the code much simpler?

JAVA References And Garbage Collection

Different Java references

Many java developers are not aware that java has mainly 4 types of references.
1.       Strong Reference
2.       Weak Reference.
3.       Soft Reference.
4.       Phantom Reference.


But why there are different types of reference? What will be there usage?

To understand that I will take an Example,

Suppose in an Application, frequently one needs to fetch data from a MASTER TABLE. As a clever developer certainly he/she don’t want every time application will hit the database, it will degrade the performance.
Obviously, the choice is Cache. Cache is a class (Internally a Map) ,first application will hit the cache to check data is available there else hit the database and put the entry in cache so next time it can be found in the cache to skip database call.

Is it going to improve the performance?
It will depend on the situation, If Master table has less entry this will work fine and certainly increase the performance. But if Master Table has huge entries it will create a problem as a time to time Cache map is growing and load entries from Master table. Now instead of providing better performance it will be the cause of Out of memory. Imagine a situation where all rows in this huge master table have been loaded to cache.  Think about the size of cache it will take most of the JVM memory even cause Out of memory.

So what should we do?
One thing we can do restricts the number of entries in the Cache. And delete the old entries from the cache.  I don’t go to the implementation part ,think is it going to solve the problem?

It will partially solve the problem but it will take constant memory in JVM. Although some of the Object in the cache is not used for a long time.

What will be the Ideal solution?
The Ideal solution would be if we can make such type of cache which is dynamic in nature it will growing and shrinking as per need.
So we need some kind of technique where we can delete those entries which will not use for a long time and sits in cache.

To achieve it , Java provides different type of reference in java.lang.ref package.

Strong Reference:  We use Strong reference in java everywhere.  Create an object then assigns it to a reference. Note that if object has a strong reference this object is never be garbage collected.
Example:
HelloWorld hello = new HelloWorld();
Here hello is strong reference to HelloWorld Object.

Soft Reference:  If an Object has no Strong reference but has a Soft Reference then garbage collector reclaims this Object’s memory when there is not enough memory, and garbage collector needs to freed up some memory. In spite of soft reference garbage collector reclaims this Object’s memory. To get a Strong reference from soft reference one can invoke get() method. If the Object is not garbage collected it returns the object else return null.

Weak Reference: If an Object has no Strong reference but has a Weak Reference then garbage collector reclaims this Object’s memory although there is enough memory. To get a Strong reference from soft reference one can invoke get() method. If the Object is not garbage collected it return the object else return null.

Phantom Reference: If an Object does not have aforesaid references then may it has phantom references. Phantom references can’t be accessed directly. Using get() method it always returns null. So what will be use of such reference? Think an object can referred by a strong reference in finalize block so to garbage collect this Object need second time to run the GC. But by phantom reference only one GC execution will suffice to GCed the same.

Example of different type of reference.

package com.example.reference;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;

public class ReferenceExample {
      
       private String status ="Hi I am active";
      
      
      
       public String getStatus() {
              return status;
       }



       public void setStatus(String status) {
              this.status = status;
       }
      
      



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



       public void strongReference()
       {
              ReferenceExample ex = new ReferenceExample();
              System.out.println(ex);
       }
      
       public void softReference()
       {
              SoftReference<ReferenceExample> ex = new SoftReference<ReferenceExample>(getRefrence());
              System.out.println("Soft refrence :: " + ex.get());
       }
      
       public void weakReference()
       {
              int counter=0;
              WeakReference<ReferenceExample> ex = new WeakReference<ReferenceExample>(getRefrence());
              while(ex.get()!=null)
              {
                     counter++;
                     System.gc();
                     System.out.println("Weak reference deleted  after:: " + counter + ex.get());
              }
             
       }
      
       public void phantomReference() throws InterruptedException
       {
              final ReferenceQueue queue = new ReferenceQueue();
              PhantomReference<ReferenceExample> ex = new PhantomReference<ReferenceExample>(getRefrence(),queue);
              System.gc();
              queue.remove();
              System.out.println("Phantom reference deleted  after");
             
             
       }
      
      
      
       private ReferenceExample getRefrence()
       {
              return new ReferenceExample();
       }
      
       public static void main(String[] args) {
              ReferenceExample ex = new ReferenceExample();
              ex.strongReference();
              ex.softReference();
              ex.weakReference();
              try {
                     ex.phantomReference();
              } catch (InterruptedException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
       }
      

}


Output :
ReferenceExample [status=Hi I am active]
Soft refrence :: ReferenceExample [status=Hi I am active]
Weak reference deleted  after:: 1null
Phantom reference deleted  after



Look at , softReference() method here we create a soft reference as memory is available so reference is not Gced.
For weakRefrence(), reference is GCed immediately as no strong reference is there.

Same for Phantom reference.


Comparison: