Best practice for initializing object attributes i

2019-06-18 00:40发布

This question has a slight emphasis on Java but applies to any OO language. Is it good practice to initialize class variables in their declarations? It seems obviously so to me. It minimizes the risk of silly null pointer exception mistakes.

For example:

class myClass{

   private String name = "";// initialize here

   public myClass(){

    //something

   }
}

But in some text books they don't bother to initialize straight away. Which is better? Does it matter?

3条回答
爷的心禁止访问
2楼-- · 2019-06-18 01:17

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.

查看更多
Melony?
3楼-- · 2019-06-18 01:21

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.

查看更多
够拽才男人
4楼-- · 2019-06-18 01:34

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.

查看更多
登录 后发表回答