Alex Len
Alex Len

Reputation: 43

Is there a way to avoid this duplication?

I have a pretty simple method here:

    private String claimAsString(
        JWTClaimsSet claims,
        String claimName,
        String fallbackClaimName)
    {
        Object claim = claims.getClaim(claimName);
        if (claim != null)
        {
            return (String) claim;
        }

        Object fallbackClaim = claims.getClaim(fallbackClaimName);
        if (fallbackClaim != null)
        {
            return (String) fallbackClaim;
        }
        return null;
    }

Basically to get a claim from a JWT claimset, and if it doesn't exist, get the fallback value. But it looks like the 2 blocks of the code are too similar... just wondering if there is a better way to re-write this to be a bit cleaner.

Upvotes: 0

Views: 254

Answers (3)

Henry Twist
Henry Twist

Reputation: 5980

You could do something like this if you're a fan of one-liners:

Object claim = claims.getStringClaim(claimName);
return (String) (claim == null ? claims.getStringClaim(fallbackClaimName) : claim);

However you might want to consider changing your claimAsString method to have an Optional return type. Then you could do:

Optional<String> claimAsString(JWTClaimsSet claims, String claimName, String fallbackClaimName) {
    
    return Optional.ofNullable((String) claims.get(claimName))
            .or(() -> Optional.ofNullable((String) claims.get(fallbackClaimName)));
}

Upvotes: 5

k314159
k314159

Reputation: 11062

If you're using Java 8, you could do the whole thing in one line (or two if you prefer):

return (String) Optional.ofNullable(claims.getClaim(claimName))
    .orElseGet(() -> claims.getClaim(fallbackClaimName));

If you're using an older compiler, as a general technique you can iterate through the two search strings:

private String claimAsString(
    JWTClaimsSet claims,
    String claimName,
    String fallbackClaimName)
{
    for (String searchedClaim : new String[] {claimName, fallbackClaimName}) {
        Object claim = claims.getClaim(searchedClaim);
        if (claim != null) {
            return (String) claim;
        }
    }
    return null;
}

Upvotes: 1

Fussel
Fussel

Reputation: 1865

Not quite sure if I found the correct docs for the class you are using but you could try it like this. getClaim or getStringClaim return null if no value is found, so you do not need the null check there.

private String claimAsString(
    JWTClaimsSet claims,
    String claimName,
    String fallbackClaimName)
{
    String claim = claims.getStringClaim(claimName);
    if (claim != null){
        return claim;
    }
    return claims.getStringClaim(fallbackClaimName);
}

Upvotes: 1

Related Questions