Coding Rules

Rules for writing robust, maintainable code

Rule 4: When you have to write non-straightforward code, explain why

It's usually better to write code in the simplest way possible. However, you might have to write code that looks unnecessarily complicated, for example to improve performance or work around problems in your environment.

If the developers who read your code don't understand why it is written the way it is, they may rewrite it the straightforward way, potentially causing bugs, performance regressions or other problems.

You can explain why your code is written the way it is in comments, commit messages, or, even better, unit tests that test the behavior that is unique to your code.

āœ… Do:

// Fast inverse square root implemented according
// to
// We don't use the built-in implementations because:
//  - it is run in the abcd function that needs to be as fast as possible
//  - the implementation in the libc is about 3x slower
//  - the code will be run mainly on the efgh platform which doesn't
//    support the rsqrtss instruction
float inverse_square_root( float number ) {
  long i;
  float x2, y;
  const float threehalfs = 1.5F;

  x2 = number * 0.5F;
  y  = number;
  i  = * ( long * ) &y;
  i  = 0x5f3759df - ( i >> 1 );
  y  = * ( float * ) &i;
  y  = y * ( threehalfs - ( x2 * y * y ) );

  return y;