DEV Community

Discussion on: Ruby's Safe Navigation Operator `&.` and is it a Code Smell?

Collapse
 
wulymammoth profile image
David • Edited

πŸ‘ for mentioning the "null object pattern". Solid write-up!

Seeing too many #try and &. in code is a major code smell! Chances are the code isn't tested well either, because, well, each of those calls expands into two new branches of tests -- one for the nil case and another for non-nil case. In the example you've shown...

potatoes.foo&.bar&.baz&.qux

complete test coverage for the potato unit test should have at least 2^3 => 8 test cases, where 2 is the number of branches spawned for each &. invocation and 3 being the number of &. used

Chaining is typically bad and it also violates the "Law of Demeter" where the subject/object should only know about its immediate neighbors/relationships. The class or code that surrounds/wraps potatoes.foo&.bar&.baz&.qux is subject to change and breakage if bar, baz, or qux's behaviors change. This is tight-coupling and no bueno!

Collapse
 
hkly profile image
hkly

Yes, exactly!