RFE: Refactor java.util.Optional and add NonNull checks

Roger Riggs roger.riggs at oracle.com
Wed Aug 23 18:41:01 UTC 2023


Hi,

Also, Null checks in the VM are very cheap, likely cheaper than a 
virtual dispatch.
Adding calls to requireNonNull is almost always a no-op, except for 
adding a variable name to the exception it still throws NPE. A 
frequently used class like Optional will be compiled to machine code and 
the number of byte codes is not an important metric.

Regardless, Project Valhalla will be converting and optimizing Optional 
to a value class as the project matures.

Thanks, Roger


On 8/23/23 11:56 AM, Remi Forax wrote:
> Sorry, you can not do that.
> Optional is a value based class [1] (see the javadoc) so the class has 
> to be final.
>
> And more generally, the API of a classes of OpenJDK will not change 
> based on some stylistic issue, OOP or not.
>
> regards,
> Rémi Forax
>
> [1] 
> https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/lang/doc-files/ValueBased.html
>
>
> ------------------------------------------------------------------------
>
>     *From: *"Oleksii Kucheruk" <iselo+openjdk at raccoons.co>
>     *To: *"core-libs-dev" <core-libs-dev at openjdk.org>
>     *Sent: *Wednesday, August 23, 2023 4:43:17 PM
>     *Subject: *RFE: Refactor java.util.Optional and add NonNull checks
>
>     Hi there.
>     I have found that `java.util.Optional` is written procedural style
>     and has `ifnonnull`  checks in each method. I propose to refactor
>     `Optional` in accordance to OOP-style. This will eliminates all
>     unnecessary `if`-statements, removes duplications and reduces
>     bytecode size more then twice.
>
>     I have two solutions:
>     1. Completely dynamic that avoids single static `EMPTY` instance
>     and unchecked casting of each `Optional.empty()`
>     2. Preserving original single static `EMPTY` per VM.
>
>     Also there are couple methods that throws NPE due to calling
>     methods on null-objects and requires to add
>     `Objects.requireNonNull(...)`.
>
>     OptionalInt, OptionalDouble, OptionalLong could be refactored same
>     way even with remove of additional boolean variable `isPresent`.
>
>     Since I'm new here any guidance will be helpful.
>     Thank you in advance.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/core-libs-dev/attachments/20230823/5d797fa4/attachment-0001.htm>


More information about the core-libs-dev mailing list