The programming language behind Delphi is Object Pascal whose origin is in structured Pascal, that is, not object oriented. For this reason it exists in the global variable support syntax. But in an Object Oriented program it is not a good practice to use global variables.
If you still want to use global variables keep in mind the following rules:
1- Global variables are not related to any class.
2- They are declared in the Unit INTERFACE section and when used it is good practice to follow the syntax Unitname.VariavelNome. Example: Unitpessoa.Qtdepopulacao := 1234;
3- They can be referred to in all program codes, Procedure, Function and methods that use Unit in which the variable is defined;
4- They can be initialized or finalized in the Unit INITIALIZATION AND FINALIZATION sections in which it is declared.
Static variables of the "Class Var" classes follow the following rules:
1- They are declared in the class definition and their value is shared by all instances of the class.
2- Class methods may refer to them;
My final suggestion:
1- Use global variable when it stores information related to the Unit in which it is declared, and not specific to a particular class of this Union;
2- In other cases, use class variable that is more elegant, more elucidative, and follows what is defined as good OO practice.
Depends on the intention. If it is a support variable for the class or all instances of that class (or subclasses), it must be a
class var
. If you have interest outside the class and that interest is shared and unique, maybe you should be avar
global, although prefer whenever possible to use a field of a Singleton object, to group fields/properties logically. And that object is in a global variable or is accessible/instantaneous through another global object.– acelent
In general I think it is better to minimize the use of global variables and tend to put the other variables in the classes.
– Tony