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?
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.
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.
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.
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.:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With