Quick Index
Standard Constructors Are Effectively Unnamed


In coding, naming variables, methods, classes, interfaces, etc is very important. In fact, the web is loaded with folks arguing passionately about naming conventions.

The problem with standard constructors is they are unnamed.

To make matters worse, many times constructors are overloaded so you have multiple unnamed constructors.

Let's look at a couple examples.

Example: Rectangle
The constructors just use the object type name (e.g., Rectangle).

It's certainly not clear what the passed parameters are. 😕
let rec1 = new Rectangle(500, 250);
let rec2 = new Rectangle(300);
Example: Circle
This won't work 😢

We would have to add unnecessary complexity and add more parameters to the constructors to allow this to work.
//constructing using radius
let circ1 = new Circle(10);
//constructing using diameter
let circ2 = new Circle(20);


Static Factory Methods


Now let's see how static factory methods work so we can compare.

Example: Rectangle
Now it is clear that we are passing width and height in the first case, and a square side in the second case. 😊
let rec = Rectangle.fromWidthHeight(500, 2500);
let square = Rectangle.fromSide(700);
Example: Circle
Circle will be left as a fun drill problem in this chapter.
Example: Date
Objects often provide multiple alternatives for construction.

Static factory methods (shown) provide clear protocol.

Standard constructors would not support these alternatives (same method signature). They would need to use a clumsy workaround such as a date-type parameter.
let date1 = Date.fromMMDDYY('6/1/99');
let date2 = Date.fromMMDDYY('6/1/1999');
let date3 = Date.fromYYYYMMDD('1999-6-1');
Example: FullName
Another example of an object providing multiple alternatives for construction.

With standard constructors, e.g., "new FullName('Asha', 'Gupta')" there is no indication of what the parameters are.
let name1 = FullName.fromFirstLast('Asha', 'Gupta')
let name2 = FullName.fromFirstMiddleLast('Asha', 'Kanvar', 'Gupta')


Conclusions


Also see the references in the introduction of this chapter.

Code clarity and simplicity is terrifically important and we can see that using static factory methods for construction often will provide more clarity.

So in general it is suggested to use static factory methods. However, nothing is 100%, and there will be cases, possibly very simple object types, where standard constructors may suffice.