Code Quality – Returning True/Nothing Instead of True/False

code-qualityfunctionslanguage-agnosticreturn-type

Is it OK to have a function that returns true/nothing instead of true/false?

My examples use JavaScript, but I'm wondering about the general case, not attached to one specific language.

The subjects of my interest:

  • Is it OK from the practical side?
  • Is it OK from the logical side?

I mean, some languages provide too much freedom and personally I don't like it. I think it is better to follow the way how it works in serious languages like C++ and Java, but I never worked with them.

var a = 1;
var b = 2;

function foo() {
    if (a === b)
        return true;
}

if (!foo())
    alert('error');

versus

function foo() {
    if (a === b)
        return true;
    else
        return false;
}

Best Answer

It depends on what you mean by "OK".

In the languages that I'm familiar with that have the capability to do so, a null/nil/undefined value is falsy. That means that it would be interpreted the same as false when used in a Boolean operation like described in the examples. However, I cannot say for absolute certainty that this will apply to all languages for all time. I also cannot say that everyone reading and working on your code will know this, especially if it's their first foray into a language that permits this behavior.

Personally, I prefer more explicit code. Even if it's slightly more verbose or less idiomatic for your given language, easier readability and maintainability is often a superior choice. Like anything, though, it's a tradeoff that must be decided among the team building the software. Often, decisions like this can be codified in the configuration of linters and other static analysis tools and violations can be detected (and sometimes auto-corrected) during the development process.

Related Topic