As you summarize, constructors are the easiest way to ensure that only valid objects are created.
However, using the constructor, I am curious how to maintain the code, since it is modified to support this requirement without breaking existing code in the code base.
I'm not quite sure what you are talking about: the risk that you will later realize that you need additional (or less) parameters to create valid objects? IMHO , which should be mitigated by carefully developing, prototyping, and testing before publishing your library . Public APIs are very difficult to change. In the case of widely used, even broken and obsolete functions should be supported unlimitedly (witness Object.clone() in Java). Regardless of what you (or clients) do to build the object, if the required parameter is missing, this is an error. IMO is better off defining such compilation cases than runtime, and constructors provide the easiest and easiest way to achieve this.
Other options you may consider:
- using the Factory Method (you still need to have all the necessary parameters inside the create method, but you may be able to use some default values for missing parameters, so as not to violate the client code),
- using Builder (similar to the above, but it gives you more flexibility when setting up design parameters or providing default values).
source share