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
PopularLaunch Week

standard

20,75 €
Save 171
Annual payment of 249
per month
  • Full course catalog
  • Receive job offers verified by Codely
  • Company invoice
Launch Week

premium

37,42 €
Save 139
Annual payment of 449
per month
  • All previous benefits
  • Early access to new courses
  • Discount on workshops

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