Putting constants and literals on the left sides of an expression

It amazes me how much simple and complex code has been written by experienced developers without following some basic programming conventions of putting constants and literals on the left sides of an expression. I am thinking about the use of  ‘=’ operator in ‘if’ statements. Some languages such as Visual Basic interpret it differently depending on the context. For instance:

[VB]

Dim length As Integer = 5
Dim perimeter As Integer = 0
If (length = 0) Then // Case 1
Console.WriteLine("Length must be greater than zero")
Else
perimeter = 4 * length // Case 2
Console.WriteLine("Perimeter is {0}", perimeter)
End If

The output of this method is: ‘Perimeter is 20‘.
In the first case ‘=’ operator is used to compare the variable ‘length’ and the constant ‘0’. However, in the second case it is used to assign a value
to the ‘perimeter’ variable. Even though the same ‘=’ operator was used the meaning was different because of the context.
Unlike VB there are languages such as C++ which unambiguously interpret ‘=’ operator. For instance:

[C++]

 int length = 5;
    int perimeter = 0;
    if (length = 0)  // Case 1
    {
        printf(“Length must be greater than zero”);
    }
    else
    {
        perimeter = 4 * length;  // Case 2
        printf(“Perimeter is {0}”, perimeter);
    }

The output of this method is: ‘Perimeter is 0‘.
In both cases ‘=’ operator is used to assign a value to the variable. Most of the time this is not the intention of a developer. It is usually intended to compare two values in the ‘if’ statement. These kinds of bugs are very easy to introduce and relatively hard to track down.
Luckily we can make a compiler work for us by putting constants and literals on the left sides of expression, like this:

[C++]

if (0 = length) // Case 1
{
    printf("Length must be greater than zero");
}

In this instance the compiler would catch the error because assigning anything to a literal is invalid. We would catch the potential bug during compilation time instead of debugging.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.