Avoid transforming an immutable type into a mutable one

Rule ND1108 Code Smells Regression

Runs only in diff mode (baseline defined). Warns when an immutable type (instance fields unmodifiable after construction) became mutable.

Immutable instances can be used concurrently without synchronization, so users often rely on immutability; breaking it may break their code.

How to fix

If immutability matters for the matched type, refactor to preserve it.

Estimated Debt: 10 minutes plus 10 minutes per instance field now mutable. Severity is High: fix these issues now, before such code gets released in production.

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 transforming an immutable type into a mutable one</Name>
// <Id>ND1108:AvoidTransformingAnImmutableTypeIntoAMutableOne</Id>
warnif count > 0
from t in Application.Types where
   t.CodeWasChanged() &&
   t.OlderVersion().IsImmutable &&
  !t.IsImmutable && 
  // Don't take account of immutable types transformed into static types (not deemed as immutable)
  !t.IsStatic

let culpritFields = t.InstanceFields.Where(f => !f.IsImmutable)
select new {
   t, 
   culpritFields,
   Debt = (10 + 10*culpritFields.Count()).ToMinutes().ToDebt(),
   Severity = Severity.High
}

//<Expl>
// The *{0}* used to be immutable in the baseline
// and is now mutable because of the *{1}*.
// Avoid breaking immutability because client code
// might rely on this property.
//</Expl>

//<Desc>
// Runs only in *diff mode* (baseline defined). Warns when an *immutable*
// type (instance fields unmodifiable after construction) became mutable.
//
// Immutable instances can be used concurrently without synchronization, so
// users often rely on immutability; breaking it may break their code.
//</Desc>

//<HowToFix>
// If immutability matters for the matched type, refactor to preserve it.
//
// Estimated Debt: 10 minutes plus 10 minutes per instance field now mutable.
// Severity is **High**: fix these issues **now**, before such code gets
// released in production.
//</HowToFix>

Code Smells Regression: all 9 items