When it comes to the style of code a lot of it is personal preference, and unfortunately we too often focus on these preferences as opposed to the parts that can be clearly reasoned as a better style. The obvious example is curly braces…

public void MyMethod()
{
}
public void MyMethod() {
}

In terms of readability one isn’t really any better than the other. You can reason why one is better, but it really is just a personal preference. Personally I prefer it on a new line. Why? Well, the biggest benefit to me is it works better with my code alignment extension.

But there are ways of formatting our code which is clearly superior. As I’ve been saying for years, the most important one is code alignment – lining up your code makes it so much more readable.

But I wanted to focus on one case today and that’s ANDs and  ORs. It’s something that a lot of people aren’t too disciplined with. When it’s simple and on a single line it’s fine but as soon as it needs to be split, people don’t know where to put the && and ||. The first way is

if (myObject != null &&
    myObject.Kind == Kind.MyKind &&
    myObject.HasValue &&
    myObject.Value >= myObject.MinValue)

this is what I think most developers do. But it sucks. The Ands are hidden if one was an OR it could be easily missed. So the first thing we can do is align the Ands.

if (myObject != null             &&
    myObject.Kind == Kind.MyKind &&
    myObject.HasValue            &&
    myObject.Value >= myObject.MinValue)

It reads nicer but it still has problems. First if it add a new value the ands need to be moved, our eyes are attracted to the left first, not the right. And when we talk, we say X… AND Y. The AND is more of a prefix than a suffix. This leads to…

if (myObject != null
&&  myObject.Kind == Kind.MyKind
&&  myObject.HasValue
&&  myObject.Value >= myObject.MinValue)

Here the AND is clearly shown as a continuation of the if. Our eyes quickly jump to the symbol.

And in case you’re wondering it works with anything not just an if

bool value = condition1
          || condition2;

return value1
    || value2
    || value3;