-
Bug
-
Resolution: Done
-
Medium
-
Beijing Release
The fetchResult method in ChefAdapterImpl class contains nonexecutable code. Writing simple junit tests has pointed out several bugs in the code and without these changes the if(resultData ==null) conditions are untestable.
In the original code, the first condition if(resultData ==null) never resolves to "true". The reason for this can be found in the behavior of the optString method's documentation:
"Get an optional string associated with a key. It returns an empty string if there is no such key. If the value is not a string and is not null, then it is converted to a string."
The optString method never returns null, only an empty string when no value has been found. This can be fixed by using the two-arg overloaded optString method which returns null as the default value instead of an empty string. This change allows the logic to go inside the other conditions, but unfortunately another bug is unveiled in the nested conditions:
resultData = allNodeData.optJSONObject(attribute).toString();
resultData = allNodeData.optJSONArray(attribute).toString();
The optJSONObject and optJSONArray do in fact return null (unlike the optString method) when no value for a given key exists. But because the toString() method is invoked on a null reference, a NullPointerException will be thrown which is clearly a developer mistake. The proposed new implementation uses lambda expressions and Optional object from java to do the toString() conversion only if a non null value exists, otherwise resultData is assigned null and the next check can be performed.