3

The question: Is it considered better practice to use derived types/subtypes or to use conditions and exception-handling to restrict the acceptable inputs for a subprogram in Ada? I understand that in Ada2012 you can use contracts, but what about for previous versions like Ada95?

The context: I want to make a series of procedures which can read/write specific fields in a packet (represented by a private unsigned byte array) to be broadcasted from an embedded device to an ASIC. A lot of the fields are different sizes and don't line up with the byte boundaries, so using standard types would allow a program using these procedures to enter illegal values if unchecked.

Extra notes: Outside of manipulating the packet contents via these subprograms, these types would not be used elsewhere. Also, if it makes a difference, this code would be used in a safety critical system.

3

You should definitely go for subtypes for specifying which subsets of a type are valid for individual operations manipulating a type.

You can also do it using derived types. That makes sense, if you (for example) have a finite number of subsets, and most of your manipulations don't change which subset of the type, a specific entity belongs to.

Generally you can write quite good subtype contracts even in Ada 95. Ada 2012 just added even more fine-grained detail to the contract formalism.

I'm sorry that my answer is a bit abstract, but I hope it helps you get started.

3

The Ada language has historically a strong focus on the type system, with both compile-time and run-time checks that assignments make sense and that variables hold values that are within their valid range.
This history makes me believe -- I can't tell for sure, as I am not an Ada programmer -- that a derived/subtype approach with compiler-generated checks will be vastly preferred over manual checks that the value is within the expected range.

Apart from the Ada-specific considerations, it is generally considered better to find problems sooner rather than later. If your compiler (or other build tooling) can show you that you are writing illegal values, then that is preferred over finding it in a test at runtime. The earlier you are notified of the problem, the sooner you can fix it and the less effort it takes to see what needs to be fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.