Java Object vs Primitive – Not Using Long Primitive Due to Default Zero Value

javaobject

Today my college presented to me an argument about not use some primitives that I never heard before. I would like to see what you guys think about it.

We have a class in our project like:

class Order {

    private long id;
    private String name;
    // more fields
}

We have a builder for this class for all the fields.

I always try to use primitive¹ instead of objects to store values, only to evict the possibility of null pointers in the middle of my code, specially as parameters on my methods. You can notice the long primitive in this class too.

But my college said to me that he prefers to use, in this case, the object Long.

His argument: there is a risk to forgot to set the Long value and the default will be 0 (zero), what could bring some problems.

I made the change and not discussed with him about it, because our ids never start with zero, already preventing some mistake about get the wrong Order with zero id.

But I was thinking if there are some another problem that could be prevented not using the primitive in the same line of his logic.

1. I'm aware about the Primitive Obssession. But I don't think that is related of this subject

Best Answer

If you need a representation for "not set", then Long is a good choice, with null standing for "not set". If that isn't needed, don't waste time and space with the unnecessary boxing and unboxing between long and Long.

However you decide to represent "not set", client code has to check for that special value. No way to avoid that.

Using null is a good choice, as client code that forgets that check will not be able to do any nonsense calculations with the value, but fail quickly with a NullPointerException. Exceptions are your friend showing you unmistakably that something went wrong. And it's quite likely that you get a compile-time warning for client code dereferencing a nullable reference.

Whatever "not set" representation you choose, make sure that it can't be used for any real work, so never use 0 or -1 for that purpose.

And, as @FrankHileman already pointed out in his comment, make sure that only valid instances come out of your constructor, and can never become invalid (e.g. make them immutable).

Related Topic