Being an avid user of NetBeans, I keep getting suggestions to split my variable declarations and assignments when I introduce a new variable. As a super quick example off the top of my head, let's take this Java line:
String someInput = JOptionPane.showInputDialog(null, "- Enter something: ");
versus:
String someInput; someInput = JOptionPane.showInputDialog(null, "- Enter something: ");
NetBeans seems to prefer the latter (I wouldn't know about other IDEs, though). While it clearly works both ways, which would be considered 'good practice', if at all? Or s it purely a matter of personal preference?
(Obviously splitting the two means an extra line that you could've just combined into one, but that's beside the point.)
There's no reason to split the declaration and the assignment if you're just going to have them on consecutive lines. I'd only split them if the assignment were conditional, or if it needed to go in a separate code block (like a try/catch, or if the assignment goes in a constructor, etc.). Yes, that about clears it up.
Declaration says, "I'm going to use a variable named " a " to store an integer value." Assignment says, "Put the value 3 into the variable a ." (As @delnan points out, my last example is technically initialization, since you're specifying what value the variable starts with, rather than changing the value.
There's no reason to split the declaration and the assignment if you're just going to have them on consecutive lines. I'd only split them if the assignment were conditional, or if it needed to go in a separate code block (like a try/catch, or if the assignment goes in a constructor, etc.).
A common pattern that traces back to early statically typed programming is to declare all the variables you need at the top of the block they need to be scoped in, and then assign to those values subsequently.
With that said, as long as you're able to clearly communicate the intent of your code to the people you work on it with, or yourself in a year's time, it shouldn't really matter.
Let us change our traditional attitude to the construction of programs: Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do. -- Donald Knuth
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With