Showing posts with label design patterns in java. Show all posts
Showing posts with label design patterns in java. Show all posts

Wednesday, June 7, 2017

3 wise men on Tell Don't ask

A story on Tell Don't ask Principle

wisemen.jpg

John, Doe, and Marcus are three good friends. They have over 20 years of experience Java/JEE stack and working in IBM, Cognizant and TCS respectively. They have immense experience in design pattern and all the new technologies and respected by their colleague for Exceptional insight on the Technology Stack.
They are planning to go for a vacation in the upcoming weekend to enjoy their spare time with lots of Burger, whiskey, and cooking. John has an Outhouse in a village so they planned to go there by driving.
At last, the day came they pack their Beer, Whiskey, and Burger and headed towards John outhouse it was far away from Town. At evening they reached the outhouse and prepare some snacks for their whiskey and sit together in a round table to enjoy Chicken roast and Whiskey.
Suddenly the power cut happens, The room is so dark that no one can see anything, from outside they can hear the Call of Cricket, Marcus put on his mobile flashlight, now they can see each other.
Doe breaking the silence by saying,
“Oh well, this ambiance is perfect for a horror story can anyone share any real life experience?”
Marcus replied in a witty way
“Umm No, I believe all we are from town and busy with IT industry so sorry can not share any horror experience but can share some Java experience which still frightened me”
John and Doe’s Architect instinct flashed with this proposal.
They said, “ Oh yes what would be more good to discuss about something which frightened us an Architect in this ambiance, it is same as Horror Story :).”

Marcus slowly demonstrated the problem.
Marcus: As an Architect when I design a solution for a problem it always frightened me what we encapsulate and what portion we expose to our client program?
John and Doe Nodded their head.
Marcas Continue with his speech,
There are lots of OOPs principle which says how judiciously you can encapsulate your classes or API from outside world.
Take an Example, The  Tell Don’t Ask principle, It says us always tell to Object, in a layman term instruct Object what to do never query for an internal state and take a decision based on that because then you loose control over the object.
Take a simple example suppose I want to write a Parcel Delivery Service and there are two domain Objects Parcel and Customer so how should we design it.
If I write following code fragments

/**
*
*/
package com.example.basic;

/**
* @author Shamik Mitra
*
*/
public class PercelDeliveryService {
   
   
    public void deliverPercel(Long customerId){
       
        Customer cust = customerDao.findById(customerId);
        List<Percel> percelList = percelDao.findByCustomerId(customerId);
       
        for(Percel percel : percelList){
           
            System.out.println("Delivering percel to " + cust.getCustomerAddress());
            //do all the stuff for delivery
        }
       
    }

}


According to Tell Don’t Ask it is a violation and should be avoided. In Parcel Delivery Service I try to fetch or ask Customer Address so I can perform the delivery operation so here I query the internal state of the Customer.
And why it is dangerous?
If later if the delivery functionality change says now it also include an email address or mobile so I have to expose these details so exposing more and more internal state think about the other services they may also use the same email address or Customer address. Now If I want to change the Customer Address return type String to Address Object then I need to change all services where it has been used, so a gigantic task to perform and increases risk factor of breaking functionality. Another point is as internal state is exposed to many services there is always a risk to pollute the internal state by a service and it is hard to detect which service changed the state. In one word I loose the control over my object as I don’t know which services use/modify my Object internal state. Now if my object is used by the Internal services of a monolith application I can search the usage in IDE and refactor them but If the Object is exposed through an API and This API used by other organization then I am gone, It really hurts our company reputation and as an architect, I would be fired.
So I can say

Action: More you Expose Internal state
Outcome:  Increase coupling, Increases Risk, Increase Rigidity.


Now again look the solution I provided,
Doe chuckled and guess which point Marcus trying to make so he interrupted him and start saying.
Doe: So Marcus you want to tell if we follow Tell Don’t Ask principle then there are couple of ways we can refactor the problem
1. make an association between Customer and Parcel . and it would be lazy loaded and deliver method should be in Customer Object so from the service we call deliver then deliver method fetch parcel list and deliver it, so if the Internal return type change from String to Address only “deliver” method should be affected.
Like this,
/*
*
*/
package com.example.basic;

/**
* @author Shamik Mitra
*
*/
public class ParcelDeliveryService {
   
   
    public void deliverParcel(Long customerId){
       
        Customer cust = customerDao.findById(customerId);
        cust.deliver();
    }

}

public class Customer{

    public void deliver(){
        List<Percel> percelList = getPercelList();
      for(Percel percel : percelList){
           
            System.out.println("Delivering percel to " + this.getCustomerAddress());
            //do all the stuff for delivery
        }
       
    }
}



By doing this I maintain Tell Don’t Ask principle properly and decreases the risk of exposing internal state and free to modify my class attributes as all behaviors are tied locally with attributes a nice way to achieve encapsulation.
2. We can create a command Object where we pass the Parcel details and pass the command object to Customer Model, the delivery method extracts the Parcel list and deliver it to the respective customer.
But both policy breaks another principle that is Single Responsibility Principle, SRP(Single Responsibility Principle) says A class has only one reason to change.
But If I think in a reverse way, why we write Services? Because each service does one job like Person Delivery Service responsible for “delivery parcel related “ operations so it maintains SRP and this service only change if there are any changes in Parcel Delivery mechanism and if it breaks other services will not be affected unless other services depend on it.
But according to Tell Don’t Ask all Customer related behaviors should be moved into Customer class so we can tell /Instruct/command Customer class to do a task. So Now Customer class has much responsibility because all Customer-related service code now goes into Customer Model. So Customer has more reason to change so increase the risk factor of failing.
So Now we are back in the same problem risk factor.
If exposing internal state then the risk for modifying attribute if move all behavior into a class then the risk of modifying functionality break the system.
So SRP and Tell Don’t Ask principle contradict in this context.

John: John nodded his head and started with his husky voice, Yes this is really a problem
not only this, If we want to implement a cache in a service or want to implement Aggregation function like Percell delivery rate charge according to distance or Account type, Find most parcels sent to a locality we use Aggregator service where we ask for internal state and compute the result. So often we break Tell Don’t Ask principle. Even as per current trend, Model Object should be lightweight and should not be coupled with each other. If the business needs an information which distributes over multiple models we can write an aggregator service and query each model and compute the result , so we querying internal state. Think about Spring data.
Now If we look in another perspective, according to the Domain-driven Design, In a Parcel Delivery Context (Bounded context) is Customer responsible for delivering the parcel?
Absolutely not, In that context Delivery Boy is responsible for delivering the parcel to the customer. For that Delivery boy needs Parcel and Customer Model, and in that context only Customer name and Address details required and for parcel Id, parcel name will be required so as per DDD we create an Aggregate Model DeliveryBoy where we have two slick Model Customer and Percell because in this context we don’t need customer other details and parcel other details like customer account details, Customer birthdate etc, Context wise model is changed so no one big model for customer where all attribute and behaviour resides rather small slick models based on bounded context and an Aggregate model querying these slick model and perform the work.
By doing this we can mix and match SRP and Tell Don’t ask. For a service perspective we only tell /command DeliveryBoy Aggregate model to do something, so Service maintains SRP and Tell don’t ask, Our Aggregate model also maintain SRP but querying Customer and Parcel Model to do the operation.

Like



/**
*
*/
package com.example.basic;

/**
* @author Shamik Mitra
*
*/
public class ParcelDeliveryService {
   
   
    public void deliverParcel(Long customerId){
       
        DeliveryBoy boy = new DeliveryBoy();
        boy.deliver(customerId);
    }

}

public class DeliveryBoy{
    Customer cust;// Context driven model
    Percel percel;
    public void deliver(Long id){
        //do stuff
//load customer slick model
//load Percel slick model
//Deliver the same by quering

        }
       
    }
}

Marcus joined and says let's take one step further as DDD insists  Microservice, so in Microservice we try to break a monolith using functional decomposition( A function is a Bounded context in DDD) so one service doing one task maintains SRP principle and if we needed and information which distributes over multiple services we create an Aggregator service and querying individual service and do the task so Microservice often breaks Tell Don’t Ask
Doe joined and says So there is no silver bullet and not all principles are good in all context, Based on the context you have to judge which principles you follow sometimes you need to compromise, may for a specific principle viewpoint your code is bad but for a given context it is optimum.

Principles are generic and they are context free but real life solution are based on context so fit principles based on context not the reverse.

In the meantime Light comes, so John said here we are for fun let stop the discussion and concentrate on Whiskey and Roast !!!!
Everyone agreed and change the topic.
Conclusion : As a Narrator, My question to all viewers, what do you think about the talk they did, is there are any points they left off which needs attention while designing?

Wednesday, May 10, 2017

A Story on Flyweight pattern

The Flyweight pattern
Flyweight Pattern

Swastika wants to introduce Theme in her blog but she is facing a problem.

The Problem:

Her blog is a combination of multiple widgets like Header widget, Footer Widget, Content Widget, Follower widget etc.

And those widgets are populated by backend call or any web service call in a simple term to load widget repetitively considered as a costly operation.

But as Swastika wants to introduce Theme, Theme can reorder the widget position as well as the color of the widgets, As Look and Feel are different for the different theme.

So the question pop up in Swastika’s mind is

Every time User changes the Theme should she reload the widget and populate the data?
Then it is a very bad design as it will load all costly widgets again and again so sluggish the response.

As Theme Change operation is in User's hand so Swastika can’t say users to “don’t change Theme frequently”. It will hurt her blog reputation.

So what she do now?

Swastika goes to her OOP Teacher for a Solution.

Sir Tell her to Reuse Widget but she believes her widget is stateful, so she explain the problem she has having now,

Swastika : Sir, I can use cache and put the Widget against a key in the cache and reuse it, but say my default theme is Classic Blue so every widget has color blue and say in classic Blue theme my Follower widget is in Left of the Screen.  Now if a user changes it to Slick green, then every widget must have to change their color to Green and say in Slick green theme, Follower widget will be on the Right side of the screen.

Now If I want to reuse my widget from cache it has Blue color and Follower widget position is in left so How I can reuse them without populating a new widget?


Sir: Wow, what a thought Swastika, very good but think about the scenario here your Widget populate data from backend and loaded once, But if you want to load it again for just to assign a color and position then you welcoming a potential danger to your blog.



So your new feature is not an addition it is a technical debt. Then it is better not to have it.

Think in an OOPs perspective when you change the Theme what happens, it just reorders your widget position and changes the color but widgets content are remain same. So if you load the Widget once and make your widget to capable of taking color and position value from outside then can you reuse your widget?

The answer is Yes as because apart from color and position your widget is state-independent in this context as it’s content does not change.

By Oops you can easily pass any attribute from outside and based on the theme your widget layout manager can decide what would be the position and color of your widget.



Flyweight pattern does the same.

What is a Flyweight pattern?

According to Wiki:
A flyweight is an object that minimizes memory usage by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.


So According to the definition widgets are Flyweight objects and reloading them unnecessary increase response time, So instead of that if we share color and position data to all Flyweight objects/Widgets then we can reuse the Widgets. And layoutManager computes the value of color and position by using Theme, An external data structure.

So every Flyweight object has two kinds of data

  1. Intrinsic data:  Which is State independent data, that is which does not change with the context like Swastika’s Widgets content does not change with the theme.
  2. Extrinsic Data:  Which is context-dependent data and changed with the context like Swastika’s Widgets color and position change with Theme.
To make our Flyweight object reusable we need to pass extrinsic data from outside to       Flyweight Object.

Coding Time:

Sir start the coding to show Swastika How he can make her widget reusable without loading it --help of Flyweight pattern.


IWidget.java

/**
*
*/
package com.example.flyweight;

/**
* @author Shamik Mitra
*
*/
public interface IWidget {
   
    public void setWidgetName(String name);
    public String getWidgetName();
    public void setWidgetContent(String content);   
    public void display();
    public void applyTheme(String color,String postion,Layoutmanager manager);

}



Now Sir create a layout manager and use Flyweight pattern there.

/**
*
*/
package com.example.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
* @author Shamik Mitra
*
*/
public class Layoutmanager {
   
    private static Layoutmanager mgr = new Layoutmanager();
   
    Map<String,IWidget> map = new HashMap<String,IWidget>();
   
    public static Layoutmanager get(){
        return mgr;
    }
   
    private Layoutmanager(){
        init();
    }
   
       
    public void addWidget(IWidget widget,String position){
        System.out.println("Adding Widget " + widget.getWidgetName()+  " in to position " + position);
       
    }
   
    private void init(){
       
        IWidget followerWidget = new IWidget(){
           
            private String name;
            private String content;
            private String color;
            private String position;

            @Override
            public void setWidgetName(String name) {
            this.name=name;
            }
           
            @Override
            public String getWidgetName() {
            return name;
            }

            @Override
            public void setWidgetContent(String content) {
            System.out.println("setting content first-time....loading from back end costly operation");
            this.content=content;
               
            }

            @Override
            public void display() {
                System.out.println(" Widget name : " + name);
                System.out.println(" Widget color : " + color);
                System.out.println(" Widget color : " + position);
                System.out.println(" Widget content : " + content);
            }

            @Override
            public void applyTheme(String color, String postion, Layoutmanager manager) {
                this.color=color;
                this.position=postion;
                manager.addWidget(this,postion);
               
            }
           
        };
       
        followerWidget.setWidgetName("Follower Widget");
        followerWidget.setWidgetContent("Showing blog Followers.");
        followerWidget.applyTheme("Blue", "LEFT", this);
        followerWidget.display();
        map.put(followerWidget.getWidgetName(), followerWidget);
       
       
       
    }
   
   
    public void ChangeTheme(){
        System.out.println("After Change Theme");
        for(String name : map.keySet()){
            if("Follower Widget".equalsIgnoreCase(name)){
                IWidget widget = map.get(name);
                widget.applyTheme("Green", "RIGHT", this);
                widget.display();
            }
        }
    }
   
    public static void main(String[] args) {
        Layoutmanager mgr = Layoutmanager.get();
        mgr.ChangeTheme();
    }
   
   

}







Explanation:
In Init() method sir creates Follower Widget for the first time and put it on a map so later on when the user does change the theme Sir can reuse the Widget.
Then apply the Classic Blue theme as the default theme.

When user call ChangeTheme() method, the application calls every Widget’s applyTheme() method and pass color and position from Layout manager so Widget/flyweights Object can change the color and set itself in the correct position.

Here Color and Position: the Extrinsic property of Flyweight Object.
Other properties of Widget is Intrinsic in nature.


Improvements:

Please note that this is a very basic example. To make it concrete more improvement needed like.

  1. The theme has to be a context Object implements an ITheme interface which dictates what will be color and other properties.
  2. LayOutManager should be the implementation of ILayoutManager interface as there can be various Layouts.
  3. The widget can be decorated by decorator pattern.
  4. We can segregate the logic of Widget creation and load it into the cache in a separate Class called WidgetFlyWeightFactory.