|
| 1 | +# Limit use of conditional modifiers to short, simple cases |
| 2 | + |
| 3 | +Conditional modifiers (i.e., `if` or `unless` at the end of a line) can be |
| 4 | +surprising when they appear on long or complex lines. The reader might not see |
| 5 | +them while scanning the code. |
| 6 | + |
| 7 | +So, prefer to use them only for short, simple cases. For example: |
| 8 | + |
| 9 | +```ruby |
| 10 | +do_later if async? |
| 11 | +``` |
| 12 | + |
| 13 | +The example above can read more naturally than: |
| 14 | + |
| 15 | +```rb |
| 16 | +if async? |
| 17 | + do_later |
| 18 | +end |
| 19 | +``` |
| 20 | + |
| 21 | +## Complex conditions |
| 22 | + |
| 23 | +However, if the line is too long (around 80 characters) or complex (e.g., an |
| 24 | +`if` with multiple conditions like `if a && b`) prefer the multi-line form: |
| 25 | + |
| 26 | +```ruby |
| 27 | +# Avoid |
| 28 | +block_access! if signed_in? && !current_user.active? |
| 29 | + |
| 30 | +# Prefer |
| 31 | +if signed_in? && !current_user.active? |
| 32 | + block_access! |
| 33 | +end |
| 34 | +``` |
| 35 | + |
| 36 | +There might be cases where the conditional modifier work well with multiple |
| 37 | +conditions, so use your best judgment. |
| 38 | + |
| 39 | +## An opportunity to refactor |
| 40 | + |
| 41 | +If the conditions are related, consider extracting a method that groups them. |
| 42 | +This might allow you to use the conditional modifier form again. |
| 43 | + |
| 44 | +```ruby |
| 45 | +def inactive_user? |
| 46 | + signed_in? && !current_user.active? |
| 47 | +end |
| 48 | + |
| 49 | +block_access! if inactive_user? |
| 50 | +``` |
| 51 | + |
| 52 | +## Conditional modifiers feel informal |
| 53 | + |
| 54 | +The modifier form of conditionals can feel more casual than the multi-line form. |
| 55 | +Conversely, the multi-line form _draws attention_ to the conditional and the |
| 56 | +code that follows it. Use this to your advantage when you want to emphasize the |
| 57 | +conditional and the code that follows it. |
| 58 | + |
| 59 | +```rb |
| 60 | +# Avoid |
| 61 | +def action |
| 62 | + return destroy_all if really? |
| 63 | + |
| 64 | + do_nothing |
| 65 | +end |
| 66 | + |
| 67 | +# Prefer |
| 68 | +def action |
| 69 | + if really? |
| 70 | + destroy_all |
| 71 | + else |
| 72 | + do_nothing |
| 73 | + end |
| 74 | +end |
| 75 | +``` |
| 76 | + |
| 77 | +You can also refactor the code so the less destructive action uses a conditional |
| 78 | +modifier, which pairs well with the informal feel of the modifier form: |
| 79 | + |
| 80 | +```rb |
| 81 | +def action |
| 82 | + return do_nothing if chill? |
| 83 | + |
| 84 | + destroy_all |
| 85 | +end |
| 86 | +``` |
0 commit comments