Posts tagged Developer

Magical Values

When writing code ALWAYS be aware of magic numbers.

You attend a magic show and for the magician’s last trick he performs the old ‘rabbit out of hat’ stunt. As you sit in your seat, you witness the magician actually pull a live rabbit out of the hat he’s been wearing all night! You are stunned, but more so confused where that furry little creature came from in the first place.

Reading poorly written code can often time’s feel like you’re trying to figure out a magic trick. In this post we will cover a strategy that will combat against magical values.

So let’s talk about what magic values are. In its simplest term, a magic value is a value that is directly used within your code that has no context of where it came from.

Take a look at the example below. Can you spot a line that could possibly raise a red flag?

The area we are concerned about is within the conditional. More specifically the integer 5 is our example of a magic value.

Although this chunk of code will work, it’s not the way experienced developers write code.

The developer who wrote the lines in the example will understand it perfectly today and maybe even tomorrow, but what if he/she comes back a year from now to refactor their code? Will he/she be able to remember what 5 means? Better yet, let’s think about other developers who may be working on this chunk of code today. They may have no idea what this integer 5 is trying to perform.

Now I understand that this example is very basic, but we want to get in the habit of writing code in a way that it can speak for itself. That way everyone including yourself stays informed and happy.

Let’s take a moment and refactor our conditional in a way that we can eliminate our magic number.

As you can see in the example above, we extracted the integer 5, and set it to a constant variable outside of the method. Now we can use this constant multiple times within the class, just by calling the constant variable’s name. This is great practice because if we wanted to change the minimum username length to 6, we only have to change one bit of code instead of multiple bits in multiple locations.

The naming of the constant variable is key. A properly named variable will give us information about what the value is trying to accomplish. After all, what’s the point of extracting the magic value if our variable is poorly named?

Here is another example of a magic values, but this time we see both integers and strings:

What does (1..12) and (“a”..”z”) mean? In the example above we do not have the slightest clue. But when we refactor our class, and get rid of the magic values the code instantly becomes more clear:


Take away points:

  • Never write code with non-descriptive values
  • When defining what a value is, set it to a constant variable
  • Make sure your constant variables are properly named
  • Always look for ways to improve readability for yourself and others

 

(Visited 2 times, 1 visits today)