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

Asked

Viewed 30 times

-1

I have heard that it is good practice to return only true or false (1 or 0) functions, but if I create a function that checks a string, and I want to know what 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 a letter 'a'.

So my question is, would that be bad programming practice? And if it is, what other way 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 don’t just want to return 1 to say "There is an error", I mean what is the error that happened, so return 1, 2, 3....

  • It is only bad practice what you do that does not meet the requirements of the project.

  • I totally diverge from this 'good' practice. A function should return what you need from what you can report.

1 answer

1

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

What I recommend to 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 is working, but I believe that most high-level have this option.

follows 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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.