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

Using Guava to reduce code complexity (and possibiliy to improve readability) of null check and assign default value

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

Problem

Below is my java code with some complexity,

String input;
double a;

if (null != input && !input.isEmpty()) {
    a = Double.parseDouble(input);
} else {
    a = defaultValue;
}


With Guava, we can compress the code from 5 lines into a 'single' line,

a = Double.parseDouble(
        Objects.firstNonNull(Strings.emptyToNull(input), defaultValue)
    );


The complexity is reduced but readability is getting worst. Any comment on improving readability at the same time reducing complexity?

Solution

This is a 'specialized' task, converting an input string to a double value. Whenever I have micro-tasks like this I try to refactor them in to a method which does things properly.

As far as I am concerned, neither of the above two systems are valid. You should be validating the input value to make sure that, even if it is populated with a value, that the value is meaningful, and the parse succeeds.

So, I would have a function:

private static final double inputToDouble(String input, double defaultval) {
    if (input == null || input.isEmpty()) {
        // clear out the obviusly invalid values
        return defaultval;
    }
    try {
        return Double.parseDouble(input.trim());
    } catch (NumberFormatException nfe) {
        // silently ignore invalid data, and return the default value
        return defaultval;
    }
}


Sure, the above may be a bit more complicated, but, using it is a charm....

a = inputToDouble(input, defaultValue);


Sometimes applications do this sort of thing a lot, and in those cases I centralize these micro-tasks to static classes like:

public final class InputUtils {
    private InputUtils() {
        // nothing
    }

    public static final double inputToDouble(......) {....};

    .....

}


And then you can reference these micro-tasks from many places, perhaps even doing a static import on the class.

Code Snippets

private static final double inputToDouble(String input, double defaultval) {
    if (input == null || input.isEmpty()) {
        // clear out the obviusly invalid values
        return defaultval;
    }
    try {
        return Double.parseDouble(input.trim());
    } catch (NumberFormatException nfe) {
        // silently ignore invalid data, and return the default value
        return defaultval;
    }
}
a = inputToDouble(input, defaultValue);
public final class InputUtils {
    private InputUtils() {
        // nothing
    }

    public static final double inputToDouble(......) {....};

    .....

}

Context

StackExchange Code Review Q#36261, answer score: 4

Revisions (0)

No revisions yet.