DEV Community

Discussion on: How I improved my code by returning early, returning often!

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️ • Edited
func main() {
   data, err := loadData()
   result, err := someCalculation(data)
   return result, err
}

Now that code will work fine

No it won't? If loadData() fails, you will then discard that error by calling someCalculations and returning the wrong error to the caller. This code is objectively broken.

const validateAuthorisedPage = (page, isUserAuthenticated) => {
  const authenticatedPages = ['profile']
  if (authenticatedPages.includes(page) && isUserAuthenticated) {
    return page
  }
  return 'login'
}

Those two returns are on mutually exclusive separate branches, yet they're on different indentation levels. Neither of them is a guard clause. In conclusion, this code should be written like this instead:

function validateAuthorisedPage(page, isUserAuthenticated) {
   const authenticatedPages = ['profile']
   if (authenticatedPages.includes(page) && isUserAuthenticated) {
      return page
   } else {
      return 'login'
   }
}
Enter fullscreen mode Exit fullscreen mode

Suddenly it's clear that both returns are on different branches and only one of the two will run every time that code is executed.

Collapse
 
jordanfinners profile image
Jordan Finneran

Sorry for not making it clear, that first example is supposed to be bad as a demonstration. :)

It's good to see how others prefer to write that statement.
Thanks for the comments!

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Sorry for not making it clear, that first example is supposed to be bad as a demonstration. :)

Yes, but you say that it's bad but not broken. I'm saying it is broken, not just bad.