I have a function and Technical Leader review code and said : Why this if statement? It's basically the same message. If you want customized, use a string builder with the type. How to change it , can someone help me?
private Optional<String> validatePrimaryPath(SalesChannelType salesChannelCode, List<String> primaryPathList) {
if (CollectionUtils.isEmpty(primaryPathList)) {
if (salesChannelCode.equals(SalesChannelType.HEB_TO_YOU)) {
return Optional.of("Customer Hierarchy is mandatory field for HebToYou.");
} else {
return Optional.of("Customer Hierarchy is mandatory field.");
}
}
return Optional.empty();
}
To prevent writing the same (partial) string literal multiple times, you can:
Use a constant for the common part:
if (CollectionUtils.isEmpty(primaryPathList)) {
final String COMMON = "Customer Hierarchy is mandatory field";
if (salesChannelCode.equals(SalesChannelType.HEB_TO_YOU)) {
return Optional.of(COMMON + " for HebToYou.");
} else {
return Optional.of(COMMON + ".");
}
}
Build the string using StringBuilder
:
if (CollectionUtils.isEmpty(primaryPathList)) {
StringBuilder buf = new StringBuilder("Customer Hierarchy is mandatory field");
if (salesChannelCode.equals(SalesChannelType.HEB_TO_YOU)) {
buf.append(" for HebToYou");
}
return Optional.of(buf.append('.').toString());
}
Personally, I would keep the code in the question, especially if you ever might need support non-English versions of the text, because in other languages the extra text might not go there.