Formatting

Professionalism, Craftsmanship, Discipline

This section is about how my code is formatted in the IDE. Careful and considered formatting helps to make the intent of the code easy to read and understand.

Firstly, don’t fight the IDE. My normal weapon of choice is Visual Studio and I don’t mess with the changes made by the IDE’s own formatting commands. It’s a tail I’d be forever chasing. Beyond that, here are the rules I live by…

Whitespace discipline is important:

  • Use blank lines to separate things that should be separated
    • 2 lines between methods
    • 1 blank line to separate ifs and loops from surrounding code
    • 1 blank line between variables and code
    • 1 blank line after return unless followed by a brace

One Class per File. Each class should be in it’s own file, named after the class.

Source files are mostly quite small, 50 or 150 lines is not uncommon. If a source file is more than 500 lines I double check to make sure the isn’t an SRP violation.

Horizonal Formatting: Never make your reader scroll horizontally. Modern screens are getting wider so this rule is changing but I think regardless of screen with lines of more than around 100 characters are painful. Most of the time lines are less than 40 or so characters. For indenting I stick with the Visual Studio default of 4 spaces.

Braces:

C# uses ANSI/ISO style braces.

void MyMethod()
{
}

Java, JavaScript & Typescript us K&R* style braces

void MyMethod() {
}

Just One If

I hate putting braces around single line ‘if’ statements and prefer the second styling below…

if (somePredicate)
{
    DoSomething();
}

if (somePredicate)
    DoSomething();

The first option seems to be to unnecessarily add to the length of the file, forcing the reader to scroll more. However, using braces in this way seems to be pretty much the Microsoft defined best practice for C# and you can’t fight city hall. Whichever option you prefer, in any given project, pick one and stick to it. If you don’t use braces then you should at least put the ‘DoSomething’ call on its own line so you can easily set a break point on it.

* K&R: Kernighan & Ritchie, the authors of the C language (https://en.wikipedia.org/wiki/The_C_Programming_Language)

Coding Standards