[comp.lang.ada] Raising exceptions to get out of iterators . . .

KETTERING@SPIKE.llnl.gov (Brett 'Volleyball Is My Game' Kettering) (04/11/90)

	Erland Sommarskog - ENEA Data, Stockholm - sommar@enea.se writes:

> Some years ago . . . rewrite the package so that PROCESS_ONE_ELEMENT should
> take a second parameter, CONTINUE : out BOOLEAN.  The problem with this is
> that if the user in 90% of the time wants to iterate through the entire set,
> this second parameter just clutters up his code . . .

	I don't think this clutters the code at all, it's a single assignment.

> . . . he may even forget to initiate it with interesting.

	The compiler will require at least one assignment to a variable that
	is an 'out' parameter.  This does not ensure that the code follows
	the thread of execution where this assignment occurs, so the code
	may not react as anticipated if there exists a thread of execution
	where an assignment is not made.  That's why programmers are hired.

> So I went for the other solution and simply wrote the invoking procedure as:
>
>   DECLARE
>      done : EXCEPTION;
>      PROCEDURE Test_One_Element (E : IN My_Element_Subtype) is
>      BEGIN
>         -- some stuff
>         IF Found THEN
>            RAISE Done;
>         END IF;
>      END Test_One_Element;
>
>      PROCEDURE Find_First_Element IS NEW
>         My_Set_Package.Process_Each_Element
>            (Process_One_Element => Test_One_Element);
>   BEGIN
>      Find_First_Element (S);
>   EXCEPTION
>      WHEN Done => NULL;
>   END;

	This, of course, assumes that MY_SET_PACKAGE.PROCESS_EACH_ELEMENT does
	not trap this exception and convert it to something else.  Correctly
	the package MY_SET_PACKAGE should export an exception DONE,
	instructing the user to raise it in PROCESS_ONE_ELEMENT if he wishes
	to exit the iterate.  This would then require the procedure
	TEST_ONE_ELEMENT to do a "raise MY_SET_PACKAGE.DONE".

	While this is possible, and I've even done it, I think it is not
	an elegant solution.  I think exceptions are something that the
	package uses to notify the user of a condition, not vice-versa.
	Furthermore, I believe that a simple assignment is much easier
	code to generate and faster than the handling of an exception.
	Finally, the inclusion of the CONTINUE parameter makes it very
	obvious to the user how to stop the iteration and its use is
	virtually self-explanatory.

Brett Kettering		KETTERING%SPIKE@ICDC.llnl.gov