I’ve been writing C++ with Microsoft’s practices since my very first line of C++. I dabbled in Google and LLVM style for a while but I always ended up doing a full 360 back to Microsoft because it just feels the most natural with me. Since clean code is one of the topics that we cover in CS348, I wanted to look into where the style I have been using forever actually comes from. It actually turns out that the Microsoft style in clang-format is based on Microsoft’s .NET coding conventions.
The page is a “how to code like us” guide which shows full examples of C# and how each rule applies. It’s built around four goals which are correctness, teaching, consistency, and adoption. I mostly only care about the layout rules. Which is four spaces for indentation with no tabs, Allman style braces so every brace gets its own line, one statement per line, and comments on their own lines. It also says teams can change conventions to fit their needs and use a .editorconfig file so Visual Studio enforces it automatically.
The part that sticks with me more than anything is that every rule has a reason tied to who is reading your code. They limit lines to 65 characters because people read the docs on their phones, which is a bit shorter than what LLVM standards ask for. They also say only use var (aka auto in C++) when a reader can tell the type from the code which is a standard that Google also says, because its not like you can just control click on your phone to see the variable’s type, if need be. I guess the lesson to be learned from that is that a style convention isn’t only about what always looks right but it should be built around who the readers are.
In my opinion, four space indent just makes sense and so do Allman braces because man do I hate braces on the same line.
// We love this đđ
if (exp)
{
foo();
}
else
{
foo2();
}
// We heavily dislike this đâšī¸
if (exp) {
foo();
} else {
foo2();
}See? Doesn’t that just look so much better?
As always, I will continue to strictly use Microsoft style for everything, like school projects, open source projects, and closed source projects, because it is an easy to track and industry loved styling convention. My .clang-format is basically just “BasedOnStyle: Microsoft” so it reformats anything I miss automatically every time I save.
At the end of the day, the person reading your code should always matter more than the person writing it, and most of the time that person reading your code actually ends up being you.