Sunday, December 4, 2011

Before or after ?

When declare variable in function: in the beginning of the function body, or  just before exact moment of use (if it's possible) ? 

The most natural choice we made is declare in the moment of use of the variable. So simple and seems trivial question turned out in a serious debate on StackOverflow, when I post that question after having a long discussion with colleague of mine: Scope of variables in C#.

Interesting thing that I found was, that from memory consumption perspective there is no any difference. As variables on function's local scope are pushed on stack by the way, will their be used or not.

The answer of Bruno Brant clearly shows what happens.


The sample code:
 static void Main(string[] args)
 {
    var a = 3;
    if (a > 1){
        int b = 2;
        a += b;
    }
    var c = 10;
    Console.WriteLine(a + c);
 }



This is IL output of provided code:

.method private hidebysig static void  Main(string[] args) cil managed{
  .entrypoint
  // Code size       24 (0x18)
  .maxstack  2
  .locals init ([0] int32 a,     // Declare a
           [1] int32 b,          // Declare b
           [2] int32 c)          // Declare c
  IL_0000:  ldc.i4.3          
  IL_0001:  stloc.0            
  IL_0002:  ldloc.0            
  IL_0003:  ldc.i4.1          
  IL_0004:  ble.s      IL_000c
  IL_0006:  ldc.i4.2
  IL_0007:  stloc.1
  IL_0008:  ldloc.0
  IL_0009:  ldloc.1
  IL_000a:  add
  IL_000b:  stloc.0
  IL_000c:  ldc.i4.s   10
  IL_000e:  stloc.2
  IL_000f:  ldloc.0
  IL_0010:  ldloc.2
  IL_0011:  add
  IL_0012:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_0017:  ret} // end of method Program::Main


It's clearly visible that "b" variable is pushed on stack even if it's in conditional "if" scope, so potentially could never be used during program run.


The architectural goodness of declaring the variable just in the moment of use  is clearly visualize the scope of use of that variable, and be sure that none outside of that scope is able to change it in any way.
Remark from Reed Copsey's post:
"In C#, it's better to place them at the scope where they are needed. This has a few benefits, including: 
1.   You reduce the risk of error from reusing a variable inappropriately, especially during long term maintenance
2.   You are keeping the variable constrained within that scope, which eases refactoring
The last point is, in my opinion, the most important. Good maintainability and testability rely on the abiltiy to keep your methods small - and keeping variables declared as they're used makes extracting a method much, much simpler. Not only do the tools become more effective, the resulting automatic refactorings tend to be simpler (as the variable isn't passed in by ref, etc)."
Thumbs up guys !









2 comments:

  1. Usually giving meaningful names reduces the risk of polluting the scope of other variables and helps code interpretation..
    I mean, calling a variable 'a' will be surely more error-prone than calling 'currentElementPosition'..

    ReplyDelete
  2. Agree, but this more about the SCOPE of variable declaration, and not so much about "the naming technique".

    ReplyDelete