Practice: Encapsulating Constructors in Simple Classes

Listen to this post
Subscribe

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

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 or over-design. Does that mean it should never be done? That seems wrong too.

Is there something that can be done to resolve this conundrum?

Diagram

Consider this diagram.

Encapsulate Constructors

Approach

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
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.