13.3 Generic Packages

Generic packages are the most powerful mechanism in Ada for building reusable components. The following example provides a simple implementation of Stacks by means of a generic package with less degree of reusability. Here the size and type of stack elements have been considered as generic formal parameters to allow the user to define for the different situations.

generic

Size : in positive;

type Item is private;

package Stack_Abstraction is

procedure Push( E : in Item);

procedure Pop ( E : out Item);

Overflow, Underflow : exception;

end Stack_Abstraction;

Alternatively, we could design this component for strong reusability by defining Abstract data types, and private types.

generic

Size : in positive;

type Item is private;

package Stack_Abstraction is

type Stack is limited private;

procedure Push( Elem : in Item; St : in out Stack );

procedure Pop ( St : in out Stack );

Overflow, Underflow : exception;

private

-----------

end Stack_Abstraction;

Guideline1 : Define ADT, declare as private for all generic types which appear

in the generic declaration part. Refer section 1.8.4 for more discussion on the private types selection.

Guideline2 : Generic packages can be instantiated by providing actual parameters as shown below.

Guideline3 : Import abstractions via generic formal parameters in order to provide the reuser with maximum flexibility.

Package Stack_Integer is new Stack_Abstraction ( Size => 200,

Item => Integer );