Demeter and Roslyn–part 1–idea
Stop Your C# Code Talking to Strangers: Introducing a Law of Demeter Roslyn Analyzer
The Law of Demeter (LoD), often summarized as “Only talk to your immediate friends,” is a valuable principle for writing loosely coupled, maintainable code. Code that follows LoD tends to be less fragile and easier to refactor.
But manually checking for LoD violations? That’s tedious. Why not automate it?
That’s why I built RSCG_Demeter: a Roslyn Source Code Generator and Analyzer designed to detect potential Law of Demeter violations directly in your C# code.
Why It’s Tricker Than Just Counting Dots
While the simplest LoD violations look like obj.GetThing().GetAnotherThing().DoWork() (too many dots!), real-world C# throws curveballs:
- Fluent Interfaces (return this): Code like builder.SetName(“X”).SetAge(30) chains calls, but it’s calling methods on the same object. This is valid LoD, not talking to strangers! The analyzer needs to recognize this pattern.
123
// Example: EmpBuilder returning 'this'
public
EmpBuilder SetName(
string
name) {
/*...*/
return
this
; }
// Usage: new EmpBuilder().SetName("Alice").SetRole("Dev");
- Complex LINQ Chains: Analyzing expressions like
12
empAll.Select(it => it.ID).Distinct().OrderBy(it => it)
var
ids =
new
List<
int
>(empAll.Select(it => it.ID).Distinct().OrderBy(it => it));
requires more than simple dot counting. We need to understand the sequence of operations and intermediate results.
- Extension Methods (like LINQ): How should we treat IEnumerable<T> extension methods? Technically, each call operates on the result of the previous one. RSCG_Demeter currently flags these as potential violations, promoting simpler data transformations, but this is a configurable aspect of LoD interpretation.
12
empAll.Select(it => it.ID).Distinct().OrderBy(it => it)
var
ids =
new
List<
int
>(empAll.Select(it => it.ID).Distinct().OrderBy(it => it));
RSCG_Demeter in Action
This tool uses Roslyn’s powerful syntax and semantic analysis capabilities to look beyond simple dot counts and identify more nuanced potential LoD violations, while aiming to ignore common valid patterns like fluent builders.
Ready to enforce the Law of Demeter automatically?
Give RSCG_Demeter a try! Find the source code, usage instructions, and contribute here:
https://github.com/ignatandrei/RSCG_Demeter
Help your codebase avoid talking to strangers!
Leave a Reply