views:

552

answers:

8

Hello,

I was thinking how much code one should put in constructors in Java? I mean, very often you make helper methods, which you invoke in a constructor, but sometimes there are some longer initialisation things, for example for a program, which reads from a file, or user interfaces, or other programs, in which you don't initialise only the instance variables, in which the constructor may get longer (if you don't use helper methods). I have something in mind that the constructors should generally be short and concise, shouldn't they? Are there exceptions to this?

Thank you.

+6  A: 

If you go by the SOLID principles, each class should have one reason to change (i.e. do one thing). Therefore a constructor would normally not be reading a file, but you would have a separate class that builds the objects from the file.

krosenvold
thanks, you just helped me avoid breaking the SRP!
Neil Williams
+2  A: 

As little as is needed to complete the initialization of the object.

If you can talk about a portion (5 or so lines is my guideline) of your constructor as a chunk of logic or a specific process, it's probably best to split it into a separate method for clarity and organizational purposes.

But to each his own.

+1  A: 

Constructors should be just long enough, but no longer =)

If you are defining multiple overloaded constructors, don't duplicate code; instead, consolidate functionality into one of them for improved clarity and ease of maintenance.

Zach Scrivena
A: 

As Knuth said, "Premature optimization is the root of all evil."

How much should you put in the consructor? Everything you need to. This is the "eager" approach. When--and only when--performance becomes an issue do you consider optimizing it (to the "lazy" or "over-eager" approaches).

cletus
Performance is usually not the issue; maintenance is! I'm not sure avoiding premature optimization means avoiding premature maintenance optimization...
skiphoppy
Yeah, I don't think this issue is about performance... it's more about designing proper code which is maintainable and easy for others to understand.
Nik Reiman
Yes and the best way to write maintainable code is to write it straightforward (ie eager). Caching for performance tends to grealty complicate code, which is counterproductive if performance isn't evne an issue.
cletus
+3  A: 

Take a look at this SO question. Even though the other one is for C++, the concepts are still very similar.

Marc Novakowski
+1  A: 

Constructors should create the most minimal, generic instance of your object. How generic? Choose the test cases that every instance or object that inherits from the class must pass to be valid - even if "valid" only means fails gracefully (programatically generated exception).

Wikipedia has a good description :

http://en.wikipedia.org/wiki/Constructor_(computer_science)

A Valid object is the goal of the constructor, valid not necessarily useful - that can be done in an initialization method.

Paxic
A: 

My customary practice is that if all the constructor has to do is set some fields on an object, it can be arbitrarily long. If it gets too long, it means that the class design is broken anyway, or data need to be packaged in some more complex structures.

If, on the other hand, the input data need some more complex processing before initializing the class fields, I tend to give the constructor the processed data and move the processing to a static factory method.

quant_dev
A: 

Your class may need to be initialized to a certain state, before any useful work can be done with it.

Consider this.

public class CustomerRecord
{
    private Date dateOfBirth;

    public CustomerRecord()
    {
     dateOfBirth = new Date();
    }

    public int getYearOfBirth()
    {
     Calendar calendar = Calendar.getInstance();
     calendar.setTime(dateOfBirth);
     return calendar.get(Calendar.YEAR);
    } 
}

Now if you don't initialize the dateOfBirth member varialble, any subsequent invocation of getYearOfBirth(), will result in a NullPointerException.

So the bare minimum initialization which may involve

  1. Assigning of values.
  2. Invoking helper functions.

to ensure that the class behaves correctly when it's members are invoked later on, is all that needs to be done.

swapnonil