X

Refactoring: introduce constant

One way to write messy code is to use constant values in code without any explanations about their values or purpose. Sometimes it feels like too small problem to think about, specially when there are only couple of constants, but I am sure that hard coded constants may waste developers valuable time more than one may think at first place. To make this kind of code easier to read and understand we can use refactoring method called introduce constant.

Let’s look at the following code.

public class TerminalConnector  

    private TerminalConnection _connection; 

    ... 

    public int ReadCurrentValue() 
    { 
        _connection.SendCommand(new byte[] { 0x34, 0x33, 0x00 }); 
        return _connection.Read(0x03); 
    } 
}

We can see there some constants in hex format and some byte arrays. Nothing tells us what these values mean. Although we may think that it is easy to understand to everybody when we write the code it is not so. After month or two we don’t remember the meaning of these values anymore. Other developers who read this code understand it even less.

Let’s make our previous code more easily readable now. Each refactoring takes only three steps here:

  1. define new constant with meaningful name,
  2. assign hard coded value to it,
  3. replace hard coded value with constant.

After refactoring our code will look like this.

public class TerminalConnector  

    private TerminalConnection _connection; 

    private byte[] const _currentValueCommand = new byte[] { 0x34, 0x33, 0x00 };
    private int const _readIntegerCommand = 0x03; 

    ... 

    public int ReadCurrentValue() 
    { 
        _connection.SendCommand(_currentValueCommand); 
        return _connection.Read(_readIntegerCommand); 
    } 
}

As a result of introduce constant refactoring our code is now much easier to read than before. If somebody else has to modify this code then he or she can easily understand what this code does.

Liked this post? Empower your friends by sharing it!
Categories: C#
Related Post