Code Style and Automatic Formatting in Tomviz
The importance of coding style should not be underestimated, and we have seen a number of changes in our projects over the last few months. Until recently VTK and ParaView used a style for braces that I have only ever encountered in projects coming from our company, with minimal to no support in most editors. Having a consistent coding style is important, but it can also be a pain to describe and takes time to go over in code reviews. I had been tracking clang-format for quite some time now, along with several of its predecessors, but this project seemed different as it built upon the language parser in clang.
--- # This configuration requires clang-format 3.8 or higher. BasedOnStyle: Mozilla AlwaysBreakAfterReturnType: None AlwaysBreakAfterDefinitionReturnType: None BreakConstructorInitializersBeforeComma: false ...
For Tomviz I based our format file on what CMake used in its recent conversion, with some minor adjustments. I was then able to run it in August on all of our source files, and Chris Harris added an automated hook on our GitHub repository to validate that proposed changes comply with the style file. All pull requests are now run through the checks, with the necessary changes supplied if the test fails. This removes the need to review pull requests for coding style, and ensures our code base has a uniform style. Chris has since extended this to our Python code using flake8 too.
Developers can easily apply the style to their changes, I usually run ‘clang-format -i path/to/changed.*’, there are other ways to use the tool too. Now to weigh in on the great brace placement war – we have chosen our side with CMake and keep them on the same line as the statement, preserving maximum vertical space. The ParaView project just merged their clang-format changes this morning, opting to place them on a new line, with VTK using a custom script that also places them on a new line.
Upcoming posts in the series – tabs vs spaces, emacs vs vim, and finally Android vs iPhone (I heard the desktop was dead already, but my typing speed is terrible on a phone and I can’t get my development environment up and running on it). Throwing down the gauntlet, but in all seriousness automating these things frees up development time while still fostering style uniformity. The clang-format tool enables us to express our code style in a very succinct fashion that can be applied very easily before committing changes – it also understands and can work with diffs/git very well.
Oh, and spoiler alert…spaces, vim, Android 😉