Avoid publicly visible constant fields

Rule ND1804 Visibility

Warns about constant fields visible outside their assembly: their value gets hard-coded into client assemblies, so changing it requires recompiling all consumers, else the program runs with different in-memory values — bugs are lurking.

Enumeration values share this pitfall but cannot be static readonly, hence the && !f.IsEnumValue condition; keep it unless you banish public enumerations.

How to fix

Declare matched fields static readonly instead of constant: the value becomes safely changeable without recompiling clients.

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 publicly visible constant fields</Name>
// <Id>ND1804:AvoidPubliclyVisibleConstantFields</Id>

warnif count > 0 
from f in JustMyCode.Fields
where f.IsLiteral && 
      f.IsPubliclyVisible && 
     !f.IsEnumValue
select new {
   f,

   Debt = 30.ToSeconds().ToDebt(), // It is fast to update field declaration
   Severity = Severity.Medium
}

//<Expl>
// The constant *{0}* is publicly exposed  to other assemblies. 
// This situation can lead to binary compatibility problems because 
// when the constant value gets changed, clients of the library 
// may need to be recompiled to use the updated value.
//</Expl>

//<Desc>
// Warns about constant fields visible outside their assembly: their value
// gets *hard-coded* into client assemblies, so changing it *requires*
// recompiling all consumers, else the program runs with different in-memory
// values — bugs are lurking.
//
// Enumeration values share this pitfall but cannot be *static readonly*,
// hence the **&& !f.IsEnumValue** condition; keep it unless you banish
// public enumerations.
//</Desc>

//<HowToFix>
// Declare matched fields **static readonly** instead of **constant**: the
// value becomes *safely changeable* without recompiling clients.
//</HowToFix>

Visibility: all 12 items