Output Parameters in Java

后端 未结 8 887
夕颜
夕颜 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 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.

提交回复
热议问题