Avoid methods with too many local variables

Rule ND1008 Code Smells

Matches methods with more than 15 variables: extremely complex, must be refactored (methods with more than 8 are already hard to maintain).

Variables are counted from compiled IL; compilers may add hidden variables (e.g. for lambdas), hence the threshold of 15 to avoid false positives.

How to fix

Split the method into smaller methods or even new classes. Question each local variable's scope: it may become an instance field of the new class(es).

Estimated Debt: linear from 10 minutes (15 variables) to 2 hours (80+).

CQLinq source

This rule is written in CQLinq, C# LINQ over the NDepend code model. It ships with every new NDepend project: you can read it, adapt it, or use it as a starting point for your own custom rules.

// <Name>Avoid methods with too many local variables</Name>
// <Id>ND1008:AvoidMethodsWithTooManyLocalVariables</Id>
warnif count > 0 from m in JustMyCode.Methods where 
  m.NbVariables > 15 
  orderby m.NbVariables descending
select new { 
   m, 
   m.NbVariables,

   Debt = m.NbVariables.Linear(15, 1,   80, 6).ToHours().ToDebt(),

   // The annual interest varies linearly from interest for severity Medium for 15 variables
   // to interest for severity Critical for 80 variables
   AnnualInterest = m.NbVariables.Linear(15,  Severity.Medium.AnnualInterestThreshold().Value.TotalMinutes, 
                                         80,  Severity.Critical.AnnualInterestThreshold().Value.TotalMinutes).ToMinutes().ToAnnualInterest()

}

//<Expl>
// The *{0}* has {1} variables. This indicates potential complexity, 
// suggesting that it might benefit from being broken down into smaller methods.
//</Expl>

//<Desc>
// Matches methods with more than 15 variables: extremely complex, must be
// refactored (methods with more than 8 are already hard to maintain).
//
// Variables are counted from compiled IL; compilers may add hidden variables
// (e.g. for lambdas), hence the threshold of 15 to avoid false positives.
//</Desc>

//<HowToFix>
// Split the method into smaller methods or even new classes. Question each
// local variable's scope: it may become an instance field of the new
// class(es).
//
// Estimated Debt: linear from 10 minutes (15 variables) to 2 hours (80+).
//</HowToFix>

Code Smells: all 10 items