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:
- The constants belong to completely different subjects.
- It is difficult to decide if all constants are still in use (The compiler or tools like a Pascal Analyzer can help you).
- If you need a constant it is not easy to find it.
- With point 3 it is possible that you redeclare a constant.
- 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:
- Declare a constant in the unit where you need it.
- If possible declare the constant as a class constant.
- The visibility of a class constant should be as private as possible.
- If you share constants between units define constant units for each subject.
- 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:
unit MyConsts; interface const cFuzzFactor = 1.23456789; implementation end.
Or you can also use class or record constants:
unit MyConsts; interface type TMyConstants = record public const cFuzzFactor = 1.23456789; end; implementation end.
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.