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.
Randall Twede wrote:also as the OP noticed, some classes don't have constructors.
Every class has at least one constructor. It's just that if we don't provide any, the compiler creates one for us.
And if you wanted to do in in a constructor, you can always create one that just initializes that variable.
However, having said that, I also prefer to initialize at declaration when possible, for member variables (not necessarily for locals though).
Carlo Moore
Greenhorn
Joined: Aug 02, 2005
Posts: 27
posted
0
Thanks for the replies. I'm just used to writing it another way, so when I came across this I wasn't quite sure if any issues would be caused down the line.
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.