Don't use constant values in programming

One of the most time-consuming part of programming is debugging. When making an estimate, programmers will guesstimate how long it might take them to create a program from the ground up. One thing we always forget to take into account is the time we will spend debugging. It is inevitable, your program will have some flaws, it is just human nature.

But those flaws can be reduced to a minimum if we follow some conventions. The convention I want to talk about today is Avoiding constant values. Let me show you an example.

$total = $price + ($price * 8.75/100);

This is very simple and most people will not have problem understanding it. Well, that's what we assume, that most people will get it. We know what $total is because it is called total. The same goes for price. But what about 8.75? What is it? If you are in California you might know that it is the tax rate, but that depends on the region vastly. If you are in a region where the tax rate is 9.25% then 8.75 will mean nothing to you.

So to fix that, simply replace the constant value with a variable with an appropriate name.

$total = $price + ($price * $taxRate);

The tax rate can be defined elsewhere or just before being used. The important thing is that your code is self documented. Anyone looking at it will know exactly what it is doing.

Another advantage is that you can simply change the value of $taxRate in one place and it will reflect everywhere it is used.

This is not limited to numbers, I talked about it before when using strings. You can use the same method to organize values in a single place to help everyone be on the same page.

Bugs are inevitable. But if you follow a convention that takes something that is valid but confusing, and make it look wrong you will spend less time trying to figure out what is wrong.

For the same reason, fixing bugs should be natural process we go through. When you open a page and there is an error. Pressure will only make it harder to fix. If you know that making a mistake is not going to get you fired then you will have one less thing to worry about when looking for the problem.

But there is a mentality that has to be changed to in the developers perspective. A bug is not a bad thing. It's a problem you have to fix. Aren't we problem solvers? So when you discover something is wrong, go through the process of finding it and fixing it.


George :

If you are going for best contents like myself, just pay a quick visit this web page everyday since it offers feature contents, thanks

Let's hear your thoughts

For my eyes only