What is the best way to return function-specific error codes? [closed]

-1

I've heard that it's a good practice to return only true or false (1 or 0) functions, however, if I create a function that checks a string, and I want to know which errors occurred in it, I usually return different values, for example:

RETURN 1 - If the string contains a number.

RETURN 2 - If the string contains special characters.

RETURN 3 - If the string contains any letter 'a'.

So my question is, would this be a bad programming practice? And if it is, how else do I return a certain error from a function that checks a string (for example).

NOTE: I return different values to display a more intuitive and user-specific error. I do not want to just return 1 to say "There is a mistake", I mean what is the error that happened, so I return 1, 2, 3 ....

    
asked by anonymous 05.04.2018 / 16:44

1 answer

1

I believe that this is something particular to each programmer and every project, there are several ways to do a validation method, for example: there are those who prefer to show errors through a class of exceptions, just like there are people who prefer to do one method that returns a string.

What I recommend for you is to create a method that returns a variable of type boolean, but has a variable out with the error message; you did not say which language you are working on, but I believe that most high-level people have this option.

follow example in C #:

public bool ValidaCampos (String minhaString, out string mensagemErro)
{
    mensagemErro = string.Empty;

    if (minhaString.Contains("a"))
        mensagemErro += "A string contém a letra A";

    ... demais validações

    return string.isNullOrEmpty(mensagemErro);
}
    
05.04.2018 / 17:00