user485498
user485498

Reputation:

Initializing object attributes in OO Languages

This question has a slight emphasis on Java but applies to any OO language. Is there any reason not to initialize instance variables in their declarations? It seems there are no obvious reasons not to. It minimizes the risk of silly null pointer exception mistakes.

For example:

class MyClass {

   private String name = ""; // Initialized here

   public MyClass(){

       // Something

   }
}

But in some text books they don't bother to initialize straight away. What might be a reason to not do so? Does it matter?

Upvotes: 5

Views: 5051

Answers (3)

ptomli
ptomli

Reputation: 11818

It totally depends on how the class is intended to be used.

One example would be for value classes, which you might often want to be immutable. Ideally in this case you would set the values in the constructor.

public final class Foo {
    private final String foo;
    public Foo(String foo) {
        this.foo = foo;
    }
}

If there are genuinely sensible default values then you can provide these at the point of declaration. It does tend to make it fairly easy to see what is the expected default value. Of course, that doesn't work with final fields (as above), as it's not possible to assign another value.

Another consideration is concerned with the relative merits of constructor or mutator initialization. Using constructor initialization ensures that the instance is never in an inconsistent state, while mutator initialization is often more flexible and provides an easier API.

In the initial remark regarding avoiding NPEs, I'd say that's best dealt with by using constructor initialization, along the lines of the code above.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477368

This has come up repeatedly on SO, so you should search the site for further opinions.

My suggestion for Java (this only makes sense in certain languages):

If the initial value is fixed for the class, then initialize inline.

If different constructors set different initial values, assign the values in the respective constructor.

In C++11 the situation is somewhat similar.

Upvotes: 3

Nathan Phillips
Nathan Phillips

Reputation: 12435

One case where it is better not to initialise inline is where you have multiple constructors that initialise fields in different ways. It would be inefficient to initialise your field at the declaration and then replace that value with a value passed to a specific constructor later.

Upvotes: 6

Related Questions