Other

Your C# Code Knows Too Much: The Law of Demeter in .NET

C# Corner Shubham Sidnale
Other

Why do chains like Order.Customer.Address.City break so easily? This article walks through the Law of Demeter with order, cancellation and ASP.NET Core endpoint examples, and shows where not to apply it.

Key points

  • Deep navigation ties the caller to other classes' internals, so a single structural change ripples outward.
  • When addresses become a list, order.Customer.Address.City stops compiling and every caller must change.
  • A meaningful operation such as Order.GetDeliveryCity() hides the structure and localizes the change.
  • Moving the rule into Order.Cancel() gives the cancellation logic one owner instead of spreading it across services.
  • An EF Core Select(s => s.Parent.Contact.PhoneNumber) already translates to SQL, so it is not a violation.
  • Banning every dot or wrapping each property in a forwarding method adds boilerplate without improving design.

Why it matters

Nothing ships here, which is exactly why it is worth a few minutes: it targets a habit rather than an API. Teams that expose entities in services and read nested properties see every domain change surface as compile errors deep inside the service layer. The most useful part is that the author refuses to treat the rule as an absolute ban: EF Core Select projections, LINQ chains and fluent APIs are query expressions, and hiding them behind methods only adds layers and cost. Before adopting this, check two things: are read paths already using DTO projections, and do business rules actually live on the entities? Wrapper methods written just to reduce dots tend to make the anemic model worse, not better.

Real-world use

  • An e-commerce order flow where customers move from a single address to multiple addresses
  • An order management service that allows cancellation only while the shipment has not gone out
  • An ASP.NET Core read endpoint whose controller should not know Student, Parent and Contact internals
  • Read-heavy APIs that project DTOs instead of loading a full entity graph

This summary was generated by the agent from the original post on C# Corner. The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message