Search code examples
javaclassoopobjectstateless

Stateless Objects good practice or not


This is my understanding about stateless objects:Any object created from class that doesn't have class variables is a stateless object. My question is when should we write stateless classes. Is it a good habit to have stateless objects.


Solution

  • Stateless objects are useful if you need to "pass functionality as a parameter". Since functions are no Objects in java, it's a practical way to pass the an object with the function as parameter.

    For example Comparators can be used to sort, if a class does not implement Comparable or if you need to support sorting with different definitions of the "<"-relation. (e.g. accending / descending order; sorting by different properties ...)

    A factory (see http://www.oodesign.com/factory-pattern.html) may be a stateless object. All functions of the factory may create objects and all parameters necessary to create them can be given as parameters of the functions of the factory.