4 ms·
Really nice, I work in a project with a lot of nested optional values, and all the `a && a.b && a.b.c && a.b.c.d` checks really introduce a lot of noise.
by dtech 7y ago
Really nice, I work in a project with a lot of nested optional values, and all the `a && a.b && a.b.c && a.b.c.d` checks really introduce a lot of noise.
- manojlds 7y agoMostly it's a code smell though https://en.m.wikipedia.org/wiki/Law_of_Demeter https://en.m.wikipedia.org/wiki/Law_of_Demeter
- Vanit 7y ago4 chains is like reaching into an XHR response to pull out the success result, so I wouldn't say that's necessarily a smell.
- mattmanser 7y agoNot really, especially when you're working with external APIs. That's when I find myself using a lot of this type of code.
- zhirzh 7y agoI'd say it is a design smell and not necessarily code smell. Any API or data interface should try to keep "optional keys" at a minimum. Depending on the language, `a.b && ...` could be checking either or both of the following: - does `a` have key 'b'? - is `a.b` truthy?
- jiofih 7y agoTell that to the team that created protocol buffers.
- gridlockd 7y agoProgramming is fundamentally about the transformation of data and sometimes data is in such a shape that inevitably requires such code. Most of the time, you don't get to decide what shape the data is in. OOP just obfuscates this basic fact of programming life to the point where it's not obvious anymore. That is not a good thing, it's a huge waste of time. Favor plain data over "objects" and functions over methods. Favor plain SQL queries over ORM.
- z3t4 7y agoI don't think it's bad enough to warrant introduction of new syntax sugar to make it shorter. The problem might be that we have most likely not yet handled the edge case situation where a.b and a.b.c doesn't exist. And just want to log out the value, and print undefined if it doesn't exist.
- gridlockd 7y agoI disagree. This is just an extreme example, but take it down one or two levels and it's extremely common. Ruby has had this kind of syntax since forever and it's one of the things that people love about it. > The problem might be that we have most likely not yet handled the edge case situation where a.b and a.b.c doesn't exist That's not an edge case, that's an expected case. If it doesn't exist, nothing is supposed to happen.
- oliyoung 7y agolodash's #get solves this for us now https://lodash.com/docs#get https://lodash.com/docs#get