Put conditional code on the same line as the condition or in brackets.
An if-condition in C# is usually formatted in one of 3 ways:
// #1 if(goat.HasEatenEnough) feeder.Stop(); // #2 if(goat.HasEatenEnough) feeder.Stop(); // #3 if(goat.HasEatenEnough) { feeder.Stop(); }
Of these, #2 should not be used as it can be confusing. It might seem like a small thing, but even industry giant Apple needed to patch a security issue for code that looked something like this:
if(goat.IsHungry) feeder.Start(); feeder.Start(); if(bird.IsHungry) feeder.Start();
if(goat.IsHungry)
only covers the next line, so the second feeder.Start();
is always executed. This is way less probable to happen with #3, as the brackets are a clear visual signal for the beginning and the end of the conditional code. It is also way less probable for #1, as the one line is one cohesive unit.
A bonus is that the visual structure is very close to natural spoken English:
if (goat .HasEatenEnough) feeder.Stop(); If the goat has eaten enough, make the feeder stop.
Next Article: In Public