DEV Community

Discussion on: DevTips: Use early returns to avoid nested conditions

4ortytwo profile image

I keep seeing seniors advising other devs to change jobs and forget the idea of them being real devs. It really needs to stop, people require time to learn and if you nurture you juniors properly, you'll have the strongest team ever. This guy sounds like the type of person who'd laugh in the face of someone who's made a mistake and put them down for this. Can't envy his colleagues unless it's a viper nest filled with the Elite just like him.

Thread Thread
thomasjunkos profile image
Thomas Junkツ

@Yann Bertrand

Although, I know you just posted your code as an example and although I know it is really nitpicky from me, but when looking at your code:

const userIsLoggedIn = user.isLoggedIn()
const userCanComment = user.score > 10

if (userIsLoggedIn && userCanComment) {
  // Comment

I see two things:

  • you have a method isLoggedIn() on user. From my POV user.isLoggedIn() is equivalent to userIsLoggedIn. This is no win.

  • userCanComment is really better than user.score > 10 which is really bad. But, why is this no method on the user too?

So you would end up with

if (user.isLoggedIn() && user.canComment()) {
  // Comment

and no extra variables needed.

Thread Thread
moopet profile image
Ben Sinclair


then they shouldn't be a developer at all

That's a really unhelpful thing to say.

Pretending it's not... I'm a professional developer who has used Javascript on and off since it was first released (though it's not my primary language by any means). I wouldn't use a hack like that, because I think it's awkward and likely to cause confusion or problems farther down the line.

There are prefectly valid ways to do things that don't sacrifice readability; when someone tries to refactor it out later on because it seemingly does nothing, they'll be at fault for introducing a bug. I say the original author introduced the bug, and would pick that up in a code review.

Thread Thread
yannbertrand profile image
Yann Bertrand

Agreed! I was not inspired, thanks for going further 🙂

Thread Thread
jouana profile image
Antoine Jouan

I am agreed with your improvement expect for adding predicate to user class.
This will break Single Reponsability principle.
I think it's better to make a class for predicate which will manage specification and one class for user which will manage user state.
So if you want to keep this syntax then you can set predicate as extension of user class but in js it's little tricky and not simple for beginner.

Thread Thread
thomasjunkos profile image
Thomas Junkツ

I do not quite understand. Starting with "classes". You could do that without classes at all. Plain objects will do.