Naming of Constants

Normally constants improve the readability and maintainability of your code. One example is the minimum value of a single. You can find it in the unit System.Math:

...
const
  MinSingle   =  1.4012984643248170709e-45;
...

Instead of writing the float value it is easier and more readable to use the MinSingle constant.
But today I found a way how to do this in a very bad way. Someone had to parse a text file. One feature was that is was possible to delete values. Therefore the writer of the file used a special value, a “*”. That’s why I found the following code:

const
  cStar = '*';
var
  sValue: string;
  ...
begin
  ...
  if sValue = cStar then
    DoDeleteValue
  ...
end;

This is complete nonsense! If you really have no idea how to name your constant then simply don’t use it! The name always should refer to the meaning of the constant and not to the content.
Maybe something like this is better:

const
  cDeleteValue = '*';
var
  sValue: string;
  ...
begin
  ...
  if sValue = cDeleteValue then
    DoDeleteValue
  ...
end;

 

This entry was posted in Tips and Tricks and tagged . Bookmark the permalink.