Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespaces in Delphi

Are there any practical benefits in using long unit file names like MyLib.MyUtils.pas or it is just a kind of unit name prefix?

like image 479
kludg Avatar asked Jan 20 '10 09:01

kludg


3 Answers

Namespaces, like all identifiers, are meant to organize.

So using them, only benefits if your project gets organized in a better way. This highly subjective matter (there have been 'wars' on even the most simple naming conventions!), so impossible to really answer.

Here is some documentation on how namespaces work in Delphi.

Note that 'true' namespaces (where more than one generic DLL can contribute to the same namespace; this is how namespaces function in the .NET world) are not possible in Delphi: you could go the BPL way, but that is not the same as a 'generic DLL'. This is not a limitation of Delphi itself, but the way that native DLLs in Windows 'work'.

--jeroen

like image 182
Jeroen Wiert Pluimers Avatar answered Nov 04 '22 05:11

Jeroen Wiert Pluimers


See:

Why does Delphi (dcc32.exe) have an option to set a “Namespace search path”?

Namespaces in Delphi are supported by the compiler, so the dot in the unit names has a special meaning. You can use the full qualified name of the file, or you can use a 'shortcut' style for the file name if the dcc32.exe option is set up properly.

So you could also write

uses
  MyBestTools;

to avoid the full qualified name

uses
  MyCompany.MyProject.MyLibrary.MyBestTools;

Disclaimer: currently this is all theory but I will make use of namespaces in some projects iin the near future

For an even better IDE support, feel free to vote in QualityCentral for this feature suggestion:

Visualize the unit namespaces hierarchy in the IDE

like image 29
mjn Avatar answered Nov 04 '22 06:11

mjn


I edited this answer in response to the comments and my obvious misunderstanding of the question.

The only practical benefit I see in using unit names like you suggest is that the IDE will sort the units in a better way than without the "namespace" prefix. I would prefer using different folders instead.

In some cases it might make sense - because of name collisions. You could for example have a unit MyLib.Utils and a unit MyOtherLib.Utils This can indeed avoid some confusion (both for the IDE and for yourself).

You could also simulate a namespace using an abstract class with static class methods:

type
  Utils = class abstract
    class procedure Beep; static;
  end;
...
Utils.Beep;   
like image 1
jpfollenius Avatar answered Nov 04 '22 06:11

jpfollenius