[comp.lang.ada] Exceptions vs. if-then-else

diederich_r_%ncsd.dnet@GTE.COM (Ray Diederich (301)-294-8400) (03/22/91)

In article <jls.669368339@rutabaga> jls@rutabaga.Rational.COM (Jim Showalter) writes:
>>procedure pop(s: stack)
>>begin
>>   if(not empty(s)) then
>>      -- pop the stack
>>   else
>>      raise underflow
     end if;
>>end pop;
>
>>procedure pop(s: stack)
>>begin
>>   stack.top := stack.top - 1;
>>   exception
>>      when Constraint_Error => raise underflow
>>end pop;

[stuff deleted]

> Not only is it faster, it is safer, since
> without using tasks you cannot guarantee that between the time you
> checked and the time you popped it hadn't been popped elsewhere.
(I assume the statement is meant to read "... safer, since _when_ using
tasks ..." rather than "... safer, since _without_ using tasks ...".)

I don't know of any machine nor compiler which guarrantees that an Ada
statement is non-interruptible. Some machines don't even guarrantee that
a decrement memory location machine instruction is atomic. I see little
difference in the degree of safety here; certainly not enough to sacrifice
the clarity of the first example.

Ray Diederich

GTE Government Systems Corporation
Strategic Electronic Defense Division
National Center Systems Directorate
(Yup, that's GTE, alias monolithic corporation)
========================================
The opinions expressed here are not necessarily those of my employer, my
country, my family, or even myself.
========================================

jls@rutabaga.Rational.COM (Jim Showalter) (03/26/91)

>I don't know of any machine nor compiler which guarrantees that an Ada
>statement is non-interruptible. Some machines don't even guarantee that
>a decrement memory location machine instruction is atomic.

Mea culpa--my apologies to the N people who beat me about the
head and shoulders for this one. Yes, absolutely right--statements
are not necessarily atomic. I obviously need to get more sleep!

So, my argument in favor of the exception version of the Pop operation
comes down to this: I think you should use exceptions whenever they
are not part of the NORMAL flow of control. Of course, this is an
inherently subjective criterion, but ask yourself this--is it NORMAL
for a client to Pop an empty stack? I think not, so I think writing
Pop without a pre-check is fine.

--
***** DISCLAIMER: The opinions expressed herein are my own. Duh. Like you'd
ever be able to find a company (or, for that matter, very many people) with
opinions like mine. 
              -- "When I want your opinion, I'll read it in your entrails."