Looking up a hostname for a given path and client ID I have this code in my library and I wanted to see whether we can avoid duplicating stuff.

private String getAddress(final String path, final int clientId) {
    if (TestUtils.isEmpty(mapping) || TestUtils.isEmpty(mapping.get(path))  || TestUtils.isEmpty(mapping.get(path).get(clientId))) {
        logger.logError("mapping must not be empty. full path= ", path, ", clientId= ", clientId, ", Mapping= ",
                mapping);
        return null;
    }
    final int localId = mapping.get(path).get(clientId);
    final String hostname = getHostname(path, localId);
    return hostname;
}


Here mapping is defined as,

private final Map&lt;String, Map&lt;Integer, Integer&gt;&gt; mapping;


Is there anything we can improve in the above code? I do see duplicated stuff as I am checking in the if statement and then using same thing just below it.
Just don't duplicate it:

Map&lt;Integer, Integer&gt; intermediate = mapping.get(path);
if (intermediate != null) {
    Integer localId = intermediate.get(clientId);
    if (localId != null) {
        return getHostname(path, localId);
    }
}

// log error here
return null;


Alternatively, you could throw the above into a helper function:

private Integer getLocalId(String path, int clientId)
{
    Map&lt;Integer, Integer&gt; intermediate = mapping.get(path);
    if (intermediate != null) {
        return intermediate.get(clientId);
    }
    return null;
}


And then have just the one check:

private String getAddress(final String path, final int clientId) {
    Integer localId = getLocalId(path, clientId);
    if (localId == null) {
        // error
        return null;
    }

    return getHostname(path, localId);
}