Java – what is the best way to test this? Binary number with 4 positions
Consider the four input fields a, B, C and D on the web surface. Users can fill in any of these There are 16 combinations of how to fill these fields Allowed are:
A B C D ------- 1 0 0 0 1 1 0 0 1 1 1 0 1 1 1 1
Where 1 means not null and 0 means null
I'm using JSF's MVC mode I don't want the logic in the view, but in the controller What is the best way to check this in Java?
So far, I have implemented two solutions
Solution 1:
@Override public boolean isInputInvalid(Integer a,Integer b,Integer c,Integer d) { if (isNotSet(a) && isNotSet(b) && isNotSet(c) && isNotSet(d) { return true; } return (firstParameterDoesNotExistAndSecondDoesExist(a,b)) || (firstParameterDoesNotExistAndSecondDoesExist(b,c)) || (firstParameterDoesNotExistAndSecondDoesExist(c,d)); } private boolean firstParameterDoesNotExistAndSecondDoesExist(Integer firstParameter,Integer secondParameter) { return isNotSet(firstParameter) && !isNotSet(secondParameter); } private boolean isNotSet(Integer parameter) { return parameter == null; }
Solution 2:
public boolean isInputValid(Integer a,Integer d) { if (exists(a) && !exists(b) && !exists(c) && !exists(d) || // exists(a) && exists(b) && !exists(c) && !exists(d) || // exists(a) && exists(b) && exists(c) && !exists(d) || // exists(a) && exists(b) && exists(c) && exists(d)) { return true; } return false; } private boolean exists(Integer level) { return level != null; }
be careful:
The first method checks whether the input is invalid, and the second method checks whether the input is valid (pay attention to the name of the method)
I wrote 16 unit test cases, and both versions run green
Do you have any tips / Tricks / tips on how to make your code more readable?
Solution
If you only care about readability:
public static List<String> validOptions = Arrays.asList("1000","1100","1110","1111"); public boolean isValid(Integer a,Integer d) { StringBuilder sb = new StringBuilder(); sb.append(a==null ? 0 : 1); sb.append(b==null ? 0 : 1),sb.append(c==null ? 0 : 1); sb.append(d==null ? 0 : 1); return validOptions.contains(sb.toString()); }
Note that this is not the fastest or cleanest solution (wasting some CPU and memory)