开发者

What is the proper way to declared class objects?

This is just a quick question to settle a dispute that I stumbled on a while back (sorry I don't have the link).

How I have been declaring object is as so:

class Foo {

   private Bar aBar = new Bar();

   ...

}

Now the dispute that I found says that this is bad Jav开发者_开发问答a. I have no idea why he would say that, but he was quite adamant. What he proposed was that all objects should be declared in the class body, but not instantiated until the constructor. Can anyone shed light on this for me? Is it indeed better to instantiate objects in the constructor?

TFYT

~Aedon

Edit 1:

I know that I used the word dispute, but I do not intend for this to be argumentative.


In most cases it doesn't matter. My rule of thumb is:

  • If you're going to use the same expression to initialize the variable in all constructors, and it doesn't rely on any parameters, do it at the point of declaration.
  • Otherwise, you're pretty much forced to do it in the constructor anyway.

Reasoning: by initializing at the point of declaration, it's clear that the value is going to be assigned the same way regardless of the constructor and parameters. It also keeps your constructors simpler, and free of duplication.

Caveat: Don't also assign the value in a constructor, as otherwise that invalidates the previous clarity :)

I suggest you ask your colleague (or whatever) for concrete reasons for his claims that your current code is "bad". I'm sure there are valid alternative points of view, but if he can't provide any reasons, then there's no reason to pay attention IMO.

Another quick note - I'm assuming that none of the initializers need to do any significant work. If they do, that could be a point of confusion, especially if exceptions are thrown. In general, I don't like my constructors doing a lot of work.


By assigning properties in the constructor, it becomes immediately clear what code will run when you instantiate your class.
If you assign inside a field declaration, people reading the class constructor won't realize that the field is set elsewhere.


The contract of a constructor is to create an instance that is semantically valid. That is all fields are properly initialized to reasonable values and so on. For this reason, initializing everything in the constructor helps to clarify what makes a valid instance of your class. In addition, mechanisms like constructor chaining can be used to avoid repeating the same code when you have multiple constructors.

However, that is just a textbook-like theory and in real life you sometimes do the more expedient thing. Since it will make almost no difference if you instantiated objects at the point of declaration or not there need be no strong positions that leads to disputes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜