Why need to specify unit names?

| category: Programming | author: st
Tags: ,

In the previous article "Crack C# namespaces in 30 seconds" I demonstrated how to make error having no idea about it. So you will have a lovely time in debugging. But in C# you're condemned to use using directive or your code will be unreadable with all these horrible specifiers

MySolution.AppModules.Accounting.AccountingType.DefaultValue

In Delphi and Free Pascal you don't obligate to specify the unit name but this practice is highly recommended to avoid similar errors. A simple example is following.

Main program:

program Print;

uses
  Orders;

begin
  writeln('Order default state is ', DefaultState);
end.

The constant is defined in Orders unit:

unit Orders;

interface

const
  DefaultState = 'submitted';

implementation

end.

When running, the results is as expected:

Order default state is submitted

One fine day, you need to use some functions from Calculs unit.

unit Calculs;

interface

const
  DefaultState = 10234;

implementation

end.

Add this unit in the main program:

uses

Orders, Calculs;

When running, you will be surprised...

Order default state is 10234

The correction is evident:

writeln('Order default state is ', Orders.DefaultState);

Conclusions

  • It is a good idea to specify unit name for the constants, generic named functions and even for some public types.
  • The declaration order in uses section is important not only because of initialization/finalization sections. You should better start with core units such as SysUtils and Classes, then OS-specific (Windows, Unix ...), , then framework-specific (Forms, Dialogs...) and finish by application-specific units.

blog comments powered by Disqus