HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Looking up a hostname for a given path and client ID

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pathlookingclientforhostnameandgiven

Problem

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> 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.

Solution

Just don't duplicate it:

Map 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 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);
}

Code Snippets

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

// log error here
return null;
private Integer getLocalId(String path, int clientId)
{
    Map<Integer, Integer> intermediate = mapping.get(path);
    if (intermediate != null) {
        return intermediate.get(clientId);
    }
    return null;
}
private String getAddress(final String path, final int clientId) {
    Integer localId = getLocalId(path, clientId);
    if (localId == null) {
        // error
        return null;
    }

    return getHostname(path, localId);
}

Context

StackExchange Code Review Q#114332, answer score: 7

Revisions (0)

No revisions yet.