Ada 95 Quality and Style Guide | Chapter 5 |
5.4.1 Discriminated Recordsguideline
When declaring a discriminant, use as constrained a subtype as possible (i.e., subtype with as specific a range constraint as possible).
Use a discriminated record rather than a constrained array to represent an array whose actual values are unconstrained. example
An object of type Name_Holder_1 could potentially hold a string whose length is Natural'Last:
type Number_List is array (Integer range <>) of Integer; type Number_Holder_1 (Current_Length : Natural := 0) is record Numbers : Number_List (1 .. Current_Length); end record;An object of type Name_Holder_2 imposes a more reasonable restriction on the length of its string component:
type Number_List is array (Integer range <>) of Integer; subtype Max_Numbers is Natural range 0 .. 42; type Number_Holder_2 (Current_Length : Max_Numbers := 0) is record Numbers : Number_List (1 .. Current_Length); end record;rationale
When you use the discriminant to constrain an array inside a discriminated record, the larger the range of values the discriminant can assume, the more space an object of the type might require. Although your program may compile and link, it will fail at execution when the run-time system is unable to create an object of the potential size required.
The discriminated record captures the intent of an array whose bounds may vary at run-time. A simple constrained array definition (e.g., type Number_List is array (1 .. 42) of Integer;) does not capture the intent that there are at most 42 possible numbers in the list.
< Previous Page | Search | Contents | Index | Next Page > |
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
TOC | TOC | TOC | TOC | TOC | TOC | TOC | TOC | TOC | TOC | TOC |
Appendix | References | Bibliography |