Clean Code – Is Returning True or Throwing an Exception Good Practice?

clean codedesign-patternsexceptions

I am focusing on learning better design and wondered if this code is good or an anti-pattern? The function Validate() returns true if the data is correct, else it will throw an exception with a message to display in a popup.

Another way could have been to return a string and treat empty string as validated, but I don't see that as much cleaner.

try
{
    if (await Validate(data))
    {
        //logic
        success = true
    }
}
catch (Exception e)
{
   message = e.Message;
   success = false;
}

return new GenericResponse(success, data, message);

Best Answer

Either returning true or throwing an exception is an unusual way of indicating success or failure. It's not an anti-pattern, but it's not good practice either. Until I read the description of what happens properly, my immediate thought was that you weren't handling Validate returning false. It therefore breaks the principle of least astonishment.

A better approach would be to use the try pattern, eg for a language that uses out parameters you might have something like:

bool TryValidate(SomeType data, out string failureMessage);

where the return value is true for success and false for failure. When false, failureMessage contains the reason it fails (and it's undefined when the return is true).

Depending on the language you are using, you could use a tuple or even an Either<bool, string> union to return the data. Whichever method is used though, the principle of the pattern is true/false with a message when false is returned.

Related Topic