Methods tagged with PureAttribute must be pure

Rule ND1911 Immutability

A pure method changes no instance or static field: a function producing a result from inputs, simplifying code by limiting side-effects. A PureAttribute expresses purity in code; this rule continuously checks it and warns when a tagged method is no longer pure.

Use NDepend.Attributes.PureAttribute (from NDepend.API.dll), System.Diagnostics.Contracts.PureAttribute (honored by the compiler only with Microsoft Code Contract enabled), or your own PureAttribute (adapting the rule).

How to fix

Find which modification broke the method purity, then refactor it back to purity.

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>Methods tagged with PureAttribute must be pure</Name>
// <Id>ND1911:MethodsTaggedWithPureAttributeMustBePure</Id>

warnif count > 0 
from m in Application.Methods where 
  ( m.HasAttribute ("NDepend.Attributes.PureAttribute".AllowNoMatch()) || 
    m.HasAttribute ("System.Diagnostics.Contracts.PureAttribute".AllowNoMatch()) ) &&
  ( m.ChangesObjectState || m.ChangesTypeState ) &&
    m.NbLinesOfCode > 0

let fieldsAssigned = m.FieldsAssigned

select new { 
   m, 
   m.NbLinesOfCode, 
   fieldsAssigned,
   Debt = 15.ToMinutes().ToDebt(),
   Severity = Severity.High
}

//<Expl>
// The *{0}* is tagged with the *PureAttribute* yet it assigns the *{2}*.
// This attribute indicates a commitment to keep this method pure
// so make sure it doesn't change any state at runtime.
//</Expl>

//<Desc>
// A pure method changes no instance or static field: a **function**
// producing a result from inputs, simplifying code by **limiting
// side-effects**. A **PureAttribute** expresses purity in code; this rule
// continuously checks it and warns when a tagged method is no longer pure.
//
// Use *NDepend.Attributes.PureAttribute* (from *NDepend.API.dll*),
// *System.Diagnostics.Contracts.PureAttribute* (honored by the compiler
// only with Microsoft Code Contract enabled), or your own *PureAttribute*
// (adapting the rule).
//</Desc>

//<HowToFix>
// Find which modification broke the method purity, then refactor it back
// to purity.
//</HowToFix>

Immutability: all 15 items