Skip to content

Latest commit

 

History

History
56 lines (38 loc) · 2.6 KB

File metadata and controls

56 lines (38 loc) · 2.6 KB

MiKo_3084: Place variables, not constants, on the left side of comparisons

Cause

A constant or literal value appears on the left side of a comparison operator instead of the right side; or is used to call the Equals method instead of being passed as its argument.

Rule description

To increase readability, place constants on the right side of an operator, not the left; or pass the constant as argument to an Equals method call. This makes the code look more intuitive and easier to understand.

Rationale behind

The order of operands in comparisons affects how naturally the code reads. Placing variables on the left and constants on the right matches how comparisons are typically expressed in natural language and mathematics.

Following this convention provides several important benefits:

  • Improves Natural Reading Flow: The pattern variable == constant reads like "is the variable equal to this value", which matches natural language. The reverse order constant == variable reads awkwardly and requires mental reversal to understand.

  • Aligns with Mathematical Notation: In mathematics and everyday language, comparisons are typically written as "x equals 5" rather than "5 equals x". Following this convention makes code more intuitive for all developers.

  • Reduces Cognitive Load: When code follows expected patterns, developers can read it more quickly and with less mental effort. Consistent ordering reduces the need to consciously process the comparison direction.

  • Simplifies Code Reviews: Reviewers can scan through comparisons more efficiently when they follow a consistent pattern. Unexpected ordering can cause reviewers to pause and double-check the logic.

  • No Longer Needed for Safety: In older C-style languages, putting constants on the left prevented accidental assignment when = was used instead of ==. Modern C# compilers prevent this error, eliminating the original reason for constant-first comparisons.

  • Maintains Consistency: Consistent ordering throughout the codebase makes the code more predictable and professional. Mixed styles create unnecessary variation that can distract from the actual logic.

How to fix violations

To fix a violation of this rule, swap the operands of the comparison so that the variable appears on the left and the constant or literal appears on the right.

For example:

  • change 5 == count to count == 5, or null == value to value == null
  • change 42.Equals(count) to count.Equals(42)

How to suppress violations

#pragma warning disable MiKo_3084
#pragma warning restore MiKo_3084