Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting Declaration and Assignment = Good Practice? [closed]

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.)

like image 222
Fiery Phoenix Avatar asked Apr 11 '13 16:04

Fiery Phoenix


People also ask

Should I Split declaration and assignment Java?

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.

What is the difference between declaration and assignment?

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.


2 Answers

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.).

like image 68
Bill the Lizard Avatar answered Sep 29 '22 01:09

Bill the Lizard


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

like image 31
jpredham Avatar answered Sep 29 '22 02:09

jpredham