Simplify complicated ternary condition

Keywords: java nested ternary-operator


I want to assign value to result as "read_only", "write_only" or "read_write". For that I want to check resourceKey.

 result =  resourceKey.get("read") == null ?
                    Constants.WRITE_ONLY :
                    resourceKey.get("write") == null ?
                            Constants.READ_ONLY :

I want to simplify this ternary condition.


Consider breaking this functionality out into a utility function.

void Thing() {
    // stuff
    var result = GetPermissions(resourceKey);
    // other stuff

static int GetPermissions(resourceKey) {
    if( resourceKey.get("read") == null )
        return Constants.WRITE_ONLY;
    if( resourceKey.get("write") == null )
        return Constants.READ_ONLY;

    return Constants.READ_WRITE;

Check out the code review stack exchange.