When a reader starts to read the function code, he should already have a very good idea of what it is does, how it does it, and what problems he might meet. I’m trying to write clean, structured, well-commented code that is easy to understand. And I’m reading Ada Style Guide and some things I didn’t understand well enough, what can i write for optional sections (for exapmle: @Error_Handling, @Pre, @Post).
I want to represent this Function like an example. Using the above guidelines, a standard function header may be derived:
-- ---------------------------------------------------------------------------
-- @Function: Arithmetic_Mean
--
-- @Description:
-- Function to find the mean of a numeric vector. The program should
-- work on a zero-length vector (with an answer of 0.0).
-- @Usage: (opt)
-- @Parameter:
-- +Num: Given array
-- @Return: Averages/Arithmetic mean or zero
-- @Error_Handling: (opt)
-- @Pre: (opt)
-- @Post (opt)
type Mean_Numbers is array (Natural range <>) of Float;
function Arithmetic_Mean (Num : Mean_Numbers) return Float is
Sum : Float := 0.0;
begin
if Num'Length > 0 then
while Num'First <= Num'Last loop
Sum := Sum + Num(Num'First );
end loop;
return Sum / Float (Num'Length);
end if;
return 0.0;
end Arithmetic_Mean;
And here is another example:
-------------------------------------------------------------- ... --
-- @Function: Get_Index
-- @Description:
-- Returns the minimum index of Item in A.
-- @Parameters:
-- +A: the array
-- +Item: element searched for
-- @Return:
-- The minimum index of Item in A.
-- @Pre:
-- true
-- @Post:
-- if exists 1 <= I <= UPPER_BOUND: A(I) = Item then
-- result = min {1 <= k <= UPPER_BOUND | a(j) = item }
-- else
-- result = 0
The
@Preand@Posttags should document your module’s approach to Design by Contract. As you observed, any precondition must be true for successful execution, and any postcondition is a promise to be fulfilled by your code. The@Error_Handlingtag identifies how you deal with violations of the other two.As a concrete example, your implementation of
Arithmetic_Meansilently ignores an empty input array, returning a mean of zero; it propagates any exceptions that are raised. These are the behaviors that should be documented.Several benefits accrue:
See also Introduction to Ada: Design by contracts, which illustrates Ada 2012 support for enforcing contracts. The Rationale for Ada 2012 offers an overview of the topic and related aspects.