Skip to content

Commit 38a8961

Browse files
fatkodimabbatsov
authored andcommitted
Extend safe navigation docs about long &. chains
1 parent 179947b commit 38a8961

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

README.adoc

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -325,32 +325,34 @@ foo&.bar
325325

326326
=== Safe navigation
327327

328-
Avoid chaining of `&.`. Replace with `.` and an explicit check.
328+
Avoid long chains of `&.`. The longer the chain is, the harder it becomes to track what
329+
on it could be returning a `nil`. Replace with `.` and an explicit check.
329330
E.g. if users are guaranteed to have an address and addresses are guaranteed to have a zip code:
330331

331332
[source,ruby]
332333
----
333334
# bad
334-
user&.address&.zip
335+
user&.address&.zip&.upcase
335336
336337
# good
337-
user && user.address.zip
338+
user && user.address.zip.upcase
338339
----
339340

340341
If such a change introduces excessive conditional logic, consider other approaches, such as delegation:
341342
[source,ruby]
342343
----
343344
# bad
344-
user && user.address && user.address.zip
345+
user && user.address && user.address.zip && user.address.zip.upcase
345346
346347
# good
347348
class User
348349
def zip
349350
address&.zip
350351
end
351352
end
352-
user&.zip
353+
user&.zip&.upcase
353354
----
355+
354356
=== Spaces and Braces [[spaces-braces]]
355357

356358
No spaces after `(`, `[` or before `]`, `)`.

0 commit comments

Comments
 (0)