This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
I've seen some code that someone has wrote which I feel is a bad practice.
The class level attribute should look like this to me
The only reason I can see why this would be a bad thing is that someone can put a whole bunch of logic inside the constructor. There must be some other reasons why this is bad practice but I can't think of why. From what I've seen no constructors have been provided so nothing is going to break right away.
I wonder why you think this is bad practice, because I don't think it is.
Carlo Moore wrote:The only reason I can see why this would be a bad thing is that someone can put a whole bunch of logic inside the constructor.
I don't see how initializing a member variable like that would encourage someone to put a whole bunch of logic inside a constructor.
Suppose that you have a class that needs to have multiple constructors. Initializing the member variable at the class level is a way to avoid having to repeat yourself (with the danger of forgetting it in one of the constructors) in every constructor.
personally i like instantiating when i declare. i did get a comment on some code once where they thought i should do it in the constructor. also as the OP noticed, some classes don't have constructors.
That isn’t a class variable; it is an instance variable.
I would prefer to see that inside the constructor, rather than relying on the compiler to supply a default constructor. As you will see from this link about the javadoc tool, many people think it is bad style to permit default constructors. But it is a style matter, not a definite rule.
If you are overloading constructors, it might be a good idea to chain them with this() calls; then the instantiation of that field can occur in the last constructor called, and you need not write it several times.