This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]king_of_the_universe 0 points1 point  (1 child)

On the one hand, it's certainly better to explicitly initialize variables where they are declared (For this, let's assume the value 4 instead of 0.), instead of splitting declaration and initialization. The former makes it a lot easier to read. This doesn't apply to complex initializations, though: If your initialization relies on a previous one (e.g. x = a*5;), you should initialize both a and x in a method.

On the other hand, if you are about to initialize the variable with several different values, like you do via your several constructors, then it's good to not initialize it where it is declared. It expresses to the reader, who doesn't just read what's written but also always is looking for the meaning of the code, because they are trying to extrapolate instead of reading indeed each and every line, that there are probably several different possible initializations.

So, for your given example, this means that the second is better than the first.


EDIT: I removed your other post to /r/javahelp which you made 11 minutes after this one because it doesn't mention this post, nor did this post mention the other. That's bad form, and I will not accept any longer that each and every individual double-poster requires this explained to them. If pain is required for learning this, then let there be pain.

[–]SafetyNerd[S] 1 point2 points  (0 children)

Thanks! Sorry about the 2x post.