Nested ternaries in C#

#c-sharp #ternaries #cleaner-code

Written by Anders Marzi Tornblad

Every now and then, I encounter code that is more concise than clear, more clever than readable. Some developers prefer prematurely optimized "one-liners" over self-explanatory code.

I think the idea is that code that is expressed with as few keystrokes as possible is more efficient, somehow. In some cases, there might be some small performance advantage to why code is written in a certain way, but in those cases, I would like developers to, at least, add an explanation in the form of a coment.

The latest case for me was finding a nested conditional operator (a ternary operator) while hunting down a bug. This one-liner broke my comprehension flow because it was just a bit too dense:

public string DescribeState(Order order)
{
    return order.IsConfirmed ? order.IsDeleted ? "Cancelled" : "Active" : "Active";
}

There are many ways this code could be rewritten to be easier to understand, which would benefit everybody, not just new people on the team or junior developers. I created a pull request with this change:

public string DescribeState(Order order)
{
    if (order.IsConfirmed)
    {
        return order.IsDeleted ? "Cancelled" : "Active";
    }
    else
    {
        // An order that hasn't been confirmed yet is always shown as active
        return "Active";
    }
}

I decided to keep the inner conditional operator, because that is the "text-book" use of those operators: a simple boolean condition and two different constants to choose from; everything else is messy and unreadable. I also added a short comment about the slightly unexpected return value for when an order is not confirmed, to clarify the decision made at that point. Even though the body of that function is now 9 lines instead of 1, the compiled IL code is almost exactly the same.