0

recently I was brought to a new codebase where I see A LOT of these, like almost everywhere

if(a && a.b && a.b.c && a.b.c.d) {
  // do something with d
}

It was brought to my attention that since the product is generating a lot of $$$, we really need to avoid runtime errors. So this ended up being the idiom in the team, each time you want something in an object do it with the syntax above.

But as you can think, this is not enforced everywhere (especially where that could matter) and worse it became a habit in zones where we already validated the object shape.

So here is my question: what would you recommend help transform a team that took this inefficient habit (false sentiment of security) to defensively check every accession.

Here are some ideas, but I would be pleased to hear your stories and your experience feedbacks.

Some Ideas:

  • go ts or babel and use optional chaining => will not change the issue, but will (NOT?) ease the syntax
  • force the use of a unique helper to safely access (custom / lodash.get / ramda.pathOr, ...)
  • educate team to the Lenses concepts and use those
  • add a strong validation layer between data layer and presentation layer
  • flatten nested object and work with the flatten form ({ a: { b: 2 }, c: [3,4]} ==> { 'a.b': 2, 'c.0': 3, 'c.1': 4 })
  • ...
Xavier Haniquaut
  • 905
  • 8
  • 22
  • 1
    I don’t think _“what would you recommend”_ is [on-topic](/help/on-topic) here. Anyway. Whether `a?.b?.c?.d` is useful, depends on what `a` or `a.b`, etc., can be. If it’s a fixed, static structure, there’s no reason to assume that property access may fail. If it’s data fetched from elsewhere, then defensive syntax may be appropriate. But instead of properties, consider `Map`s or some other construct, depending on the semantics of `a`, `b`, `c`, or `d`, e.g. `a.maybeGet("b.c")?.d` or whatever. The syntax should communicate what is really being checked; you should _know_ what you’re doing. – Sebastian Simon May 08 '21 at 11:13

0 Answers0