Call by Result

G

Gene Wirchenko

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.

Sincerely,

Gene Wirchenko
 
A

Andreas Leitgeb

Gene Wirchenko said:
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's three basic ways to do it:

1) Return null to indicate failure. (Unless you consider null to
also be a valid String-value - That typically depends on the
context and I didn't read your wording as being explicit on that.)
String retVal = getString();
if (retVal == null) { /* too bad */ }
This won't work, though, if you need to return a String both
on failure and success.

2) instead of the string, pass a mutable container of a string:
String[] stringContainer = new String[1];
boolean didItWork = getString(stringContainer);
if (didItWork) { /* stringContainer[0] has the string */ }

and within GetString:
public boolean getString(String[] strCont) {
strCont[0] = "blah"; return true;
}

3) encode the String: e.g.: prepend a particular text to "success"-
strings, and a different text to "failure"-strings:

public String getString(String[] strCont) {
if (ok()) { return "+" + okMessage; }
else { return "-" + errMessage; }
}
use:
String retVal = getString();
if (retVal == null || retVal.length() == 0) { /* internal error */ } else
if ( retVal[0] == '+' ) {
// All's well that ends well: retVal.subString(1)
} else if ( retVal[0] == '-' ) {
// Uh-Oh!: retVal.subString(1)
} else { /* internal error */ }


PS: Surely, someone will soon point out coding-conventions about
upper-/lower-casing different kinds of identifiers. I dare to agree
in advance. (Btw., I changed to conformant casing in my examples.)
 
N

Nigel Wade

There's three basic ways to do it:

1) Return null to indicate failure.

2) instead of the string, pass a mutable container of a string:

3) encode the String: e.g.: prepend a particular text to "success"-

Are 1) and 3) not precluded by the proviso "It is not acceptable to have
a special String value mean failure".

A fourth way would be to return a class/object containing both the
boolean and the String. To me, this would be the natural OO way of
returning more information than a primitive type.

And a 5th way could be to return the String and throw an Exception if it
did not work. Some purists may argue that failure to work is not
strictly an exception, but if it gets the job done...
 
A

Andreas Leitgeb

Nigel Wade said:
Are 1) and 3) not precluded by the proviso "It is not acceptable to have
a special String value mean failure".

It is conceivable that "1)" might be, but (in my understanding) not implied.
It boils down to whether one considers null to be a String value. If you
think "of course", then so be it. I don't really care.

"3)" is rather not, because it is just a different way of implementing
your "4)" below. (Although it might take some more fuss to also encode
possible nulls for success and failure into the return string, if at all
needed.) Both the boolean and the original string value can be safely
extracted from the encoded string. I'm speaking of "String values" here,
such as identified by .equals(), not of String instances, though. So, if
the latter has to be preserved, too, then "3)" would indeed be ruled out.
A fourth way would be to return a class/object containing both the
boolean and the String. To me, this would be the natural OO way of
returning more information than a primitive type.

And a 5th way could be to return the String and throw an Exception if it
did not work. Some purists may argue that failure to work is not
strictly an exception, but if it gets the job done...

"4)" and "5)" are both very good ideas, both nicer/cleaner than mine, and
I'm a bit embarrassed for not having thought of them, myself. (Well, at
least, mine are a bit shorter to implement ;-)
"5)" has also been suggested by Patricia.
 
A

Arved Sandstrom

Are 1) and 3) not precluded by the proviso "It is not acceptable to have
a special String value mean failure".

A fourth way would be to return a class/object containing both the
boolean and the String. To me, this would be the natural OO way of
returning more information than a primitive type.

And a 5th way could be to return the String and throw an Exception if it
did not work. Some purists may argue that failure to work is not
strictly an exception, but if it gets the job done...
This is the kind of thing where "purists" will get a bit bloody. Not to
teach you or any other respondent here how to suck eggs, but I'll throw
in, for general edification of a wider audience, the information that
we've got this problem both because Java has "pass object reference by
value" and Strings are immutable. Hence the OP's question.

Given that, Andreas' #2 is legit (I agree, Nigel, with your concerns
regarding #1 and #3), and so are the two suggestions you and Patricia
have put forth.

I'll accept that returning an object containing both the possible
modified String and a boolean status is OK. I don't much like it,
however, for two reasons. It's still the use of a return value for
operation status, and although that's defensible, there's nothing OO
about it - it's pure imperative programming. And were we to still pursue
that approach, unfortunately Java has no elegant means for supporting
it, unlike Haskell Maybe or Scala Option.

The failure of Java to cleanly support the previous approach pretty much
argues, IMHO, for exceptions. And this is, again IMHO, quite pure. It's
basically my business to define what I consider to be failures and
errors. Myself I see absolutely no problem in arguing that a failure to
work (parse) is a failure. :) It's certainly an error in the input to
be parsed. In any case the OP would hardly be asking for an operation
success status if it wasn't possible for the method to fail.

Another argument for exceptions here is the OP's

if (!DidItWork)
// too bad

bit. I have my doubts as to whether the OP's intended error processing
consists just of a NOOP and a comment. Assuming that it doesn't, and one
actually wants to do something productive in the error-handling,
exceptions are the best way to do it.

AHS
 
E

Eric Sosman

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

Andreas Leitgeb

Arved Sandstrom said:
I'll accept that returning an object containing both the possible
modified String and a boolean status is OK. I don't much like it,

Why would such a returned object contain a possibly *modified* String?
It would expectably contain whatever String the method getString wants
the caller to see. It doesn't get one from outside in this case (as
opposed to my #2 case), so there's nothing to "modify".
however, for two reasons. It's still the use of a return value for
operation status, and although that's defensible, there's nothing OO
about it - it's pure imperative programming. And were we to still pursue
that approach, unfortunately Java has no elegant means for supporting
it, unlike Haskell Maybe or Scala Option.

Not sure, what feature you're principially talking of. Is it some kind of
syntactic sugar to further simplify code like this:

BoolStr bs = getString();
boolean b=bs.bool; String s=bs.str;

?
(just curious)
 
S

Silvio

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.

Sincerely,

Gene Wirchenko

This is a perfect case for the Scala Option and the Haskell Maybe construct.

You could Google for them and create such a beast in Java yourself. It
would be a good replacement for most places where you now use null...

Silvio
 
S

Stefan Ram

Gene Wirchenko said:
I wish to call by result with a method.

I am surprised about all the answers, whose authors seems
to have understood what Gene wanted to convey with this.

I never have heard »call by result«.

But I was able to look it up in an online encyclopedia:

»When the reference is passed to the callee
uninitialized, this evaluation strategy may
be called "call by result".«

http://en.wikipedia.org/wiki/Evaluation_strategy

Did you all knew this before you answered? The reference
has to be /uninitialized/ for an evaluation strategy to be
called "call by result"!
String ReturnString="";
boolean DidItWork=GetString(ReturnString);

But in Java we cannot pass uninitialized references!
Especially, in this case, the reference is not uninitialized.
So how could a call by result be possible in Java without
the means to pass uninitialized references?

Also, »call by result« is a special case of
»call by copy-restore«, (see the above URI),
which I do not understand. But I am not sure whether even
this »call by copy-restore« is possible in Java, since its
descriptions refers to acts of leaving some results
undefined (which is possible in Perl, but not in Java).
 
A

Andreas Leitgeb

Stefan Ram said:
I am surprised about all the answers, whose authors seems
to have understood what Gene wanted to convey with this.

Ok, I admit, I was a bit confused, too, at first, but
the example was good at clarifying what the OP meant.
 
S

Stefan Ram

Peter Duniho said:
That is, it seems more likely that what the OP cares about is
the "modify the argument, return a boolean" aspect more than
he cares about the "was the argument initialized" aspect.

Ok, the OP contained:

For my taste, the object-oriented way to do this is:

final Getter getter = new Getter();
getter.get();
if( getter.isValid() )result = getter.value(); else ...

, while the Java way to do this is

try{ s = getString(); }
catch( final Exception exception )...

. The OP used upper-case names of variables and methods,
so he might be a beginner in Java, in which case it might be
more appropriate for him to learn how things are natively
done in Java than to learn how to emulate features of other
languages (such as call by result) in Java.
 
S

Stefan Ram

»When the reference is passed to the callee
uninitialized, this evaluation strategy may
be called "call by result".«
http://en.wikipedia.org/wiki/Evaluation_strategy

Ok, the Wikipedia possibly might be wrong or misleading here.
What it means according to another source is that

- for each »out parameter«, uninitialized space is
reserved in the activation record /of the callee/,

- then the callee writes to that space, and finally,

- the value in that space is copied to the corresponding
»out argument« variable.

However, it might be a further optimization, that the caller
also is allowed to pass an uninitialized »out variable«.
 
M

markspace

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.


I'm kind of surprised by all the answers here also. I'm glad Stefan
pointed out the definition of "call by result," which I also did not know.

However call-by-result is just a use case of pass-by-reference, so why
not use that? In Java the standard quicky semantic is to use an array.

String[] returnString = new String[1]; // just 1 return string
boolean didItWork = GetString( returnString );
if( didItWork ) {
String result = returnString[0];
.... process result here
} else {
.... too bad
}

returnString is just a holder, as was mentioned earlier, but temporary
arrays are often used for pass by reference in Java (which only has pass
by value), so any programmer is likely to grasp what is going on here
quickly.
 
R

RedGrittyBrick

Dear Java'ers:

I wish to call by result with a method. Is it possible?

No, strings are immutable, so GetString() cannot alter the value of
ReturnString.

If not, can it be easily simulated in an unnasty way?

I believe it is better to use a Java pattern which other Java
programmers will be familiar with.

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.

I think Stephan Ram's answer is roughly what I would do.

String returnString;
Thagomizor thangomizor = new Thagomizor();
thangomizor.thangomize();
if (!thangomizor.didItWork()) {
throw new TooBadException();
} else {
returnString = thangomizor.getString();
}
 
M

Martin Gregorie

I think Stephan Ram's answer is roughly what I would do.

String returnString;
Thagomizor thangomizor = new Thagomizor(); thangomizor.thangomize();
if (!thangomizor.didItWork()) {
throw new TooBadException();
} else {
returnString = thangomizor.getString();
}

Likewise, this is my usual style too, though its quite possibly a carry-
over from the way I write C.
 
G

Gene Wirchenko

There's three basic ways to do it:
2) instead of the string, pass a mutable container of a string:
String[] stringContainer = new String[1];
boolean didItWork = getString(stringContainer);
if (didItWork) { /* stringContainer[0] has the string */ }

and within GetString:
public boolean getString(String[] strCont) {
strCont[0] = "blah"; return true;
}

This is a kludge but fairly simple. I did a bit more looking and
found
http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html
where a simple class is created. I ended up with

***** Start of Code *****
// Parameters.java
// Experimenting with Parameters
// Last Modification: 2011-06-10



class StringValue
{
String Value;
}

class IntValue
{
int Value;
}



public class Parameters
{

public static void main
(
String[] args
)

{
IntValue a=new IntValue();
IntValue b=new IntValue();
StringValue RetVal=new StringValue();

a.Value=1;
b.Value=2;

System.out.println(
"a="+a.Value+", b="+b.Value+", RetVal="+RetVal.Value);

ChangeValues(a,b,RetVal);

System.out.println(
"a="+a.Value+", b="+b.Value+", RetVal="+RetVal.Value);
}

public static void ChangeValues
(
IntValue First,
IntValue Second,
StringValue ReturnValue
)

{
First.Value*=2;
Second.Value++;
ReturnValue.Value="change";
}

}
***** End of Code *****

[snip]

PS: Surely, someone will soon point out coding-conventions about
upper-/lower-casing different kinds of identifiers. I dare to agree
in advance. (Btw., I changed to conformant casing in my examples.)

I have used a number of languages. One of the things that I
dislike about Java is the small letter first style. It is
particularly bothersome, because my variable naming convention often
has HN-like prefixes. When I use a prefix, the main part of the name
is initial-capitalised; prefixes are not capitalised. For example,
"fhIn" is file handle for In.

Sincerely,

Gene Wirchenko
 
G

Gene Wirchenko

On Fri, 10 Jun 2011 08:23:17 -0300, Arved Sandstrom

[snip]
This is the kind of thing where "purists" will get a bit bloody. Not to

Let them scream. I have other comments elsethread. In short, if
your favourite way of doing things causes me a bunch of extra work to
use, I am liable to not use it.
teach you or any other respondent here how to suck eggs, but I'll throw
in, for general edification of a wider audience, the information that
we've got this problem both because Java has "pass object reference by
value" and Strings are immutable. Hence the OP's question.

Nope. I simply want to call by result.
Given that, Andreas' #2 is legit (I agree, Nigel, with your concerns
regarding #1 and #3), and so are the two suggestions you and Patricia
have put forth.

I based my answer on #2.
I'll accept that returning an object containing both the possible
modified String and a boolean status is OK. I don't much like it,
however, for two reasons. It's still the use of a return value for
operation status, and although that's defensible, there's nothing OO
about it - it's pure imperative programming. And were we to still pursue
that approach, unfortunately Java has no elegant means for supporting
it, unlike Haskell Maybe or Scala Option.

Well, imperative programming does exist, and I use it.
The failure of Java to cleanly support the previous approach pretty much
argues, IMHO, for exceptions. And this is, again IMHO, quite pure. It's

Nope. Too complicated.
basically my business to define what I consider to be failures and
errors. Myself I see absolutely no problem in arguing that a failure to
work (parse) is a failure. :) It's certainly an error in the input to
be parsed. In any case the OP would hardly be asking for an operation
success status if it wasn't possible for the method to fail.

Another argument for exceptions here is the OP's

if (!DidItWork)
// too bad

bit. I have my doubts as to whether the OP's intended error processing
consists just of a NOOP and a comment. Assuming that it doesn't, and one
actually wants to do something productive in the error-handling,
exceptions are the best way to do it.

Get real! It is common in examples to have a comment indicating
what would be done when said code is not particularly relevant to the
example.

Sincerely,

Gene Wirchenko
 
A

Arved Sandstrom

Why would such a returned object contain a possibly *modified* String?
It would expectably contain whatever String the method getString wants
the caller to see. It doesn't get one from outside in this case (as
opposed to my #2 case), so there's nothing to "modify".

Sorry, my brain disconnected from my fingertips for a few seconds there.
Not "possible modified" String, but just result String. You're quite right.
Not sure, what feature you're principially talking of. Is it some kind of
syntactic sugar to further simplify code like this:

BoolStr bs = getString();
boolean b=bs.bool; String s=bs.str;

?
(just curious)

Maybe and Option are datatypes that allow you to return either the
requested value or a value that represents a failure of the computation.
This is conceptually different from having a special value, because in
the case of Maybe or Option, if the function/method succeeds, *every*
possible value of the underlying datatype (String or Integer or
whatever) is still a legal successful value. In effect Maybe and Option
are wrapper types just like BoolStr in your example; it's simply that
Scala and Haskell have better language support for dealing with
datatypes of that sort.

Like I said, in Java the "BoolStr" approach wouldn't be *my* preference
- I like exceptions here. But I wouldn't hold my nose if someone decided
to use "BoolStr".

AHS
 
G

Gene Wirchenko

On 6/10/2011 2:03 AM, Nigel Wade wrote:
...
My view of this is that a method should not be called "getString", or
any variation on that theme, unless its primary purpose is to get a
string. In that case, it should return the string it gets. Any failure
to get the string is an exception relative to its purpose.

Its primary purpose is to get a string. Where its result is
returned is not so important. Call by result is compact.
Even when programming in C, I regarded the tendency to return a
success/fail flag and treat the main purpose of the function as a side
effect as an unfortunate but necessary ugliness. In Java, I regard it as
pure ugliness, with no justifying necessity.

It is interesting that the so-called ugliness is much shorter
than the try-catch ugliness. The added verbosity of try-catch does
not add anything to the code.

I think that using exceptions can bloat one's code all to easily.
I like my code's flow of control to read as a story. If there are too
many interruptions, it is difficult to see that story.
Some people seem to confuse making something an exception in a
particular interface with regarding it as a whole program failure. That
makes no sense to me. If there is to be any hope of code reuse, method
interfaces must be designed based solely on the method's intended
function, not the overall program design.

The method's intended function is as a subroutine in imperative
code.

Sincerely,

Gene Wirchenko
 
G

Gene Wirchenko

[snip]
Exceptions provide an alternative. Rather than returning a didItWork
boolean, return the String if it did work, and throw an exception if it
did not work.

if-else does so, too, and is more compact.
In addition to allowing the method to return its primary result, it also
allows for passing back more information in the case of failure, which
can lead to better reporting.

So does call-by-result, and in less space.

Sincerely,

Gene Wirchenko
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top