I’ve recently had a small discussion around my preference of favouring the positive outcome first before the negative outcome for ternary operations - let’s see why.

1
2
3
4
5
6
public static int GetResult(SomeClass obj)
{
    return obj == null || obj.NullableProp == null
        ? 0
        : 1;
}

This is usually done because of preference of minimising usage of !=.

Let’ see how this would look if we actually tried to get the happy outcome first.

1
2
3
4
5
6
public static int GetResult(SomeClass obj)
{
    return obj != null && obj.NullableProp != null
        ? 1
        : 0;
}

Now this may be all subjective, but I’m personally in favour of the way it’s written the latter. This reads in my head as

if obj and it’s property has a value, then return as happy, otherwise we’re sad

The first one involves a bit more thought and reads to me as

if either obj or it’s property has a null value, then we’re sad, otherwise, we’re happy

What requires a bit more thought is reading “either this or that” - this makes me question immediately whether there’s a mistake in the logic and whether the two conditions can both be evaluated.

What do you think? Where do you stand?