Naming guard clauses that throw exceptions
https://softwareengineering.stackexchange.com/questions/188310
-
05-11-2019 - |
Question
I have a function evaluate()
that parses a String
for some variables and replaces them with their corresponding value:
public String evaluate() {
String result = templateText;
for (Entry<String, String> entry : variables.entrySet()) {
String regex = "\\$\\{" + entry.getKey() + "\\}";
result = result.replaceAll(regex, entry.getValue());
}
if (result.matches(".*\\$\\{.+\\}.*")) { //<--check if a variable wasn't replaced
throw new MissingValueException();
}
return result;
}
Since the evaluate()
function now does 2 things, it first replaces the variables with the values AND check for any variables that weren't replaced, I thought about refactoring it to:
public String evaluate() {
String result = templateText;
for (Entry<String, String> entry : variables.entrySet()) {
String regex = "\\$\\{" + entry.getKey() + "\\}";
result = result.replaceAll(regex, entry.getValue());
}
checkForMissingValues(result);
}
private void checkForMissingValues(String result) {
if (result.matches(".*\\$\\{.+\\}.*")) {
throw new MissingValueException();
}
}
Now is this a good name for the function checkForMissingValues
? I mean it does check for missing values, but it also throws an exception.
I thought about renaming it to throwExceptionIfMissingValueWasFound()
, but this name tells HOW the function does it more than WHAT the function is doing.
Is there a standard for naming such functions that check for a condition then throw an exception?
No correct solution