Tuesday, August 7, 2018

Arguments for Encapsulating Constructors

I always encapsulate my constructors. That is, given the following two designs (C#), I choose the latter whenever I can:

// this...
class A { }

// ...or this
class A {
  A() { }

  public static A GetInstance() => new A();
}

"Why?" you may ask.

There are several reasons to do this, the most obvious being this rule of thumb:
Encapsulate everything you can and only expose only that which you must.
In most languages, exposing a constructor gives clients an opportunity to create a special kind of coupling.

new A() couples code not only to the fact that there is a type A but that this class is concrete and all functionality accessible through A is accessible through instances of class A. No suitable substitutes will be accepted.

The real answer, though, is just another question: You can always make a constructor public if you really need to do that so what do you have to lose by making it private, now?