Splitting Declaration and Assignment = Good Practice?

Fiery Phoenix picture Fiery Phoenix · Apr 11, 2013 · Viewed 16.7k times · Source

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

Answer

Bill the Lizard picture Bill the Lizard · Apr 11, 2013

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