Is it safe to use the java out parameter?
I happened to create a mutable class like this:
class Mutable{ private T value;
public Mutable() { this.value = null; }
public Mutable(T value) { this.value = value; }
T get() { return this.value; }
void set(T value) { this.value = value; }
}
And then it's often used in a method like this:
boolean operation(String input, Mutable> dataOut) throws ... { boolean result;
try {
String data = doSomething(input);
result = validate(data);
if (result && dataOut != null) {
Listvalues = Arrays.asList(data.split(", ")); Collections.sort(values);
dataOut.set(new LinkedHashSet(values)); }
} catch(SpecificIgnorableException ex) {
result = false;
logger.debug(ex);
}
return result;
}
...which is just an example, could be any use case, where one would use ref or out parameters in C#, or non-const reference parameters in C++, or pointers to output parameters in C.
First, the same could be done by using an array (with one element) instead of the above custom type. Does it make sense to have this custom type which clearly states mutable, instead of using an implicitly mutable array?
Second, is this pattern bad and code smell in Java? Let's limit to cases where using out parameter would make sense in C#. Should every instance of this kind of Java code be replaced? With what?
First of all, out and ref have nothing to do with each other. An java out parameter in C# is just the only way the language has of returning multiple values from a function, short of creating a new type to use as the return value. Just because it's in the parameter list is only a syntax thing. There's no equivalent in Java.
I think what you've got there is a code smell because it's not really idiomatic Java. In your situation, I would just define a new class to use as a result value.