Forums Register Login

Exception as flow control?

+Pie Number of slices to send: Send
I want to execute certain methods linearly in a way that if any of the methods says the data passed to it is invalid, it should not let methods to be called after it to execute.
For example, my code has following calls:

If validateB() says 'someData' is invalid then validateC() should not execute. What can be a good solution to that? (Probably without using exception as flow control!)
+Pie Number of slices to send: Send
What's the return type of those three methods?
+Pie Number of slices to send: Send
I have, for now, had it to be boolean so that i could make:



This didn't seem a good solution to me!
+Pie Number of slices to send: Send
You could argue that since you're actually checking for errors, using exceptions here is actually appropriate. I might well take that approach.

If you're not convinced by that, then you can avoid deep nesting of methods by taking advantage of the fact that && short-circuits:


Edit: having seen Jesper's post below, I'd just add: I'd use my approach for many validations, or if I thought the number was likely to change. If I was confident there were always going to be a small number, I'd use his.
+Pie Number of slices to send: Send
Or just:

This guarantees that for example validateB() and validateC() will not be called if validateA() returns false, because expressions are evaluated from left to right and && is a short-circuit operator (if the operand on the left is false, it won't evaluate the operand on the right).
+Pie Number of slices to send: Send
 

Ashish Malik wrote:If validateB() says 'someData' is invalid then validateC() should not execute. What can be a good solution to that?


As you can see, there are several possibilities.

One other thing to consider is: are these validations independent? If they are, then all the advice given so far is absolutely correct. If they aren't, you may need to consider writing your methods differently, eg:would imply that your three methods have a hierarchy.

Winston
+Pie Number of slices to send: Send
As all validations are independent i would fallback on



Thanks!
it's a teeny, tiny, wafer thin ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 853 times.
Similar Threads
$.getJSON leaking memory?
setRollbackOnly
throwing exceptions
Idiom => Item 27 from Bloch's book
Art of Java: Ch 13 Control Flow vs. Exception handling
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 08:32:48.