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 Java. 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:
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.