Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do fluent interfaces violate the Law of Demeter?

The wikipedia article about Law of Demeter says:

The law can be stated simply as "use only one dot".

However a simple example of a fluent interface may look like this:

static void Main(string[] args) {    new ZRLabs.Yael.Pipeline("cat.jpg")         .Rotate(90)         .Watermark("Monkey")         .RoundCorners(100, Color.Bisque)         .Save("test.png"); } 

So does this goes together?

like image 523
Jakub Šturc Avatar asked Sep 15 '08 22:09

Jakub Šturc


People also ask

What is the Law of Demeter trying to prevent?

The Law of Demeter asks us to minimize coupling between classes and avoid reaching out to the third object in order in order to make refactoring and developing new features easily.

Is fluent interface good?

Fluent interface, first coined as a term by Martin Fowler, is a very convenient way of communicating with objects in OOP. It makes their facades easier to use and understand. However, it ruins their internal design, making them more difficult to maintain.


2 Answers

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.

like image 148
Sebastian Rittau Avatar answered Nov 09 '22 16:11

Sebastian Rittau


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.

like image 42
Jon Limjap Avatar answered Nov 09 '22 17:11

Jon Limjap