Best practice for initializing object attributes in OO languages

This question has a slight emphasis on Java, but is applicable to any OO language. Is it good practice to initialize class variables in your declarations? It seems to me so obvious. This minimizes the risk of stupid pointer pointer exception errors.

For example:

class myClass{ private String name = "";// initialize here public myClass(){ //something } } 

But in some textbooks, they do not want to initialize right away. What's better? Does it matter?

+7
source share
3 answers

One case where it is better not to initialize inline is where you have several constructors that initialize the fields in different ways. It would be inefficient to initialize your field in the declaration, and then replace that value with the value passed later to the particular constructor.

+5
source

This has been repeated many times on SO, so you should look for additional opinions on the site.

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

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

If different constructors specify different initial values, assign values ​​in the corresponding constructor.

In C ++ 11, the situation is somewhat similar.

+3
source

It completely depends on how the class should be used.

An example is value classes, which can often be immutable. Ideally, in this case, you should set the values ​​in the constructor.

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

If there are really reasonable defaults, you can provide them at the point of declaration. This, as a rule, makes it pretty easy to see what the expected default value is. Of course, this does not work with leaf fields (as indicated above), since it is impossible to assign a different value.

Another consideration concerns the relative merits of initializing a constructor or mutator. 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 comment on avoiding NPE s, I would say that it is best to use it by initializing the constructor according to the code above.

0
source

All Articles