[ScopedValue] best way to conditionally bind a value ?
Alan Bateman
alan.bateman at oracle.com
Thu Jul 31 06:16:42 UTC 2025
On 30/07/2025 19:16, Benoit LEFEVRE -CAMPUS- wrote:
> Hello
>
> After using the ScopedValue for a few days, I'm wondering if there
> is a better way to conditionally bind a value than doing the
> following :
>
>
> public static final ScopedValue< Locale > ACCEPT_LANGUAGE =
> ScopedValue.newInstance();
> public static final ScopedValue< String > USER_ID =
> ScopedValue.newInstance();
>
> final Locale acceptLanguage = getAcceptLanguageFromHeader(
> httpRequest );
>
>
> if( acceptLanguage == null ) {
> ScopedValue
> .where( USER_ID, uid )
> .call( MyClass::myStaticCallableMethod );
> } else {
> ScopedValue
> .where( USER_ID, uid )
> .where( ACCEPT_LANGUAGE, acceptLanguage )
> .call( MyClass::myStaticCallableMethod );
> }
>
>
> The point for me of doing so, instead of simply setting a null
> acceptLanguage, is to have a more readable code afterward :
>
>
> private String myStaticCallableMethod() {
> final Local localToUse = ACCEPT_LANGUAGE.orElse(
> A_DEFAULT_LOCAL );
>
>
> ...
> }
>
>
> What is your advise about it ?
>
If the user ID and accept language were (explicit) method parameters
then you might write:
if (acceptLanguage == null) {
MyClass.myStaticCallableMethod(uid);
} else {
MyClass.myStaticCallableMethod(uid, acceptLanguage);
}
With implicit method parameters you've got the same if-then-else so I
don't think it is terrible.
Is there any reason why the caller can't bind ACCEPT_LANGUAGE to
A_DEFAULT_LOCALE so that the callee doesn't need to handle it? That
would change the usage to:
ScopedValue
.where(USER_ID, uid)
.where(ACCEPT_LANGUAGE, (acceptLanguage != null) ? acceptLanguage :
A_DEFAULT_LOCALE)
.call(...);
It would then be a bug f myStaticCallableMethod were called without
bindings for either.
-Alan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/loom-dev/attachments/20250731/a6494e49/attachment-0001.htm>
More information about the loom-dev
mailing list