Thoughts on What to Return After Passing Invalid Input to Helper

Posted 1 year ago by lindstrom

I have a helper that wraps libphonenumber. The package throws a NumberParseException when it receives a number that isn't valid* for a given region. My inclination is to return the original value after catching the error. This is just one scenario, but I could see it applying to lots of formatting helpers. Since they are typically used for display, returning null or false isn't very useful IMO. The answer may be simply to be consistent.

What do you typically do?

Here's the method for illustration:

    private function formatNumber($value, $format, $region)
    {
        try {
            $phoneUtil = PhoneNumberUtil::getInstance();
            $phoneNumberObject = $phoneUtil->parse(
                preg_replace('/\D/', '', $value),
                $region
            );
        } catch (NumberParseException $e) {
            return $value;
        }

        return $this->{$format}($phoneUtil, $phoneNumberObject);
    }
  • Why not validate first? Two words, legacy data. The value could be virtually anything.

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.