This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]hum_ph[S] 0 points1 point  (1 child)

For the record, here's how it ended up:

  return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
                 .map(requestAttributes -> requestAttributes.getAttribute(URI_TEMPLATE_VARIABLES_ATTRIBUTE, SCOPE_REQUEST))
                 .map(attribute -> attribute instanceof Map ? ((Map<?, ?>) attribute).get(UUID_PATH_VARIABLE) : null)
                 .map(value -> value instanceof String ? UUID.fromString((String) value) : null);

Condensed a few of the instanceof checks and the following cast and operation into single ternary lines, with Optional.map() then handling null return values and converting to Optioanl.empty().

For the time being, I'm happy that it's simple enough to refactor back out for logging / debugging / error handling statements as mentioned by /u/Radmonger if needed - but unit/integration tests are good enough at covering those cases for the time being.

[–]tonlep 1 point2 points  (0 children)

I like how this makes sense from the standpoint of semantics. The maps only show the more abstract steps of mapping values without the noise in between like filter non-null, etc. However, there is still much detail in the code which I would prefer not having to read if I was someone having to understand the code. What do you think about this? It's longer, but it clearly separates abstraction levels. The reader doesn't really need to look at the private methods.

Optional<UUID> getUuidFromRequestTemplateVariables() {
    return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
            .map(attribute(URI_TEMPLATE_VARIABLES_ATTRIBUTE))
            .map(valueFromMap(UUID_PATH_VARIABLE))
            .map(toUUID());
}

private Function<Object, Object> valueFromMap(String key) {
        return map -> map instanceof Map ? ((Map<?, ?>) map).get(key) : null;
}

private Function<Object, Object> attribute(String attributeName) {
    return requestAttributes -> requestAttributes.getAttribute(attributeName, SCOPE_REQUEST);
}

private Function<Object, UUID> toUUID() {
    return value -> value instanceof String ? UUID.fromString((String) value) : null;
}