Ada 95 Quality and Style Guide Chapter 8

Chapter 8: Reusability - TOC - 8.2 ROBUSTNESS

8.2.3 Minimizing and Documenting Assumptions


  • Minimize the number of assumptions made by a unit.
  • For assumptions that cannot be avoided, use subtypes or constraints to automatically enforce conformance.
  • For assumptions that cannot be automatically enforced by subtypes, add explicit checks to the code.
  • Document all assumptions.
  • If the code depends upon the implementation of a specific Special Needs Annex for proper operation, document this assumption in the code.

  • example

    The following poorly written function documents but does not check its assumption:

       -- Assumption:  BCD value is less than 4 digits.
       function Binary_To_BCD (Binary_Value : in     Natural)
         return BCD;

    The next example enforces conformance with its assumption, making the checking automatic and the comment unnecessary:

       subtype Binary_Values is Natural range 0 .. 9_999;
       function Binary_To_BCD (Binary_Value : in     Binary_Values)
         return BCD;

    The next example explicitly checks and documents its assumption:

       -- Out_Of_Range raised when BCD value exceeds 4  digits.
       function Binary_To_BCD (Binary_Value : in     Natural)
         return BCD is
          Maximum_Representable : constant Natural := 9_999;
       begin  -- Binary_To_BCD
          if Binary_Value > Maximum_Representable then
             raise Out_Of_Range;
          end if;
       end Binary_To_BCD;


    Any part that is intended to be used again in another program, especially if the other program is likely to be written by other people, should be robust. It should defend itself against misuse by defining its interface to enforce as many assumptions as possible and by adding explicit defensive checks on anything that cannot be enforced by the interface. By documenting dependencies on a Special Needs Annex, you warn the user that he should only reuse the component in a compilation environment that provides the necessary support.


    You can restrict the ranges of values of the inputs by careful selection or construction of the subtypes of the formal parameters. When you do so, the compiler-generated checking code may be more efficient than any checks you might write. Indeed, such checking is part of the intent of the strong typing in the language. This presents a challenge, however, for generic units where the user of your code selects the types of the parameters. Your code must be constructed to deal with any value of any subtype the user may choose to select for an instantiation.

    < Previous Page Search Contents Index Next Page >
    1 2 3 4 5 6 7 8 9 10 11
    Appendix References Bibliography