Sunday, February 17, 2019

Testing private method in Java

Private method in java is not accessible outside the Class which defines it.
Since they cannot be accessed we cannot call them from any Test Class directly to test them.

Following are some of the options to test the private method

1) Change the visibility of the private method to package or protected.
2) Create a public method in the Class and call the private method from the public method

Above two solutions requires us to change the original Class. Some times we cannot change the original Class but still would like to have a Test Class for the same method.

The other option is to use Reflection api to invoke the private method.

For example lets try to test a private method multiple on Class CreditcardMask.java

Class targetClass =
(Class) Class.forName(CreditcardMask.class.getName());

// get the method multiply
Method testMethod = targetClass.getDeclaredMethod("multiply", Integer.class, Integer.class);

Assert.assertNotNull("testMethod is Null", testMethod);

// set visibility to true for the private method
testMethod.setAccessible(true);

// get the constructor
Constructor constructor = targetClass.getDeclaredConstructor();
Object instance = constructor.newInstance(); // create a new instance

Integer param1 = 10;
Integer param2 = 10;

// invoke the method
Object testMethodResult = testMethod.invoke(instance, param1, param2);

Assert.assertEquals(100, testMethodResult);


Full source code can be found on
Github https://github.com/siddharthagit/javaexpcodes/blob/master/core-java/test/TestPrivateMethod.java

Friday, February 1, 2019

Proxy Design Pattern In java

Type : Structural Design Pattern

Summary


Proxy Design pattern lets a Proxy Object rather then the real object to interact with Client. By doing so the proxy can control access to the real object or delay the creation of real object unless it is is really needed.

Description


In Proxy Design pattern the Client is served with a Proxy Object rather than the real object. Benefit of doing so is that, we have greater control in when to create the real object. It would help us in providing in lazy loading the real object, providing extra security checking etc. 

Example


For example lets consider a service called UserDetails Service which the Client calls to get UserDetails Object. Now say UserDetails is a complex object, and we need to real the database to populate it. Also we would like to have a security authorization check by which we will not show the details at all or show only few attributes from UserDetails Object.

Returning a Proxy rather than original object help us in achieving our goals. In our example UserDetailsProxy either returns a proxy object or real object based on the parameter(caller id). Say if "admin" user is calling than it returns the actual object otherwise it returns the proxy object.

Class Diagram




Sample Code


public interface UserDetails {

  public UserDetails getUserDetails(String callerId, String uid);

  public Double getTotalBalance(String uid);
}

// actual Object which contains UserDetails
public class UserDetailsImpl implements UserDetails {

  private String userId;
  private String bankAccountNo;
  private String socialSecurityNo;
  private String zipCode;
  private Double totalBalance;

  @Override
  public UserDetails getUserDetails(String callerId, String uid) {
    return UserDetailsService.retrieveUserById(uid);
  }

  public UserDetailsImpl() {

  }

  @Override
  public String toString() {
    return "userId=" + this.userId + " bankAccountNo=" + this.bankAccountNo + " socialsecurity="
        + socialSecurityNo;
  }

  @Override
  public Double getTotalBalance(String uid) {
    return totalBalance;
  }

}


// proxy Object for UserDetails
public class UserDetailsProxy implements UserDetails {

  UserDetailsImpl realUserDetails = null;

  @Override
  public UserDetails getUserDetails(String callerId, String uId) {
    if (callerId.equalsIgnoreCase("admin")) {
      return UserDetailsService.retrieveUserById(uId);
    } else {
      return new UserDetailsProxy();
    }
  }


  @Override
  public String toString() {
    return "userId=NA bankAccountNo=NA socialsecurity=NA";
  }


  @Override
  public Double getTotalBalance(String uid) {
    if (realUserDetails == null) {
      realUserDetails = UserDetailsService.retrieveUserById(uid);
    }

    return realUserDetails.getTotalBalance();
  }

}


//UserDetails Service which returns the Object
public class UserDetailsService {

  public static UserDetailsImpl retrieveUserById(String uId) {
    UserDetailsImpl userDetail = new UserDetailsImpl();
    userDetail.setUserId(uId);
    userDetail.setBankAccountNo("swissbank_11228899");
    userDetail.setSocialSecurityNo("888 11 777");
    userDetail.setZipCode("95011");
    userDetail.setTotalBalance(99.9);
    return userDetail;
  }
}

Github Code

Advantages


Proxies can help increase performance by delaying creation of the real object.
It can improve security by wrapping the real object by proxy object and returning real object when allowed.

Disadvantages

Proxy pattern introduces new Proxy objects.
Proxy objects might need to refactored if the Original object also changes.

References

https://en.wikipedia.org/wiki/Proxy_pattern

Flyweight Pattern in Java

Type : Structural Design Pattern

Summary


Flyweight design pattern deals with sharing some of the internal details between different object instances, so that we can save memory by basically using less duplication of the attributes across its instances.

Details


In Flyweight design pattern the Object attributes are categorized into its extrinsic and intrinsic attributes. Extrinsic attributes are the attributes that can be considered as sharable across other instances. Intrinsic attributes are the attributes that are unique for each object, like the primary key, unique fields etc.
In Flyweight design we can improve the memory footprint by reusing the extrinsic properties in multiple instances of the object.

Flyweight can use Cache to store the different Extrinsic states. Factory method can be used to create the instances of the Extrinsic object and stored in cache.

Example


For instance say we are designing a Vehicle in OOP. Now each instance of the Vehicle will have some unique characteristics like its serial number, registration number.
Also we can notice that each vehicle instances will share something very similar like the Body Type, Engine etc. across multiple instances. 
We will consider the Engine to be extrinsic property which can be shared across different instances of Vehicle
We will consider the serial number as intrinsic property.

Vehicle is the interface representing vehicle
Vehicle contains an instance fo Engine
Engine is an interface
We have two type of Engine implemented by ElectricEngine and GasolineEngine
EngineFactory is a cache holding different types of Engine.
CarImpl implements Vehicle. It has a reference to Engine object.

Class Diagram



Sample Code


public interface Engine {
  
  public String getEngineName();

  public String getType();

  public int getHorsePower();

  public String getMaxSpeed();
}



public interface Vehicle {

  public String getModelName();

  public String getYear();

  Engine getEngine();

}

public class ElectricEngine implements Engine {

  private String engineName;
  private String engineType;

  public ElectricEngine(String name) {
    this.engineName = name;
    this.engineType = "Electric";
  }

  @Override
  public String getEngineName() {
    return engineName;
  }

  @Override
  public int getHorsePower() {
    return 200;
  }

  @Override
  public String getMaxSpeed() {
    return "110 MPH";
  }
  
  public String getEngineType() {
    return engineType;
  }

  @Override
  public String getType() {
    return this.engineType;
  }

}

public class GasolineEngine implements Engine {

  private String engineName;
  private String engineType;

  public GasolineEngine(String name) {
    this.engineName = name;
    this.engineType = "Gasoline";
  }

  @Override
  public String getEngineName() {
    return this.engineName;
  }

  @Override
  public int getHorsePower() {
    return 200;
  }

  @Override
  public String getMaxSpeed() {
    return "170 MPH";
  }

  public String getEngineType() {
    return engineType;
  }
  
  @Override
  public String getType() {
    return this.engineType;
  }

}



public class EngineFactory {
  private static Map engineCache = new HashMap();

  public static Engine getEngine(String engineName) {
    if (engineCache.containsKey(engineName)) {
      return engineCache.get(engineName);
    } else {
      if (engineName.startsWith("Electric"))
        return getElectricEngine(engineName);
      else
        return getGasEngine(engineName);
    }
  }

  public static Engine getGasEngine(String engineName) {
    GasolineEngine gasEngine = new GasolineEngine(engineName);
    engineCache.put(engineName, gasEngine);
    return gasEngine;
  }

  public static Engine getElectricEngine(String engineName) {
    ElectricEngine gasEngine = new ElectricEngine(engineName);
    engineCache.put(engineName, gasEngine);
    return gasEngine;
  }

  public static int getTotalEnginesMade() {
    return engineCache.size();
  }

}

public class CarImpl implements Vehicle {

  private String model;
  private String year;
  private String serialNumber;
  private Engine engine;

  public CarImpl(String model, String year, String slNumber, String type) {
    this.model = model;
    this.year = year;
    this.serialNumber = slNumber;
    this.engine = EngineFactory.getEngine(type);
  }

  @Override
  public String getModelName() {
    return this.model;
  }

  @Override
  public String getYear() {
    return this.year;
  }

  @Override
  public Engine getEngine() {
    return this.engine;
  }

  public String getSerialNumber() {
    return this.serialNumber;
  }

  @Override
  public String toString() {
    return "model= " + this.model + " year=" + this.year + " slNo=" + this.serialNumber
        + " engineType=" + this.engine.getType();
  }
}

Advantages


Memory consumption can be reduced by sharing Extrinsic states across objects.

Disadvantages

Flyweight weight increases the complexity of Object structure.

Adapter Design Pattern in Java

Type : Structural Design Pattern

Summary


Adapter design pattern is a Structural design pattern. It is used to provides compatible interface for and Class so that can be used by Client. Adapter pattern is used to provide compatibility for Classes which already exists and cannot be modified.

Details


Need for adapter design pattern is very obvious. It is also very common in real world as well as in Software Engineering. For instance if we have any electrical appliances which runs on 110 Volt and then we travel to a country where the electricity supply is 220 V. We cannot change or modify the electric connection to provide us 110 V. Rather we can use a adapter to convert the 220 V from outlet to 110V.

Adapter pattern is similar to Bridge pattern because both provide mechanism to connect incompatible Classes.

Advantages

Incompatible Object or Class can be used using an Adapter for it.

Disadvantages

Increases number of Classes
Adapter Class needs to be modified if the Target Classes changes.

Example


For instance if we consider a TV set which has input connector as USB. We can connect any device which has USB port.

Now say a new device launched "Blue Ray DVD" which has HDMI as output. We cannot connect this two devices as they are not compatible . 

We make them work together by providing an adapter HDMIToUSBAdapter which converts HDMI to USB and vice versa

Class Diagram



Sample Code



// TV which connects though USB port
public class TV {

  private USBConnectorPlayer connect;

  public void connectTVAndPlay(USBConnectorPlayer conn) {
    this.connect(conn);
    this.connect.renderContent();
  }

  public void connect(USBConnectorPlayer connect) {
    this.connect = connect;
  }
}


// USB connector player
public class USBConnectorPlayer {
   private String content;
   public USBConnectorPlayer(String content) {
     this.content = content;
  }
   public void renderContent() {
       System.out.println(this.content);
   }
}

// a player that supports HDMI connection
public class HDMIConnectorPlayer {

  private StringBuffer content;

  public HDMIConnectorPlayer(StringBuffer content) {
    this.content = content;
  }

  public void renderContent() {
    System.out.println(this.content);
  }

  public StringBuffer getContent() {
    return content;
  }
}

package blog.javaexp.structural.adapter;

// Adapter Class to convert HDMI to USB
public class HDMIToUSBAdapter {

  public USBConnectorPlayer convertToUSB(HDMIConnectorPlayer hdmi) {
    String str = hdmi.getContent().toString();
    USBConnectorPlayer ret = new USBConnectorPlayer(str);
    return ret;
  }

}


Github Code


References


Abstract Factory Design Pattern in Java

Type:  Creational Design Pattern


Summary

Provide an indirect way to create object that abstracts the creation of families of related objects without directly specifying their concrete Classes. The Factory owns the responsibility create objects. Client is not aware of how to create the object.

Details

It is similar to Factory method design pattern. Only difference is that rather than returning instance of Subclasses, Abstract factory method can create object of Subclasses having different inheritance hierarchy. Generally Abstract Factory will return different Factories, which in turn can be used to Objects

Abstract Factory is used when we want to create objects by Clients and control which instance should be returned. It is used in DAO (Data Access Object).


It can be used to design Platform dependent software solution, by providing platform specific implementations.  

Example

We will extend the example of Sales Man and Different types of Car (SUV, Sedan) to have different type of Car's in terms of its engine (Electric, Gasoline). Now rather than giving an option to create instance of concrete Class like SUV and Sedan, we have an Abstract Factory Class which can return Factory for either ElectricCar or GasolineCar.

Class Diagram


Sample Code



// interface for Engine Factory
public interface EngineProvider {

  public Car getSedan();

  public Car getSuv();
}

// electric Car Factory
public class ElectricCarFactory implements EngineProvider {

  @Override
  public Car getSedan() {
    return new ElectricSedan();
  }

  @Override
  public Car getSuv() {
    return new ElectricSUV();
  }
}


//gasoline Car Factory
public class GasolineCarFactory implements EngineProvider{
 
  @Override
  public Car getSedan() {
    return new GasolineSedan();
  }

  @Override
  public Car getSuv() {
    return new GasolineSUV();
  }

}


// Car Factory Class which interacts with Clients
public class CarFactory {

  private static EngineProvider factory;

  public static EngineProvider getProvider(String providerName) {
    switch (providerName) {
      case "ELECTRIC":
        factory = new ElectricCarFactory();
        break;
      case "GASOLINE":
        factory = new GasolineCarFactory();
        break;

    }
    return factory;
  }
}

Github Code 


Advantages

Provide a standard interface by which family of objects can be created
Internally in the Abstract factory we can use other design patterns like Flyweight or Proxy or Prototype pattern as per the need.

Disadvantages

Sometime supporting for new Object type might lead to changing the interface and refactoring the existing implementation.

References

Factory Design Pattern in Java

Type:  Creational Design Pattern

Summary


Factory or Factory method Design pattern is a creational design pattern. It helps in loose coupling between client and the actual object that the Client needs. Rather than Client calling the constructor using new operator it calls the Factory and the factory returns the respective object.

Details


Factory method design pattern encapsulate the complexities around creating an object and also uses Inheritance by letting factory method to decide which Subclass instance is needed to be returned.

Factory method pattern solves the issue of creating object without exposing internal details by
Provide an interface (Could be an Interface or Abstract Class) and a factory method
let the Client create the appropriate object by calling the factory method.

Example


Let's say we have a company ABC Cars Corp, which manufactures different type's of Cars (Sedan, SUV etc).  Now we want to provide a way to the Sales man to be able to get a Car (object instance) based on Customer preference, and can demo those cars to Customers.
One option is to provide constructor for those Cars. So that Client can call the constructors and create cars.

That exposes a lot of technical details to the Sales Man. Better would be have a factory/or room which has all available cars. Then the Sales Man can could quickly turn around with available Car to the Customer. That way the learning curve for the Sales Man is very minimum.

Now say down the lane, ABC Cars Corp also starting manufacturing Sports Car. Now the problem is, all the Sales Team needs to know what parameters needed to be sent to create a sample Sports cars. 

Factory method does that by utilizing inheritance and based on the requirement it creates a specific instance of one of the SubClass.

GasolineCarFactory is the Factory that implements a factory method.
Car is extended by two Subclasses SUVCar and CompactSedan Car

Class Diagram



Sample Code 



// subclass of Car
public class CompactSedanCar extends Car {

  @Override
  public String getModel() {
    return "Compact4person";
  }

  @Override
  public String getPrice() {
    return "20k";
  }

  @Override
  public String getType() {
    return "COMPACT";
  }
}

// subclass of Car
public class SUVCar extends Car {

  @Override
  public String getModel() {
    return "SUV2019";
  }

  @Override
  public String getPrice() {
    return "40k";
  }

  @Override
  public String getType() {
    return "SUV";
  }
}

// factory method Class which the Client interact with
public class GasolineCarFactory {

  public Car getCarType(int i) {
    switch (i) {
      case 1:
        return new CompactSedanCar();
      case 2:
        return new SUVCar();
      default:
        return new CompactSedanCar();
    }

  }

}

Github Code 

Advantages


Centralized interface to create object.
Easy of refactoring and code reuse.
Easy discovery for developers.
Better testable codes.
Internally the factory method can utilize Prototype design pattern or Flyweight design pattern as per the situation.

Disadvantages


Factory method design pattern adds a layer of attraction between Client and real Object.
when a new SubClass is introduced the factory method needs to update to take that into consideration.

When to Use


When we want to provide a centralized or common interface to create multiple objects (subclasses)
When we want to hide the complexities of creating instances of those object.
When we want to control how an object instance should be created.
If we have complex business logic while creating objects, this design pattern is very useful

Singleton Design Pattern

Type: Creational Design Pattern

Summary


Singleton Design pattern is used to provide a mechanism so that a Class can have only one instance. So when Client try's to use an instance of Singleton Class it gets the same instance. 
Singleton.

Details


Singleton Design pattern make sure that Class which implement this pattern can have only one instance. In case of Java, only one instance in a single JVM.
For instance if we want only one instance of Cache Class which would store temporary values in memory.

Singleton pattern is also used in Logger Classes. Logger provide single instance for logging which is used by application code.

Singleton design pattern is implemented by following mechanism
1) Making the constructor private. So that Client cannot create different instances
2) Provide a static method, which the client will interact to get the instance of the class
3) Do not offer any setter method for the object
4) If any getter for individual property returns any object reference, it should return a copy of it
5) Taking care of reflection api, to do this we can throw exception in the constructor if it the instance is not initialized.

Advantages


Provide an option to make sure the instance is single, and if we want to create multiple copies of the object still they will be same.

Useful when we want only one instance of a Class like Service, shared resource etc.

Disadvantages


Depending on the need, DI/IOC can be better suitable.

Possible ways to break

Following points need to be thought about possible ways to break the Singleton Class to get more than one instance.

In java one can use the Reflection API to alter the constructor (private) of the Singleton Class to create different instances. This can be taken care by throwing exception from the private constructor.

In Java one can use the clone. It can be achieved by overriding clone() method and throwing Exception.

Multiple thread can break the Singleton Class. It needs to be taken care as well.

In Java Serialization can cause breaking this contract. It can be handled by returning the instance from readResolve() method.

Example


Let's take example of a House Key. We want only one key for the whole house. We do not want any way to temper the key. We want only one identical key to be available. If any one needs a key, essentially they will get the same single key instance. We can utilize the Singleton pattern to make sure that the key once generated is not modifiable.

Here the Class HouseKey implements Singleton pattern, and that Class make sure only one instance of the key exists.

Class Diagram


Sample Code



public class HouseKey implements Serializable {
  private static final long serialVersionUID = 1L;
  private String keyPattern;
  private Long keyDate;

  private static HouseKey instance;

  // private constructor
  private HouseKey() {

  }

  // public get instance method
  public static HouseKey getInstance() {
    if (instance == null) {
      synchronized (HouseKey.class) {
        instance = new HouseKey();
        instance.keyPattern = "key 12345";
        instance.keyDate = new Date().getTime();
      }
    }
    return instance;
  }


  // safeguard against Clone
  protected Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
  }


  // safeguard against Serialization
  public Object readResolve() {
    return HouseKey.getInstance();
  }

  @Override
  public String toString() {
    return "HouseKey " + this.keyPattern + "  " + this.keyDate;
  }
}

Github Code 

References