Search code examples
javaprimitive-typesjedisboxinglettuce

Advantage of returning boxed primitive values from library function


Context

I am looking at a couple of Java Redis clients like Lettuce and Jedis. I see that both libraries have defined their methods to return boxed primitive types rather than straight primitives.

For example, sadd() returns Long rather than just long. https://lettuce.io/lettuce-4/release/api/com/lambdaworks/redis/api/sync/RedisSetCommands.html#sadd-K-V...-
and
https://github.com/xetorthio/jedis/blob/d7aba13a8b65e66dedc01c51b73e3794cbe68a62/src/main/java/redis/clients/jedis/commands/BinaryJedisCommands.java#L139

Question

What could be the reason for returning boxed primitives?
From what I understand boxing adds performance overhead.

Would it make sense for my library which uses Redis library, to keep and the return values boxed and propagate it to users of the library?

Edit: None of the methods return null, so encoding special meaning to null does not apply to them.


Solution

  • In my opinion the main reason is to ability to retrieve an Object instead of a primitive type. E.g. it's possible to retrieve null.

    Numeric wrappers like Integer, Long... are cached values between around -128; +127. All other values will be duplicated in memory. Moreover to store Long it takes over 3 times more space than store long.

    In general case I following following rule. If you do not need to return null you should prefer to return a primitive value than numeric wrapper.