Practice: Encapsulate Constructors in Simple Classes

A recurring question in object-oriented software (OO) is this: When it is determined that an algorithm should be established in its own separate class (to make it testable, reusable, or simply as an issue of cohesion), should it also be given a separate abstract type that it implements?

images

The advantage, of course, is that the client (or clients, as more arise) will not couple to the specific service class, but rather to the abstract type. If more versions of the service are added, then clients will be largely unaffected. It's a form of “future proofing.” But can you do this all the time? Should every class, when deemed necessary, also have a second class that hides its real type? Often this would seem like overkill/overdesign. Does that mean it should never be done? That seems wrong too. So, is there something that can be done to resolve this conundrum?

The Encapsulating Constructors Practice

One very simple solution to this is to encapsulate the constructor of simple classes:

class Service {

 private Service() {}

 public static Service getInstance() {

  return new Service();

 }

 // rest of implementation follows

}

class Client {

 private Service myService;

 public Client() {

  // instead of “myService = new

  // Service();”

  myService = Service.getInstance();

 }

}

At first glance, this does not seem like much. Calling the static method getInstance() couples the client to the service type as much as using new does. The difference is that the latter couples the client to the fact that service is concrete, and the former does not. An abstract class can sport a static method just as well as a concrete class can. But new cannot be used on an abstract class.

This means that later, if needed, the service can be changed to this, with limited or no effect on any clients.

abstract class Service {

 public static Service getInstance() {

  // return any one of many implementations

  // based on appropriate decision logic

 }

}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset