adaptTo() should return an Optional

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

adaptTo() should return an Optional

Jörg Hoh-2
Hi,

When working in a more functional style, the null checks for adaptTo() are
not rally nice, and I typically wrap the result of adaptTo() just into an
Optional by my own.

String propValue =
Optional.ofNullable(resource.adaptTo(ValueMap.class)).map(vm ->
vm.get("property").orElse(() -> {return "defaultValue"});

it would be nice if I could write it like this:

String propValue = resource.adaptTo(ValueMap.class).map(vm ->
vm.get("property").orElse(() -> {return "defaultValue")});

It would require an extension to the Adaptable interface, but that could be
implemented as default method, so it's signature would not change.
While I can do that in my code as well, it would be good to have it in the
Adaptable interface as well; it can encourage others to use Optional
instead of explicit Null Checks; and the Null checks are often missing :-(

WDYT?


--
Cheers,
Jörg Hoh,

http://cqdump.wordpress.com
Twitter: @joerghoh
Reply | Threaded
Open this post in threaded view
|

Re: adaptTo() should return an Optional

Carsten Ziegeler
Use resource.getValueMap() :)

Regards
Carsten

Am 12.11.2018 um 14:21 schrieb Jörg Hoh:

> Hi,
>
> When working in a more functional style, the null checks for adaptTo() are
> not rally nice, and I typically wrap the result of adaptTo() just into an
> Optional by my own.
>
> String propValue =
> Optional.ofNullable(resource.adaptTo(ValueMap.class)).map(vm ->
> vm.get("property").orElse(() -> {return "defaultValue"});
>
> it would be nice if I could write it like this:
>
> String propValue = resource.adaptTo(ValueMap.class).map(vm ->
> vm.get("property").orElse(() -> {return "defaultValue")});
>
> It would require an extension to the Adaptable interface, but that could be
> implemented as default method, so it's signature would not change.
> While I can do that in my code as well, it would be good to have it in the
> Adaptable interface as well; it can encourage others to use Optional
> instead of explicit Null Checks; and the Null checks are often missing :-(
>
> WDYT?
>
>

--
Carsten Ziegeler
Adobe Research Switzerland
[hidden email]