Prefer return collection abstraction instead of implementation
Matches methods returning a collection implementation (List<T>, HashSet<T>, Dictionary<TKey,TValue>). Clients rarely need the exact implementation: prefer returning an interface like IList<T>, ICollection<T>, IEnumerable<T> or IDictionary<TKey,TValue>.
Not a rule, since the interface isn't preferable in all cases.
Not a rule, since the interface isn't preferable in all cases.
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>Prefer return collection abstraction instead of implementation</Name>
// <Id>ND2303:PreferReturnCollectionAbstractionInsteadOfImplementation</Id>
// warnif count > 0 // This query is not a rule per default
let implTypes = ThirdParty.Types.WithFullNameIn(
"System.Collections.Generic.List<T>",
"System.Collections.Generic.HashSet<T>",
"System.Collections.Generic.Dictionary<TKey,TValue>")
from m in Application.Methods.WithReturnTypeIn(implTypes)
select new {
m,
m.ReturnType,
Debt = 5.ToMinutes().ToDebt(),
Severity = Severity.Low
}
//<Expl>
// The *{0}* should return a collection abstraction like *IList<T>*
// instead of returning the concrete *{1}*.
//</Expl>
//<Desc>
// Matches methods returning a collection implementation (*List<T>*,
// *HashSet<T>*, *Dictionary<TKey,TValue>*). Clients rarely need the exact
// implementation: prefer returning an interface like *IList<T>*,
// *ICollection<T>*, *IEnumerable<T>* or *IDictionary<TKey,TValue>*.
//
// Not a rule, since the interface isn't preferable in all cases.
//</Desc>
Open in the interactive Rules Explorer · All default rules
.NET Framework Usage / System.Collections: all 4 items
- Collection properties should be read only ND2300
- Don't use .NET 1.x HashTable and ArrayList ND2301
- Caution with List.Contains() ND2302
- Prefer return collection abstraction instead of implementation ND2303