Law of Demeter (LOD)

  • #engineering
  • #web
  • #fragments

, 2 min read

https://blog.chaoticgood.computer/content/annotations/highlights/www2.ccs.neu.edu/Law-of-Demeter-(General-Formulation)

From www2.ccs.neu.edu

Annotations

Quote

A more general formulation of the Law of Demeter is: Each unit should have only limited knowledge about other units: only units "closely" related to the current unit. Or: Each unit should only talk to its friends; Don't talk to strangers.

This a principle I’ve tried to stick through with Flowthru, which is made easy by connections between its primitives being closely tied to the DAG that they assemble: if you try coupling things together in terrible ways, the flows (which are all DAGs) become immediately nightmarish. “Ugly” DAGs have a somewhat pleasant aesthetic definition: if the visualization of a DAG is structurally fucked, then the DAG itself is probably also structurally fucked.

Coming from Pragmatic Programmer, it’s difficult not to think about this as a form of software rot (tip 3, software entropy): that by reaching for “but X should talk to Y!” too often, there’s a tendency to tangle.

I also think this hails back to Software Gardening: the role of a stack engineer is to make it structurally difficult for a unit of the code to know too much outside its immediate domain, making the Law of Demeter an actual law, rather than a soft rule to be shortcutted past by an agent.

(The Pragmatic Programmer actually touches on that idea: its footnote on the Law of Demeter is “So it’s not really law. It’s more like The Jolly Good Idea of Demeter”. I believe we have more tools than ever to codify this: that’s part of why I enjoy writing linters that make use of .NET’s Roslyn, and do this a lot in Flowthru.)

Quote

A method should have limited knowledge of an object model. This view leads to aspect-oriented programming: we pull out the method and transitively all its auxiliary methods into a separate aspect. This works best if the separate aspect has limited knowledge about the object model.

I think this is something that I really had to noodle on when I first entered into the domain of ORMs, which enforce databases and objects in code to align. Over a lot of time working with EFCore, specifically, I’ve developed a repulsion towards having methods attached to objects that should, in an ideal setup, be purely data objects representing the rows of a table.

It also meshes well in my broken dev brain of thinking about things in terms of little machines on an assembly line, where the data (a product moving across the assembly line) and the actions done to that data ought to be separate things.

Around the Web

No discussion yet. Be the first to reply.

On Bluesky

No discussion yet. Be the first to reply.

On Hacker News

No discussion yet. Be the first to reply.