Lets imagine you have a general validation function and you have to do several sub-checks to the input.Each of them also returns boolean. See this fictive one:
private function hasValidContent(string $content) : bool
{
$isValid = false;
$isValid = $this->hasMoreThanOneChar($content);
$isValid = $this->hasValidCharacters($content);
$isValid = $this->hasCapitalLetters($content);
...
return $isValid;
}
Of course, this code above wont work since every next check will override the evaluation of the previous.
But how can it be achieved to stop further checks, when the first check leads to false? For example if its content has not more than one char, then it should stop after the hasMoreThanOneChar function and return the hasValidContent method immediately as false.
Yes of course, you could check after each method call if the expression turned to false, but that is awkward and is much overhead and repetition.
Also it feels really ugly to do it in a single if with thousands of || or && like in
return $this->checkA($content)
&& $this->checkB($content)
&& $this->checkC($content)
...;
The readability will suffer after few more expressions.
A further often mentioned approach might be using exceptions
private function hasValidContent(string $content) : bool
{
try {
$this->hasMoreThanOneChar($content);
$this->hasValidCharacters($content);
$this->hasCapitalLetters($content);
...
}
catch {
return false;
}
return true;
}
private function hasMoreThanOneChar(string $string) : void {
if(count($string) < 2 ) {
throw new HasNotMoreThanOneCharException(...)
}
}
But i also see this not as an elegant solution since validating stuff is nothing exceptional.
So my question:
Is there any elegant pattern for this? Any keyword i can search for?