James Parsons
James Parsons

Reputation: 6057

What is the point of making a subtype without specifying a range in Ada?

In Ada, I have commonly seen something like this:

type Number is new Integer;

What is the point of this? Can't you just be happy with an Integer? I have also seen code such as:

type Small_Number is range 1..5;

This makes sense to me; I can see why this would be useful. But why would you choose to use the former example?

Upvotes: 1

Views: 2133

Answers (3)

Jacob Sparre Andersen
Jacob Sparre Andersen

Reputation: 6611

I agree that

type Number is new Integer;

(which is not a "renaming" of a type) looks like bad style, but there may be a perfectly good reason for it. For example:

  • You want Number to be a distinct type, but with the same range as Integer.
  • You want Number to match the range of an array type with an Integer derived index.

Upvotes: 1

user571138
user571138

Reputation:

More commonly I have seen code like this:

Type Pounds  is new Integer;
Type Euros   is new Integer;
Type Dollars is new Integer;

This means that you are not going to assign your Pounds to Euros to Dollars by accident.

If you want to convert between the two you would need to either do an explicit cast, or write a conversion routine, both of which would take the applicable exchange rate into account.

(Now I think about it further, Float would have been better than Integer for this example!)

Upvotes: 13

paxdiablo
paxdiablo

Reputation: 881463

The point is that Number is a new type, quite distinct from Integer.

That means more control over parameters and such since you cannot use an Integer where a Number is required; this aids with encapsulation.

It's quite plausible that you want to keep this level of control and perhaps plan for the future where you may end up with Number being totally different from Integer.

Upvotes: 6

Related Questions