Do fluent interfaces violate the Law of Demeter?

Solution 1:

Well, the short definition of the law shortens it too much. The real "law" (in reality advice on good API design) basically says: Only access objects you created yourself, or were passed to you as an argument. Do not access objects indirectly through other objects. Methods of fluent interfaces often return the object itself, so they don't violate the law, if you use the object again. Other methods create objects for you, so there's no violation either.

Also note that the "law" is only a best practices advice for "classical" APIs. Fluent interfaces are a completely different approach to API design and can't be evaluated with the Law of Demeter.

Solution 2:

Not necessarily. "Only use one dot" is an inaccurate summary of the Law of Demeter.

The Law of Demeter discourages the use of multiple dots when each dot represents the result of a different object, e.g.:

  • First dot is a method called from ObjectA, returning an object of type ObjectB
  • Next dot is a method only available in ObjectB, returning an object of type ObjectC
  • Next dot is a property available only in ObjectC
  • ad infinitum

However, at least in my opinion, the Law of Demeter is not violated if the return object of each dot is still the same type as the original caller:

var List<SomeObj> list = new List<SomeObj>();
//initialize data here
return list.FindAll( i => i == someValue ).Sort( i1, i2 => i2 > i1).ToArray();

In the above example, both FindAll() and Sort() return the same type of object as the original list. The Law of Demeter is not violated: the list only talked to its immediate friends.

That being said not all fluent interfaces violate the Law of Demeter, just as long as they return the same type as their caller.