How far is too far with fluent C#?

448 views Asked by At
public static class Th
{
    public static T e<T>(T theObject) where T : class
    {
        return theObject;
    }        
}

public static class ObjectExtensions
{
    public static bool Is<T>(this T o, Func<T, bool> a) where T : class
    {
        return a(o);
    }
}

//...

//logic in a method somewhere
Func<string, bool> valid = property => _myService.SomeValidationMethod(property);

if (Th.e(_request.Property).Is(valid))
{
   //do something
}

Is this code suitable for production and why?

Edit: Thank you for all your comments. I hope you had as much fun reading my stretching of the C# syntax to breaking point as I did reading your responses.

4

There are 4 answers

3
Jacob On BEST ANSWER

I have no problem with fluent APIs, but this seems to violate the principle of least surprise. I would not understand the purpose of a class named Th nor of a method named e.

2
Frederik Gheysels On

What makes you think that this code is 'fluent' ?

this is absolutely not fluent, nor self documenting.

0
Dylan Beattie On

That is too far. No, the code is not suitable for production. Th.e is neither correctly phrased prose nor appropriately-named code - it's meaningless in both contexts.

0
ceztko On

While what you call "fluency" is extremely important, and most developers are missing that (even who should really care about this, like CS algorithm writers), the code style you showed us is abusing expressibility of the language and not very useful, IMO, for 2 reasons:

  • if (_request.Property.Is(valid)) would be "fluent" enough even without those Th class and Th.e method;
  • Because of this "fluency" your are loosing precious identifiers. What if you need to verify another object? You do if (Th.e(_request.Property2).Is(valid)) or if (Th.e(_request2.Property).Is(valid))? What if you need to perform another test? You do if (Th.e(_request.Property).Is(valid2))?