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.