Locally defined

In the olden times, there were some languages which forced you to declare every local variable at the beginning of a function. Oh, and yes: This was, more or less, a technical restriction. That doesn’t mean it’s a good practice in all other cases, although it may satisfy some anal definitions of “tidyness”.

Of course the location of your variable definitions only matters in long methods; which, by definition, you should not have. But if you do, it’s quite a pain when a variable is defined 50 lines from where it’s actually used.

Local variables, in general, are not your friends; they make refactorings harder. In most cases, it’s probably better to ask an object for something repeatedly instead of using a “temp” variable.

Personally, I like to keep local variables as local as possible. This means declaring them in the innermost scope, only declaring them when I’m about to need them and not to re-use a variable for a different purpose.


Comments are closed.

Blog at WordPress.com.

Up ↑

%d bloggers like this: