Image of Lucian Ghinda writing for notes.ghinda.com
November 12th, 2024

Choosing between if and a modifier

A little bit of bikeshedding: In Ruby, even outside of guard clauses, I sometimes use modifiers to make the code easier to read out loud.

A mental rule that I use to choose when to use a full if versus a modifier is taking into consideration if the condition has a side effect:

An image with three code samples showing an Active Record model and two options to check if post is saved
Example of two ways to write a condition

In this case I would choose the explicit if because the post.save has some important information when reading this code, while return Success(post) if post.save focuses on what is returned when skimming the code.

An image with a block of code and an explanaation about why I would choose that version
Using the normal if to communicate the important of the post.save operation