DEV Community

Discussion on: Fluent APIs Make Developers Love Using Your Libraries

Collapse
 
torvin profile image
Torvin • Edited

I love fluent APIs. But please, please don't make fluent APIs mutable! They become very confusing. Consider this code using your class:

var x = MyFluentClass.WithValue(5).Add(1);
var y = x.Subtract(6);
Console.WriteLine(x.Result()); // most people would expect 6, but the result is 0

This is one of the things that is killing moment.js that otherwise was pretty great.

Collapse
 
jamesmh profile image
James Hickey

I would agree 100%. The class I used in the article actually wouldn't work in the snippet you made 😉

The second line of your code snippet would throw an exception since the only available method would be Result, which I highlighted in the article.

It should actually do what you want (immutable) 👍

Collapse
 
torvin profile image
Torvin • Edited

You are right, sorry, my bad! Try this:

var x = MyFluentClass.WithValue(5);
var y = x.Subtract(5);
Console.WriteLine(x.Add(1).Result()); // correctly returns 6
Console.WriteLine(y.Result()); // 6 again?!
Thread Thread
 
jamesmh profile image
James Hickey

Sure, anyone can try to misuse code if they really want 😜😂