Monday, 29 December 2014

My Enum Frustration

At work, there is a bit of Legacy around.

The following example of several Enum classes we have, is what is currently frustrating me (and I try actively to change them).

Let's enumerate (oh, look, I made a joke) the issues:
Replacing magic numbers with constants and enums is, of course, one of the Good Thingstm.

But in this example, they seem to have totally missed the point.

Not only have they replaced magic numbers with "magic enums", it's an eyesore to use the underscore in the Enum instances.

When you have to take refuge in the use of underscores to make things work, it is a sure sign that you are doing something seriously wrong.

Monday, 22 December 2014

The Terrible Dangers of Autoboxing (Part 3) - Solution

The solution to my previous post regarding the Terrible Dangers of Autoboxing, is written below.

In our case, the type of the second expression is 0L (long) and the third is null but returns from a Long method.

Java assumes that the second and third operands have types that are convertible to numeric types.

In that case, the conditional operator causes binary numeric promotion.2

During binary numeric promotion, it is possible an unboxing is performed3 (on null in our case), which consequently fails with a NullPointerException.

The solution is to replace
return hasSurfaceArea() && getSurfaceInM2() == null ? 0L : getSurfaceInM2();
With:
return hasSurfaceArea() && getSurfaceInM2() == null ? Long.valueOf(0) : getSurfaceInM2();

P.S. Rewriting the conditional expression into an if statement, will also solve it.

Quote

Here is a brilliant quote that every Java programmer needs to remember and understand (especially that last bit):
“Autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it.1

References

[1] Java SE Documentation - Autoboxing
http://docs.oracle.com/javase/7/docs/technotes/guides/language/autoboxing.html
[2] Chapter 15.25 Conditional Operator ? :
Java Language Specification
[3] Chapter 5.6.2 Binary Numeric Promotion
Java Language Specification
Java Tutorials - Autoboxing and Unboxing
http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html