Today, I found another example of a common mistake, a unit with global constants.

I guess most of you know this situation. There is a value that is used several times in a unit and you declare a constant for it. After a few minutes you recognize that you need the constant in another unit. Since it is difficult to decide to which unit the constant belong you simply create a constant unit for it.

With the growth of you project the number of constants in your constant unit increases. After a few weeks the unit contains hundreds of constants. In the current project I mentioned above there are about 600 constants in one unit.

As you can imagine there are some problems according to this unit:

  1. The constants belong to completely different subjects.
  2. It is difficult to decide if all constants are still in use (The compiler or tools like a Pascal Analyzer can help you).
  3. If you need a constant it is not easy to find it.
  4. With point 3 it is possible that you redeclare a constant.
  5. If you need in a new project only one single constant you have to add all the other constants to the project.

In order to avoid the problems from the beginning there are some small rules:

  1. Declare a constant in the unit where you need it.
  2. If possible declare the constant as a class constant.
  3. The visibility of a class constant should be as private as possible.
  4. If you share constants between units define constant units for each subject.
  5. Don’t mix constants in a constant unit that belong to different subjects.

Just to show the difference between normal constants and class constants, please look at these examples.

First you can define normal constants:

Or you can also use class or record constants:

The class constants allow you to play with the visibility, they are more object-oriented and they can be used like namespaces for constants. Therefore they are longer to type in your code. In the Delphi source code normal constants are used, In my code I’m using more and more class constants.

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