One of the most important considerations when writing code, is how to choose identifier names. This holds for Delphi as well as for other languages.
There is plenty of information available about how to select suitable names for your identifiers. In this article, we will discuss another related issue, which is not about how to name identifiers, but more about when to give them a name.
Consider for example this scenario:
type TModule = class .. end; TParsedModules = array of TModule; .. var ModuleIndex : Integer;
The variable ModuleIndex is of type Integer. It is used to point into a TParsedModules array, declared higher up..
Also further down in the code there are functions like:
function InsertModule(InsertIndex : Integer) : Integer; procedure RemoveModule(RemoveIndex : Integer);
This is where we got to the point of today’s article:
A good approach is to declare a special (custom) type:
type TModuleIndex = Integer;
.. and declare the variable as:
var ModuleIndex : TModuleIndex;
The function signatures will now look like:
function InsertModule(InsertIndex : TModuleIndex) : TModuleIndex; procedure RemoveModule(RemoveIndex : TModuleIndex);
Compare this with the original version.
function InsertModule(InsertIndex : Integer) : Integer; procedure RemoveModule(RemoveIndex : Integer);
Compared with the original code, the new version using TModuleIndex conveys much more information about the parameters and result type.
So, in this way, with little effort, your code is much clearer and self-explanatory!
We can summarize the advantages of creating special types: