1. Imagine you have the following:
void Foo::doFoo()
{
if (!isConditionValid())
{
log("doFoo not possible because condition is not valid");
return;
}
if (!isTheOtherConditionValid())
{
log("doFoo not possible because the other condition is not valid");
return;
}
// do Foo actions
}
Is there a better way to format the code? Really often, I have 1,2 or 3 conditions, and I find it really repetitive to have this structure.
2. What if I have the doBar method, that has the exact same conditions, so we would have:
void Foo::doBar()
{
if (!isConditionValid())
{
log("doBar not possible because condition is not valid");
return;
}
if (!isTheOtherConditionValid())
{
log("doBar not possible because the other condition is not valid");
return;
}
// do Bar actions
}
I feel like I should refactor those conditions, but I find it difficult to find the name of the method. If call the method "areConditionsValid", I don't expect it to log anything, just to return a boolean. So the following doesn't seem right to me:
bool Foo::areConditionsValid(String action)
{
if (!isConditionValid())
{
log(action + " not possible because condition is not valid");
return false;
}
if (!isTheOtherConditionValid())
{
log(action + " not possible because the other condition is not valid");
return false;
}
return true;
}
Because it does more than what it says it does.
I can't call it checkConditionsAndLog()
because it is not good practice to have a "And" in the method's name, it is a good way to see that it's doing more than it should do...
What's the best way to refactor this?
The same applies if there is only one condition to check.
PS: It's in C++
isConditionValid()
andthrowIfConditionInvalid()
respectively. (I use exceptions in projects whenever exceptions are allowed.)