From b8452097054f2a93d1146329249bc4d29b23176a Mon Sep 17 00:00:00 2001 From: fatkodima Date: Wed, 11 Sep 2024 19:02:22 +0300 Subject: [PATCH] Extend safe navigation docs about long `&.` chains --- README.adoc | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/README.adoc b/README.adoc index 132e6c29..abe7c141 100644 --- a/README.adoc +++ b/README.adoc @@ -325,23 +325,24 @@ foo&.bar === Safe navigation -Avoid chaining of `&.`. Replace with `.` and an explicit check. +Avoid long chains of `&.`. The longer the chain is, the harder it becomes to track what +on it could be returning a `nil`. Replace with `.` and an explicit check. E.g. if users are guaranteed to have an address and addresses are guaranteed to have a zip code: [source,ruby] ---- # bad -user&.address&.zip +user&.address&.zip&.upcase # good -user && user.address.zip +user && user.address.zip.upcase ---- If such a change introduces excessive conditional logic, consider other approaches, such as delegation: [source,ruby] ---- # bad -user && user.address && user.address.zip +user && user.address && user.address.zip && user.address.zip.upcase # good class User @@ -349,8 +350,9 @@ class User address&.zip end end -user&.zip +user&.zip&.upcase ---- + === Spaces and Braces [[spaces-braces]] No spaces after `(`, `[` or before `]`, `)`.