I\'m working on a class which sends a RequestDTO to a Web Service. I need to validate the request before it is sent.
The request can be sent from 3 different places and
An easy way is to promote the check into a separate method:
private String getAppendString(String value, String appendString) {
if (value == null || value.isEmpty()) {
return "";
}
return appendString;
}
And then you can use this method instead of the if
blocks:
sb.append(getAppendString(request.getStreet(), "street,");
This will reduce complexity from 28 down to 3. Always remember: high complexity counts are an indication that a method is trying to do too much. Complexity can be dealt with by dividing the problem into smaller pieces, like we did here.
Another approach would be to enforce that contract in the Request object itself. If a field is required or can't be null, say so when the Request is created.
Create the Request in such a way that it's 100% valid and ready to go when the constructor exists.
I'd also create that String version in the Request toString() method. It should know how to render itself.