From Effective Java - Joshua Bloch
Item 49- Prefer primitive types to boxed primitives
Use primitives in preference to boxed primitives whenever you have choice. Primitive types are simple and faster. If you must use boxed primitives, be careful! Autoboxing reduces the verbosity, but not the danger, of using boxed primitives.
When I need a method that always return a primitive value that is calculate with their parameters, and their parameters could come from a Double object,
I prefer to write the code like:
public double someCalculation(double primitiveDouble, double anotherPrimitiveDouble) {
return primitiveDouble + anotherPrimitiveDouble;
}
instead of :
public double someCalculation(Double doubleObject, double doublePrimitive) {
if (doubleObject!= null) {
return doubleObject+ doublePrimitive;
}
return 0d;
}
In the caller, I do the validation for null and the call of doubleValue()
in the boxed primitive doubleObject
like:
public void someCaller() {
double doublePrimitive = getSomeDoublePrimitive();
Double doubleObject = getSomeDoubleObject();
if (doubleObject != null) {
double result = someCalculation(doubleObject.doubleValue(), doublePrimitive)
}
.....
}
instead of:
public void someCaller() {
double doublePrimitive = getSomeDoublePrimitive();
Double doubleObject = getSomeDoubleObject();
if (doubleObject != null) {
double result = someCalculation(doubleObject, doublePrimitive)
}
.....
}
When I call the method someCalculation(double primitiveDouble, double anotherPrimitiveDouble)
I use the call doubleValue()
in the Double parameter doubleObject
as doubleObject.doubleValue()
to explicitly unbox the double primitive value of doubleObject
.
By this way:
I'm sure that my method get a primitive double and not a Double object.
If the null validation disappears in the caller, I go to be more closer to the place of an eventually NullPointerException in my stack trace.
I believe that I improve readability of my code because I'm more explicit of my intention.
I pass the accurate parameter to the method
someCalculation(double primitiveDouble, double anotherPrimitiveDouble)
that only need primitive types
My Questions:
What are the advantages/disadvantages of using explicit unboxing ?
It is acceptable to use doubleObject.doubleValue()
when I call some method that only accept primitive types parameters as someCalculation(double primitiveDouble, double anotherPrimitiveDouble)
?