i have a method which will return an error code(int) and a result(int). If the error code is 0, the result is valid. In c++, this may like:
int method(int& result);
Java calls by reference, so if we change a object in a method, the change is visible by the caller. But, int is not a class, so I could't make is like this in java:
int method(int result);
And Integer and Long are immutable in Java, so change is not visible by the caller if i do it like this:
Integer method(Integer result);
Wrap the result into a Wrapper Class works! But, that's no so simple!
I work with c++ for long and move to java recently, this bother me a lot! could any one provide a solution?
=================================
well, in a conclusion, there are these flowing solutions:
1st and 2nd make my api ugly 3rd and 4th seems not so perfect about 5th, this method is frequantly called so i've to take efficiency into consideration 6th seems match my require most
thanks!
Don't use return codes for errorcodes: use Exceptions; it is what they are for. Just return the actual result.
You can't return more than one integer for your method. What you can do is:
Create a new object with 2 integer fields and let your method return an instance of that object (basically a wrapper);
Make your method return an array of 2 integers (or take it as a parameter);
Make your method return a String variable of the form <int 1>,<int 2>
. You can then use the split() to get the numbers from the string and parse them back to integers.
Make your method throw the exception and return the number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With