Evil use of Maybe monad and extension methods in C#?

前端 未结 8 1871
面向向阳花
面向向阳花 2020-12-07 17:11

edit 2015 This question and its answers are no longer relevant. It was asked before the advent of C# 6, which has the null propagating opertor (?.)

8条回答
  •  醉话见心
    2020-12-07 17:20

    Much as I'm a fan of extension methods, I don't think this is really helpful. You've still got the repetition of the expressions (in the monadic version), and it just means that you've got to explain Maybe to everyone. The added learning curve doesn't seem to have enough benefit in this case.

    The IfNotNull version at least manages to avoid the repetition, but I think it's still just a bit too longwinded without actually being clearer.

    Maybe one day we'll get a null-safe dereferencing operator...


    Just as an aside, my favourite semi-evil extension method is:

    public static void ThrowIfNull(this T value, string name) where T : class
    {
        if (value == null)
        {
            throw new ArgumentNullException(name);
        }
    }
    

    That lets you turn this:

    void Foo(string x, string y)
    {
        if (x == null)
        {
            throw new ArgumentNullException(nameof(x));
        }
        if (y == null)
        {
            throw new ArgumentNullException(nameof(y));
        }
        ...
    }
    

    into:

    void Foo(string x, string y)
    {
        x.ThrowIfNull(nameof(x));
        y.ThrowIfNull(nameof(y));
        ...
    }
    

    There's still the nasty repetition of the parameter name, but at least it's tidier. Of course, in .NET 4.0 I'd use Code Contracts, which is what I'm meant to be writing about right now... Stack Overflow is great work avoidance ;)

提交回复
热议问题