aspose file tools*
The moose likes Java in General and the fly likes Exception as flow control? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Exception as flow control?" Watch "Exception as flow control?" New topic
Author

Exception as flow control?

Ashish Malik
Ranch Hand

Joined: Jul 11, 2010
Posts: 50
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!)
Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4658
    
    5

What's the return type of those three methods?


luck, db
There are no new questions, but there may be new answers.
Ashish Malik
Ranch Hand

Joined: Jul 11, 2010
Posts: 50
I have, for now, had it to be boolean so that i could make:



This didn't seem a good solution to me!
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4466
    
    8

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.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14349
    
  22

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).


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8242
    
  23

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
Ashish Malik
Ranch Hand

Joined: Jul 11, 2010
Posts: 50
As all validations are independent i would fallback on



Thanks!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exception as flow control?