I recently saw a programmer at a client site developing a small test app. For reasons that didn’t become clearer till later, this person has developed their application in such a way that it did all it’s processing in the class constructor.
When I first saw this I was a bit dumbfounded. The class had a main so the it could run from the command-line. the main method for this class looked like the following.
public static void main(String args) CodeInConstructor c = new CodeInConstructor(); }
So we have a class who’s Constructor has a side-effect of actually doing the work the class is meant to perform. Strange.
Next, as the person developed the application they started to handle and throw exceptions from the processing part of the class. They had try/catch blocks in both the main and the Constructor. Things where getting messy.
When I asked why they were doing this they stated that they did it all the time. Then I explained how this is typically a good habit to have they defended themselves with “Nobody told me”.
Â OK. So to tell others. Here is a good things to get into your head when developing classes.
Use the Constructor to initialize the class and to leave the class in an initialized state. Use methods to perform work thereby requiring that users of your class create the class and they call it’s methods.
For the people who have code in their Constructors. Take the code out and put it in a method which you can call run if you need a suggestion. Then create your object and call the run method.
public static void main(String args) CodeInConstructor c = new CodeInConstructor(); c.run(); (); }