Return Value -Java API Design VS. C API

I've used C a lot before and am now using Java. I have an API design question in JAVA. In C, I always use int

as a meaningful return value and put multiple objects (some of which will be modified) in the arguments. eg,

int foo(int x, int y, int *result)
{
     *result=x+y;
     return SUCCESS;
}

      

In Java, passing by reference seems to be undefined and is it useful to put returned objects in an argument? eg,

Class Person{
   ...
}

      

Two APIs:

public Person bar()          // return value is the object 

      

against.

public int bar(Person p)     // return value is passed by reference

      

Also, how about modifying multiple objects in one function? Returning a list may not be graceful.

public int zoo(Person p, Alien x)   // both p and x will be changed

      

EDIT1

This question boils down to two.

1) If we want to change objects in one function, do these objects have to be passed in arguments (as mutable objects)?

2) How does the caller know the return status, return code, or others (like exceptions)?

+3


source to share


2 answers


One of the main differences is that from the very beginning Java had exceptions and exception handling. This means there is no need to return SUCCESS. If it returns at all rather than throwing an exception, it was successful.



Java has no . What he has are pointers. When you call a method of the type public int bar(Person p)

, p

it is a pointer to the object Person

, if it is not null.

+2


source


If you want to return multiple objects, you should probably define a class for the return value. There's a fair chance they are related and are secretly looking for a home to live together anyway. Another option is to use the Pair

(Apache commons lang) or class List

, but this is useless and should be avoided.

You should avoid passing arguments that need to be changed by reference, as the semantics of parameter passing can be different for RPC-type calls, even depending on the container configuration (in other words, you are not guaranteed to get the result returned as an as parameter, it may turn out differently ).



As far as return codes are concerned, you usually don't need them. Throw an exception if there is an error, otherwise it will succeed. If you have different options for success, you may need to return a complex object or object hierarchy. If you are returning some kind of integer status code, it may indicate an anti-pattern.

+1


source







All Articles