Semantic Constructors - Named Constructors #CleanCode

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:

You can respond in the comments of the videos :)

Pay according to your needs

lite (only monthly)

19 €
per month
  • Access to a subset of courses to lay the foundation for maintainable, scalable, and testable code
  • Company invoice
Popular

standard

24,92 €
Save 121
Annual payment of 299
per month
  • Full course catalog
  • Design and architecture challenges
  • Highlighted solutions videos for challenges
  • Receive job offers verified by Codely
  • Company invoice

premium

41,58 €
Save 89
Annual payment of 499
per month
  • Everything above
  • More benefits coming soon

We won’t increase the price while your subscription is active