Re: Call by Result
On 6/10/2011 2:03 AM, Gene Wirchenko wrote:
Dear Java'ers:
I wish to call by result with a method. Is it possible? If not,
can it be easily simulated in an unnasty way?
I am writing a simple preprocessor. I have a few spots where a
string needs to be parsed. I want to call something like this:
String ReturnString="";
boolean DidItWork=GetString(ReturnString);
if (!DidItWork)
// too bad
It is not acceptable to have a special String value mean failure. I
want the method to be able to return any potential string.
There are lots of ways to do what I think you want (the phrase
"call by result" is new to me). One is
class ResultHolder {
String returnString;
// ... other stuff, if desired
};
ResultHolder result = new ResultHolder();
result.returnString = ""; // if desired
boolean didItWork = getString(result);
if (didItWork)
System.out.println("Result is " + result.returnString);
else
System.err.println("Woe is me!");
The same thing, really, in a quick-and-dirty form:
String[] result = new String[1];
boolean didItWork = getString(result);
if (didItWork)
System.out.println("Result is " + result[0]);
else
System.err.println("Woe is me!");
Still another variation is to put the String and the boolean
in the same holder class (I'd be tempted to rename the boolean to
something like isValid).
Of course, there's a completely different approach:
try {
String result = getString();
System.out.println("Result is " + result);
} catch (ItsNoGoodException ex) {
System.err.println("Woe is me!");
}
.... and I'm sure there are possibilities beyond these.
--
Eric Sosman
esosman@ieee-dot-org.invalid