Refactoring: reduce variable scope

In good code variables are used as short as possible. Often we can see code where variables are defined in wider scope than it is necessary. There are many examples about too wide scopes. One of fuzziest of them is variable that is defined in class scope but it used only by one method and this method uses this variable as local variable. But variable life time can also be reduced in local scope. To achieve this we use refactoring method called reduce variable scope.


NB! This blog is moved to

Click here to go to article


  • Why not reduce the scope of IList too?

    If it isn't used by other parts of the class, it could be a parameter of the Import method.

    The code also looks like it would be better served by a foreach loop ;)

  • I would be interested to see what the Visual Studio code analysis thinks is the correct scope for the invoice variable?

  • To make my point better understandable I added comment // do something with _invoices to the first code block.

    _invoices is class attribute that is used also by other methods. I hope this comment makes things more clear.

Comments have been disabled for this content.