Legible or not: C# multiple ternary operators + Th

2019-02-02 20:26发布

Do you find the following C# code legible?

private bool CanExecuteAdd(string parameter) {
    return
        this.Script == null ? false
        : parameter == "Step" ? true
        : parameter == "Element" ? this.ElementSelectedInLibrary != null && this.SelectedStep != null
        : parameter == "Choice" ? this.SelectedElement != null
        : parameter == "Jump" ? this.SelectedStep != null
        : parameter == "Conditional jump" ? false
        : false.Throw("Unknown Add parameter {0} in XAML.".F(parameter));
}

where Throw is defined as:

public static T Throw<T>(this T ignored, string message) {
    throw new Exception(message);
}

I know that's not idiomatic C#. However, would you be able at understand it at first or second glance? Or did I stray too far?

15条回答
我欲成王,谁敢阻挡
2楼-- · 2019-02-02 21:05

My rule of thumb: use expressions for things with no side effects. Use statements for things with one side effect and for control flow.

Throwing is effectively a side effect; it does not compute a value, it alters control flow. You're computing a value, computing, computing, computing, and then boom, side effect. I find code like that confusing and vexing. I say that control flow should be in statements, not the side effect of something that looks like a computation.

查看更多
我只想做你的唯一
3楼-- · 2019-02-02 21:05

At first I was horrified, but actually I can't think of a way to write this much clearer in C# - I was trying to think of something where you had an array of Funcs mapped to results, but it got even uglier.

Even though parsing through the actual conditionals is rough, it's at least easy to grok the intent, though I'd prefer to use a switch block and handle everything else as a special case.

查看更多
Anthone
4楼-- · 2019-02-02 21:07

I really don't like this code. It took me more than about 15 seconds to understand, so I gave up.

An if/then would be preferable.

查看更多
登录 后发表回答