views:

2121

answers:

6

With a third party API I observed the following.

Instead of using,

public static string getString(){
   return "Hello World";
}

it uses something like

public static void getString(String output){

}

and I am getting the "output" string assigned.

I am curious about the reason of implementing such functionality. What are the advantages of using such output parameters?

+6  A: 

Something isn't right in your example.

class Foo {

    public static void main(String[] args) {
        String x = "foo";
        getString(x);
        System.out.println(x);
    }

    public static void getString(String output){
        output = "Hello World"
    }
}

In the above program, the string "foo" will be output, not "Hello World".

Some types are mutable, in which case you can modify an object passed into a function. For immutable types (such as String), you would have to build some sort of wrapper class that you can pass around instead:

class Holder<T> {
    public Holder(T value) {
        this.value = value;
    }
    public T value;
}

Then you can instead pass around the holder:

public static void main(String[] args) {
    String x = "foo";
    Holder<String> h = new Holder(x);
    getString(h);
    System.out.println(h.value);
}

public static void getString(Holder<String> output){
    output.value = "Hello World"
}
Adam Batkin
+1  A: 

This functionality has one big disadvantage - it doesn't work. Function parameters are local to function and assigning to them doesn't have any impact outside the function.
On the other hand

void getString(StringBuilder builder) {
    builder.delete(0, builder.length());
    builder.append("hello world");
}

will work, but I see no advantages of doing this (except when you need to return more than one value).

Tadeusz Kopec
why use a StringBuilder at all?
Carlos Heuberger
Do you ask "what is the use of StringBuilder" or "Why use StringBuilder in this case"? Generally StringBuilder is for fast string building and concatenation (as the name suggests). In this case it is the only way to achieve desired effect (returning string value by modification of function argument). You can't do this with String object as it is immutable.
Tadeusz Kopec
+2  A: 

That example is wrong, Java does not have output parameters.

One thing you could do to emulate this behaviour is:

public void doSomething(String[] output) {
    output[0] = "Hello World!";
}

But IMHO this sucks on multiple levels. :)

If you want a method to return something, make it return it. If you need to return multiple objects, create a container class to put these objects into and return that.

Bombe
A: 

Sometimes this mechanism can avoid creation of a new object.

Example: If an appropriate object exists anyhow, it is faster to pass it to the method and get some field changed.

This is more efficient than creating a new object inside the called method, and returning and assigning its reference (producing garbage that needs to be collected sometime).

Curd
Object creation is cheap and should *not* be the reason to clutter your code with constructs that have no further purpose than to reduce the number of created objects.
Bombe
@Bombe: (1) Even if object creation is cheap, object creation _and_ assigning cannot be cheaper than just assigning (2) It is not only creation that costs; there is also garbage colletion that costs. (3) There are Java evironments where object creation is extremely expensive (Java Card). Here object creation should be avoided whenever possible
Curd
+1  A: 

String are immutable, you cannot use Java's pseudo output parameters with immutable objects.

Also, the scope of output is limited to the getString method. If you change the output variable, the caller won't see a thing.

What you can do, however, is change the state of the parameter. Consider the following example:

void handle(Request r) {
    doStuff(r.getContent());
    r.changeState("foobar");
    r.setHandled();
}

If you have a manager calling multiple handles with a single Request, you can change the state of the Request to allow further processing (by other handlers) on a modified content. The manager could also decide to stop processing.

Advantages:

  • You don't need to return a special object containing the new content and whether the processing should stop. That object would only be used once and creating the object waste memory and processing power.
  • You don't have to create another Request object and let the garbage collector get rid of the now obsolete old reference.
  • In some cases, you can't create a new object. For example, because that object was created using a factory, and you don't have access to it, or because the object had listeners and you don't know how to tell the objects that were listening to the old Request that they should instead listen to the new Request.
Xr
A: 

in my opinion, this is useful when you have more than one result in a function.

davideconsonni
In my opinion, this is a really ugly and bad way to return more than one result. Instead, create a (bean) class that contains the multiple things you need to return, and let the method return an instance of that. Slightly worse: Return an Object[] that contains the multiple things.
Jesper