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!)
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.
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).
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.
Joined: Jul 11, 2010
As all validations are independent i would fallback on