C++ Best Practices

Introduction

I’ve been writing C++ code and leading teams developing software and hardware systems coded in C++ for quite a few years now. Over that time I have written various sets of coding guidelines for the C++ environment as well as some rules that are more specific to particular operating systems or development tool sets.

General Rules

  1. Don’t try to be overly clever

    Code that clearly does what it appears to is better than code that manages a clever shortcut or apparent optimization. In general, a decent compiler (and you should be using a decent compiler) will optimize your code better than any hand tweaking can optimize it. If the code looks clever to you and took a while to get right then you should probably assume that the next person coming through will also take some time to figure it out and may not be as clever as you are and may actually break things while trying to modify it.

  2. Assume that someone else will be involved in maintaining your code

    Keep in mind that your code will live on beyond your involvement with it. Consider that a range of people with a varied range of programming expertise will be making changes. The more obvious and easy to understand the design of your code is, the more likely it is that they’ll be able find their way through your code and fix the bugs you missed (and there will be some) or add that new feature that is now required. If a clever use of some advanced language feature will genuinely simplify the overall code then go for it, but make sure there are high quality comments and/or documentation provided and make sure that your code reviewers understand the clever code before you commit the change.

Engineering execution and creativity mixed for the best results…