Avoid methods with too many local variables
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.
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+).
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>
Open in the interactive Rules Explorer · All default rules
Code Smells: all 10 items
- Avoid types too big ND1000
- Avoid types with too many methods ND1001
- Avoid types with too many fields ND1002
- Avoid methods too big, too complex ND1003
- Avoid methods with too many parameters ND1004
- Avoid methods with too many overloads ND1005
- Avoid methods potentially poorly commented ND1006
- Avoid types with poor cohesion ND1007
- Avoid methods with too many local variables ND1008
- Avoid unmaintainable code ND1009