user42155
user42155

Reputation: 49665

How much code should one put in a constructor?

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 initialization things, for example for a program, which reads from a file, or user interfaces, or other programs, in which you don't initialize 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?

Upvotes: 22

Views: 15868

Answers (9)

Ramiz Uddin
Ramiz Uddin

Reputation: 4259

Constructor is like an Application Setup Wizard where you do only configuration. If the Instance is ready to take any (possible) Action on itself then Constructor doing well.

Upvotes: 0

Swapnonil Mukherjee
Swapnonil Mukherjee

Reputation: 2342

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.

Upvotes: 0

quant_dev
quant_dev

Reputation: 6231

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.

Upvotes: 2

Paxic
Paxic

Reputation: 1760

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.

Upvotes: 0

Marc Novakowski
Marc Novakowski

Reputation: 45398

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

Upvotes: 4

cletus
cletus

Reputation: 625037

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).

Upvotes: 1

Zach Scrivena
Zach Scrivena

Reputation: 29539

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.

Upvotes: 1

Alex Goodwin
Alex Goodwin

Reputation:

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.

Upvotes: 2

krosenvold
krosenvold

Reputation: 77131

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.

Upvotes: 12

Related Questions