I am reading Effective Java and came across following paragraph.
A class can have only a single constructor with a given signature. Programmers have been known to get around this restriction by providing two constructors whose parameter lists differ only in the order of their parameter types. This is a bad idea. The user of such an API will never be able to remember which constructor is which and will end up calling the wrong one by mistake. People reading code that uses these constructors will not know what the code does without referring to the class documentation.
Because static factory methods have names, they do not share with constructors the restriction that a class can have only one with a given signature. In cases where a class seems to require multiple constructors with the same signature, you should consider replacing one or more constructors with static factory methods whose carefully chosen names highlight their differences.
My questions are…
Do we really need multiple constructers with the same signature?
Have anybody had this requirement ever during the development?
My blood is tested +ve for Java.
Scheepers de Bruin
Ranch Hand
Joined: Jul 19, 2005
Posts: 99
posted
0
Sometimes you'll bet dearly tempted to.
I wrote a data mapping component, that maps properties to tables and rows.
Now there are two ways to construct a DAO object that uses this component - you could specify the data mapping key (where the datasource is derived from the mapping configuration) OR a datasource key (where the mapping is not used, but the dao is).
The problem is that both of these keys are strings, and there was no way to differentiate between the two types of keys. I started by typing:
Eventually gave up and just decided that mappings take preference, so if there was a mapping and a source with the same key, the mapping would always be used.
We're doomed!!<br />Yay!!!<br />No that's bad Girr!!<br />Yay!!!
Chetan Parekh
Ranch Hand
Joined: Sep 16, 2004
Posts: 3636
posted
0
Thx Scheepers de Bruin
Your cleared all my darkness.
Tony Morris
Ranch Hand
Joined: Sep 24, 2003
Posts: 1608
posted
0
Do we really need multiple constructers with the same signature?
No. I develop all my Java applications with all constructors declared private, with no arguments (mandated by the language spec.) and declaring and explicitly throwing UnsupportedOperationException. This is because the semantics of Java constructors violate encapsulation, and I ignore verbosity as a side-effect of the flaw. Therefore, we never *need* such a thing.