Named constructors, or "factory methods," are small static functions that serve as generators for instances of a specific class. Ultimately, they allow our constructors to be more semantic and robust. This provides us with greater robustness and meaning in the contracts of the instance-creating methods. In today's video, we will see two practical examples where they could be applied: a domain model User, and a domain exception.
" />Here is the link to the video about the Single Responsibility Principle referenced at the beginning of this week's chapter :) I would also like to add a little nuance that I realized after recording the video: we could also reconstruct the state of an instance through reflection. Languages like PHP and Java allow modifying the visibility of attributes to enable such changes. As Sergi mentioned to me, some ORMs use this technique to map database records to entities in our system without needing to keep the constructor public as we proposed in the video. Fine magic. For more information, here is a detailed refactoring guide on "Replace Constructor with Factory Method," examples of the pattern in Java, and a post with Mathias Verraes' explanation. Remaining questions:
- When is it bad to use a static function?
- How could we respect ISP and SRP in this class design?
You can respond in the comments of the videos :)