if / else expressions are a powerful tool that allow us to express conditional logic. However, when it comes to returning Booleans they are generally the wrong tool for the job. They can be redundant or, worse, obscure the meaning of what is being done.
This is a mistake I often see brand new programmers fall into. If you’re looking to write an if/else, it’s natural to express “admins can edit and others cannot” as the following conditional:
On closer inspection though, we can see that the conditional code is redundant. It just returns the value that the Boolean already holds. Instead, we can return the Boolean directly without doing any logic.
This one is very similar to the “identity” conditional shown above but the branches are flipped. When admin? is true we return false and when it is false we return true.
Ruby syntax allows for combining early returns with a postfix conditional to create really terse conditional logic. If you’re using this approach to return different Booleans, you’re probably better off using the Boolean operations instead. Consider the following: