Wednesday, January 12, 2022

The Zen of Coding - Magic Numbers

I have been coding professionally now for over 30 years in a large variety of languages. There are a number of practices that I have found to be universally best practices regardless of the programming language or programming style in use. Many of these relate to how readable code is, which is the 2nd most important aspect of code, right behind correctly functioning code.

Readable code is more easily maintained, and I have yet to run into the app that I didn't need to revisit and update. In general, code is read an order of magnitude more often than it is written. It is one of the reasons why coding style guidelines are important if there is more than one author working on a project, either concurrently or across time. With the growth of open source and more companies using agile teams, it is rarer and rarer to be the sole author on a project. 

The Zen of coding are these meta rules that apply universally. Many of these items are noted in other places on the internet and in books. You can look at this as my list of favorite coding pet peeves to avoid. Let's, start with the first one magic numbers.

What is a magic number?

A magic number is a literal numeric value in code, outside of a assignment of that value to a named constant. For example 22/7 in the following code is a magic number.

float circularArea radius * radius * 22/7;

Looking at this code, most people are not going to know what 22/7 is. A better way to write the code would be

float circularArea = radius * radius * Math.Pi;

Here we can use a predefined constant as opposed to defining one ourselves. Let's consider a program dealing with force and acceleration. When you find 9.8 sprinkled all over the code you might be able to deduce from the code that it is the value of gravitational acceleration. It would be much better to declare the constant and use the name of the constant everywhere else in the code. For example:

const float gravitationalAcceleration = 9.8;

Doing this not only increases the readability of the code, but also has the added benefit of increasing maintainability. When a more precise value for gravitational acceleration is needed, such as 9.80665, the code only needs to be changed in one place.

Some people have raised a concern that the extra assignment can affect performance. I have yet to run into the case where this is the case. I have gone so far as to prove this by looking at the compiled assembly language to prove it.

Zen of Coding Rule: Use constants whose name has semantic meaning instead of numeric literals. 

Happy Coding.

No comments:

Post a Comment

The 2024 State of DevOps Report and the Importance of Internal Development Platforms

On the State of DevOps Report The State of DevOps Report, published annually by the DevOps Research and Assessment (DORA) team, has been a c...