5 ms·
I have two issues with constructors. 1. They don't have a name. That's bad because names are important. It's OK if constructor is primitive and does not do any
by vbezhenar 4y ago
I have two issues with constructors.
1. They don't have a name. That's bad because names are important. It's OK if constructor is primitive and does not do anything but field assignment. But often constructors do something and naming might help.
2. There can't be two constructors with identical types (as a consequence that constructors don't have a name). This might be restricting in some cases.
Factory methods solve both issues.
If anything, I'd prefer to remove constructors completely and use factory methods for anything. Not realistic with Java, of course. But in my code I'm trying to follow this pattern. Constructors are absolutely minimal (usually just initializers for final fields) and any non-trivial code goes into factory method. Of course it causes issues with subclassing, so it's not a silver bullet.
- vips7L 4y agoIn practice the names are just not descriptive (of, from, newInstance, get) and I suspect this is because they're typically used to dynamically return implementations at runtime so you don't know the name of thing you want. If you know the name of the thing you want ahead of time, isn't the constructor of the named type good enough?
- _benedict 4y agoA good example might be static constructors that indicate the semantics of the parameters, such as of(array), copyOf(array), ofSorted(array) Where perhaps the first wraps, the second copies and the third may wrap and avoid sorting the input. This would all of course depend on some conventions on meaning within the codebase.