3.2. Library packages - JulTob/Ada GitHub Wiki

Ada consistently supports a separation of interface and mechanism. Libraries, such as Simple_IO, are composed by two packages.

Specification, that describes the interface. It contains declarations, public access interface, and private interfaces (data that has to be built externally but must be isolated or limited in access).

The Body, that contains the implementation.

We can define as many library modules as we want. We just have to make an interface file with all the public declarations and a body file with all the private algorithms and implementations.

[module_name].ads

package [module_name] is
  -- Public Declarations
private
  -- Private Declarations
end [module_name];

[module_name].adb

Module’s libraries call]

package body [module_name] is
 -- Hidden Implementation
end [module_name];

We call the libraries from the body so the clients of this library are not clients of those libraries.

Example of Specifications:


Package Simple_IO is
   Procedure Get(F:    out Float);
   Procedure Put(F: in     Float);
   Procedure Put(S: in     String);
   Procedure New_Line(N: in     Integer := 1);
… 
end Simple_IO;

Parameter Specification

In enables de parameter to be used in the right side of an expression, and to be read.

Out enables the parameter to be used in the left side of an assignment expression, and to be overwritten.

They both can be combined in parameters that are both input and output of a process.

Implicitly, all parameters for Functions are input by default.

Also note the Overload specification for Put, allowing two types of inputs.

Last remark, the default value for New_Line as set.

Example of Body:


With Ada.Text_IO;
Package body Simple_IO is

   Procedure Get(F:    out Float) is
      ... --Algorithm goes here
   end Get;

... --Other processes

end Simple_IO;

The Body Package contains full procedures bodies and other supporting material needed for its implementation. It’s hidden from the outside user.

With

The with clause shows that the implementation of the procedures in Simple_IO uses the more general package Ada.Text_IO. The notation indicates that Text_IO is a child package of the package Ada.

Without (Hidding)

Ada has the keyword private. This will give you the opportunity to hide methods and types that you do not want users to freely call.

Private makes the code visible, but not accessible. It happens to be necessary in cases such as making a new record, where the size of the memory space must be known to the OS.

In C++ this 'private' is a protected code.

To contrast, the code inside the body is neither visible nor accesible.

In C++ this is 'private' code.

Conclusion

One purpose of this section has been to stress that the idea of packages is one of the most important concepts in Ada. A program should be conceived as a number of components which provide services to and receive services from each other.🔫