• Post Reply Bookmark Topic Watch Topic
  • New Topic

Placement of local variable decleration  RSS feed

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe that local variables should be declared just before use (or as close as possible to use). I think this makes the code easier to understand and in most case you are able to declare and initilize the variable at the same time.

I also found http://www.javaranch.com/styleLong.jsp (see 3.3) recommending to "Declare variables as close as possible to where they are used".

My problem is that we are starting on a new project with lot of newbie programmers and wanted to lay down coding standards (with the Sun Conventions http://java.sun.com/docs/codeconv/html/CodeConventions.doc5.html#16817 as the base). The only point I do not agree with in the Suns conventions doc is the one on declaring variables at the top of the block.

Should I let this particular standard be left open to the developers in my project or is it better to set one of these conventions as a standard and have developers follow it. (Most developers are new and have not yet picked a convention).

Any suggestions/comments?
 
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, I'm with you. I like to put them close to their usage.

However, this doesn't sound like something that should be worrying you too much. Personally, I think a coding standard, to that level of detail, is not helpful.

A coding standard should encourage good practices, which make code more readable, efficient or reliable. It should discourage bad practices, which do the opposite. But it shouldn't go overboard in specifying every little piece of formatting.

An overly-prescriptive coding standard might be taken by many people as a sign of micro-management, and stifling creativity.
 
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I like "as close to use as possible" because it makes "extract method" easier. If a method is so long that it becomes a problem to scroll around and find variable declarations, I'd focus on the length issue first.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!