In Java it seems Public constructors are always a bad coding practice
Posted
by
Adam Gent
on Stack Overflow
See other posts from Stack Overflow
or by Adam Gent
Published on 2012-10-24T16:47:29Z
Indexed on
2012/10/24
17:00 UTC
Read the original article
Hit count: 293
java
|coding-style
This maybe a controversial question and may not be suited for this forum (so I will not be insulted if you choose to close this question).
It seems given the current capabilities of Java there is no reason to make constructors public
... ever. Friendly, private
, protected
are OK but public
no.
It seems that its almost always a better idea to provide a public static
method for creating objects. Every Java Bean serialization technology (JAXB, Jackson, Spring etc...) can call a protected or private no-arg constructor.
My questions are:
- I have never seen this practice decreed or written down anywhere? Maybe Bloch mentions it but I don't own is book.
- Is there a use case other than perhaps not being super DRY that I missed?
EDIT: I explain why static methods are better.
.1. For one you get better type inference. For example See Guava's http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained
.2. As a designer of the class you can later change what is returned with a static method.
.3. Dealing with constructor inheritance is painful especially if you have to pre-calculate something.
© Stack Overflow or respective owner