Making constructors pre-process the arguments before encapsulating them seems to be bad practice. However, very often it’s necessary to do exactly that: perform some manipulations with the objects provided as arguments and only then assign them to the attributes of the constructed object. For this purpose I suggest using prestructors, which could be methods or stand-alone objects.
Say, this is your code:
The only constructor expects a list of titles, which is being
this.titles for some future use. It’s also protected against
any accidental modifications, through the JDK decorator at
So far, so good. Now, we want to make our class a bit smarter
and let it accept not only the
List but an array of strings:
What’s wrong with this code? Those of you who have read my earlier blog posts about OOP most definitely know the answer. First, there are two primary constructors, which is another bad practice. Second, there is code in the second constructor, which is also a bad idea.
Here is how I usually refactor this code, to solve both mentioned problems:
I call this new static method
toList() a prestructor: it is used
only at the moment of object construction and only from the
An even better way to design it would be to make a new class
which would do exactly the same, but in a more declarative and lazy way: