Search code examples
coding-stylereadabilitycode-readabilityhuman-readableguard-clause

Guard clause for a single statement function?


What is the most readable way of writing a very simple function that is effectively executing one statement, if a condition is met?

What I find most readable is this:

function doSomething(myNumber){
    if(myNumber !== null && myNumber > 5){
        doTheThing();
    }
}

However, my colleague insists that guard clauses make anything more readable, and would always write this function like this:

function doSomething(myNumber){
    if(myNumber === null || myNumber <= 5)
        return;
    doTheThing();
}

I understand that guard clauses can be way more readable in bigger functions, especially if there is a need to check for multiple conditions, and/or if exceptions need to be thrown. But in a case like this, I always have to do a triple-take to understand in which case doTheThing() will be executed, which seems ridiculous for such a simple function.


Solution

  • This is not really a technical question, but rather a choice of style.

    There are many ways you can write that function and the compiler will try to optimise it as best as possible. As for "readability" this is purely up to the programmer's choice. As long as you follow the language rules and standards, then any choice is fine. Of course if you work in a team it might be better to agree on a certain style, so that everyone can work on the code without getting confused.

    Personally, if I really want to make it readable I would do this:

    function doSomething(myNumber)
    {
       if(myNumber != null && myNumber > 5)
       {
           doTheThing();
       }
    }
    

    On the other hand if I want less lines of code I would choose this:

    function doSomething(myNumber)  {
        if(myNumber == null || myNumber <= 5)  return;
        doTheThing();
    }
    

    Also it is important to consider how the if statement should be. In this case you cover all possibilities, but just keep it in mind to avoid unexpected errors.