Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is There a Benefit to Using Fully Qualified Namespaces in the Uses Clause?

Is it better to fully qualify the namespaces in the uses clause? For example, is one of these declarations better than the other?

uses
  ShellApi,
  Windows,
  SHFolder,
  SysUtils;

uses
  Winapi.ShellApi,
  Winapi.Windows,
  Winapi.SHFolder,
  System.SysUtils;

like image 507
Michael Riley - AKA Gunny Avatar asked Jul 13 '14 00:07

Michael Riley - AKA Gunny


2 Answers

It really depends on what you're building. If it's a simple VCL application as Delphi is most known for, then you usually don't need to worry about it. However, if you're building a package, with components for example, you need to be sure to clearly define which environment you intend to use: VCL or FMX. Embarcadero added namespace prefixes to be able to differentiate different possible solutions.

However, in most scenarios, the . only serves as a visual representation. It helps you, the coder, be able to identify which libraries you're using.

Take this other question for example. The Delphi IDE/Compiler would not accept one very common unit without either adding the namespace prefix or the namespace in the project options. The standard Graphics unit needed to be explicitly defined as Vcl.Graphics, as opposed to FMX.Graphics.

On a side-note, using the full namespace is comfortable for many coders who come from other languages where it was strictly enforced, and not only that, but allows you to see the nature of everything in a single glance, without having to look elsewhere for more information about what you're actually using.

EDIT

In addition, I just recently saw that using fully qualified namespaces also helps speed up compile-time, because the compiler doesn't have to try to resolve all the namespaces.

like image 169
Jerry Dodge Avatar answered Nov 04 '22 06:11

Jerry Dodge


The main benefit of fully qualifying names is that your code can be compiled successfully into projects, irrespective of the namespace prefix settings of those projects.

Why is this useful? Well, if you are writing application code then you likely know and control the namespace prefix settings of the project(s) that contain a particular unit. However, if you are writing library code, code that is intended to be included in projects outside of your control, then you cannot predict what the namespace prefixes will be in those projects. If you do not fully qualify unit names, then you place a constraint on the projects settings of any project that consumes your library code. And library code is expected not to do that.

So, in summary, for application code, namespace qualifiers can reasonably be omitted, if you prefer less verbose names. For library code, fully qualified names should be used to allow the library code to stand alone.

like image 28
David Heffernan Avatar answered Nov 04 '22 06:11

David Heffernan