So there are 3 things to consider, passing an OptionalInt
, Integer
or int
to a method (or having a property in your class of this type).
Usually passing an Integer
is not the best idea, since you would need to check against null
. Some people actually want that, well mostly for Boolean
as it can denote 3 states - unknown/true/false
- I still don't like it (an enum
is far more suited in this case).
So semantically passing a null
to a method that accepts an Integer
could mean - I don't want this value to be present. But then, the code providing such a method should be responsible to handle this; a better approach is to have overloaded methods that do not take it as input as such - thus making it clear IMO that this parameter is not mandatory to begin with.
OK, so is passing an int
better? Yes, sort of. Think ORM (hibernate) for a second; there are cases when a certain property could be either int
or Integer
- in this case I favor Integer
; mainly because int
has a a default value or zero
- and I would prefer code to fail with a NullPointer
instead of keeping stale values: zero could be a perfectly valid business value, but what if we did not mean to put it as zero
? Of course, this means that the DB and Service Layer needs proper validation, etc - I am not going into these details.
So what about passing a OptionalInt
to a method that previously was accepting an Integer
? You would still have to check for the presence of it (is it null
?), you would still have to check if it is empty or not and take according steps. And that usually means that you want different code paths depending on that parameter - in which case something more descriptive must be passed in. You could still do it, but what if in time, you will need one more condition? OptionalInt
can't handle that, so a major refactoring would need to take place.
But Optional are awesome as return types. If a method returns an Integer
how many times have you checked if it's actually null? On the other hand if a method returns OptionalInt
you have to think what to do in case it is missing, because otherwise you can not retrieve it's value: unless isPresent?
or any other methods like orElse/orElseGet
etc.