Take this skeleton class that someone wants to fill in to fetch RSS streams on a series of web sites:
public class RSSStream extends Thread {
public RSSStream(String rssStreamName,String rssURL,int refreshTime){
// constructor code goes here
}
}
Now, let’s consider that refreshTime has to be higher than zero and that rssURL should be a valid http address.
The obvious reflex is to have some value checking logic inside the constructor. However, a call to the constructor instantiates an Object whatever happens. This means the Object ends up being useless if the values don’t allow it to do it’s job. This also means that the Object should be eventually dumped or reused.
So, here’s a couple of questions on the subject:
- Why do some classes impose a getInstance() method coupled with what is probably a private constructor ? If I remember well, one example would be GregorianCalendar.
- In what cases would you use this same approach ?
- In most cases do you have the checking logic in your constructor ?
- If so, do you apply this or not to Entity-style classes used in the persistence context of a domain model ?
All your answers are welcome. It’ll be interesting to get a clear view of the most common practise is.
A few of the most common things:
If you use FactoryMethod for the construction of complex objects you’ll typically have a private constructor and require instantiation through the factory. This supports switching construction strategies with the factory.
Clearest to me would be throw a custom ( and hopefully informative ) Exception in the constructor if instantiation can’t happen: :
public class Person {
This is likely to create a mess in entity persistence objects, mostly because you want these objects to be logic-free, and because the framework should handle this for you – e.g. if you have a bean containing (id, name) in hibernate and try to persist into a table with the name required to be non-null, the error the db throws or from your configuration should be sufficient.