Output Parameters in Java

后端 未结 8 838
夕颜
夕颜 2020-12-21 05:36

With a third party API I observed the following.

Instead of using,

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

i

相关标签:
8条回答
  • 2020-12-21 05:55

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

    0 讨论(0)
  • 2020-12-21 06:02

    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.

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-12-21 06:11

    I disagree with Jasper: "In my opinion, this is a really ugly and bad way to return more than one result". In .NET there is a interesting construct that utilize the output parameters:

    bool IDictionary.TryGet(key, out value);
    

    I find it very usefull and elegant. And it is the most convenient way to aks if an item is in collection and return it at the same time. With it you may write:

    object obj;
    if (myList.TryGet(theKey, out obj))
    {
      ... work with the obj;
    }
    

    I constantly scold my developers if I see old-style code like:

    if (myList.Contains(theKey))
    {
      obj = myList.Get(theKey);
    }
    

    You see, it cuts the performance in half. In Java there is no way to differentiate null value of an existing item from non-existance of an item in a Map in one call. Sometimes this is necessary.

    0 讨论(0)
  • 2020-12-21 06:11

    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.
    0 讨论(0)
  • 2020-12-21 06:14

    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"
    }
    
    0 讨论(0)
提交回复
热议问题