←back to thread

1457 points nromiun | 1 comments | | HN request time: 0.207s | source
Show context
makeitdouble ◴[] No.45075139[source]
Lowering the cognitive load by assigning temporary variables requires more thought and skill than credited here.

In particular these variables need to be extremely well named, otherwise people reading the code will still need to remember what exactly is abstracted if the wording doesn't exactly fit their vision. E.g.

> isSecure = condition4 && !condition5

More often than not the real proper name would be "shouldBeSecureBecauseWeAlsoCheckedCondition3Before"

To a point, avoiding the abstraction and putting a comment instead can have better readability. The author's "smart" code could as well be

  ```
  if (val > someConstant // is valid
      && (condition2 || condition3) // is allowed
      && (condition4 && !condition5) // is secure 
  ) {
      ...
  }
  ```
replies(3): >>45075269 #>>45075640 #>>45075674 #
1. claytongulick ◴[] No.45075640[source]
I try to structure functions and validations like this in a early-return list at the top of a function.

    if(val <= someconstant)
        return; //not valid

    if(!(condition2 || condition3))
        return; //not allowed

    ...
The author mentions this technique as well.

I find it particularly useful in controller API functions because it makes the code a lot more auditable (any time I see the same set of conditions repeating a lot, I consider whether they are a good candidate for middleware).

I try to explain this to newer developers and they just don't get it, or give me eyerolls.

Maybe sending them this article will help.