Encapsulate Constructors

Competency Type: Practice

The principle that states Separate Use from Construction is generally interpreted as implying the use of object factories to instantiate service objects for clients to use. While we appreciate the value of object factories, it is not a practice that can be promoted as universal.

That said, failing to use an object factory up-front can create significant maintenance problem in the future. A middle ground is needed between:

  1. Failing to separate use from construction (usually resulting in “new” being coded into the client, or using object), and
  2. Creating a separate factory object to create all instances, even when they are simple, non-varying services.

This simple practice involves protecting the constructor of the service object by providing a static method that creates it. Often we will also make the actual constructor private or protected, preventing clients from accessing it via "new".

Resources
Encapsulating Construction (Webinar)
Principles And Practices (Webinar)
Perspectives of Use vs. Creation in Object-Oriented Design (Article)