Tuesday, April 22, 2014

Design Implication: Class with static methods VS Singleton

Question: Functionality of a singleton can also by having a class in which all methods are static, then why should one choose singleton?

Answer:  When choosing any approach one should see the impact this design has in terms on maintainability.

Following are the reasons for which one should not choose a class with static methods:

1. Encapsulation: When one uses a class with static methods then encapsulation is broken.
2. Inheritance: A class with static method though can be inherited but parent class reference cannot be used to invoke child class methods
3. Extensibility: If one wants to change the behavior and move away from the singleton behavior, it is a problem if one has the class with static methods

When use class with static methods:
1. Utility class: When a class is a utility class and doesn't need any instance variables
2. Design evolution: If the design is fixed and there is no room for improvement by inheritance

Some of the common classes with static methods in java are:
1. Math