Skip to content

Commit 7e54062

Browse files
Add guideline for using safe operator. (#912)
Add guideline for using safe operator
1 parent d38d9d5 commit 7e54062

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

README.adoc

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,34 @@ foo&. bar
323323
foo&.bar
324324
----
325325

326+
=== Safe navigation
327+
328+
Avoid chaining of `&.`. Replace with `.` and an explicit check.
329+
E.g. if users are guaranteed to have an address and addresses are guaranteed to have a zip code:
330+
331+
[source, ruby]
332+
----
333+
# bad
334+
user&.address&.zip
335+
336+
#good
337+
user && user.address.zip
338+
----
339+
340+
If such a change introduces excessive conditional logic, consider other approaches, such as delegation:
341+
[source, ruby]
342+
----
343+
#bad
344+
user && user.address && user.address.zip
345+
346+
#good
347+
class User
348+
def zip
349+
address&.zip
350+
end
351+
end
352+
user&.zip
353+
----
326354
=== Spaces and Braces [[spaces-braces]]
327355

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

0 commit comments

Comments
 (0)