DEV Community

Discussion on: If/else or just if?

Collapse
 
sunnysingh profile image
Sunny Singh

I always go with Statement B. This is known as "early returns" and helps with confusing success/error cases. Take for example:

function createPost(post) {
  // Earliest potential error if no post is provided.
  if (!post) return false;

  // Ensure correct data type.
  if (typeof post !== 'object') return false;

  // Ensure required data is provided.
  if (!post.title || !post.body) return false;

  // We're all good at this point. Assume it's safe to create the post!
  const isPostCreated = create(post);

  return isPostCreated;
}
Enter fullscreen mode Exit fullscreen mode

It's nice to know for sure that the end of the function where we're saving the post to the database will not error out due to bad data, since we already verified those cases earlier.

Collapse
 
tyrw profile image
Tyler Warnock

This looks great to me. I'd be happy even without the comments as it feels pretty self-documenting.

Collapse
 
sunnysingh profile image
Sunny Singh

I added the comments just for the sake of the example, but they should definitely be removed for a real app.

Collapse
 
scooby359 profile image
Chris

I like this style more - it looks clearer to me, and from the point of working through the logic, I like that the returns just end the function.

If a block just set a value and returned it later, there's a chance it could be reassigned in another buggy block, so I think there's less risk in this style too.