Optional used as method argument?

Vitaly Davidovich vitalyd at gmail.com
Fri Oct 2 13:00:03 UTC 2015


Optional really needs value types to be used more widely in these
contexts.  Given a language that doesn't have non-null baked into the type
system or language, the next best thing would be a library solution.  It's
much better to indicate nullability in the parameter type rather than
javadoc; the javadoc should still explain what a null value would imply for
the method, but it's a poor substitute for encoding that fact.

Also, having consumeAValue vs consumeNoValue type of approach doesn't scale
all that well with more than a single nullable parameter.  Unfortunately,
there's no good solution in java at the moment; before someone suggests
using annotations, let me say they're helpful, but just a bandaid.

On Fri, Oct 2, 2015 at 8:49 AM, Roger Riggs <Roger.Riggs at oracle.com> wrote:

> +1
>
> The "no such value" makes me curious about the context.
> The @param tag really should be saying something about the parameter.
>
> The absence of an @throws (or class/package wide spec) documenting the NPE
> for nulls
> would indicate that null is allowed.
>
> Roger
>
>
>
> On 10/2/2015 4:10 AM, Remi Forax wrote:
>
>> Hi Max,
>> yes, It's usually not a good idea,
>> creating an Optional is like a boxing, you create an object (and prey
>> that escape analysis will work),
>> usually null means there is no value so either you have two methods
>> consume, something like consumeAValue(String) and consumeNoValue() or you
>> have one method consumeAValue and you don't call it if there is no value.
>>
>> regards,
>> Rémi
>>
>> ----- Mail original -----
>>
>>> De: "Wang Weijun" <weijun.wang at oracle.com>
>>> À: core-libs-dev at openjdk.java.net
>>> Envoyé: Vendredi 2 Octobre 2015 03:25:43
>>> Objet: Optional used as method argument?
>>>
>>> I hear people saying Optional is usually used as return values. Can I
>>> use it
>>> as an argument, like this?
>>>
>>>    void consume(Optional<String> value)
>>>
>>> This way, I don't need to add spec like "@param value can be null if
>>> there is
>>> no such value".
>>>
>>> Thanks
>>> Max
>>>
>>>
>>>
>



More information about the core-libs-dev mailing list