3 ms·
In Ruby (and Crystal), I tend to use `unless` for guards at the top of the method, or returns. These are typically `return foo unless baz`. When I write Elixir
by hosh 4y ago
In Ruby (and Crystal), I tend to use `unless` for guards at the top of the method, or returns. These are typically `return foo unless baz`.
When I write Elixir, `unless` gets awkward in a functional style of programming, and Elixir has guard clauses and pattern matching. I pretty much never use `unless` in Elixir despite using it in Ruby for years.
Sometimes, I'll add extra methods with a negation in the name itself. So for example
# instead of
return "invalid" unless valid?
return [] if empty?
# I define invalid?() and do
return "invalid" if invalid?
return [] if empty?
- mjevans 4y agoPerl also had that delayed syntax check style as an option and I HATED IT. THING if logical condition Filter First is far better self-documentation: if condition THING
- hosh 4y agoThat's a matter of what fits better with the structure of how you think internally, and not necessarily that there is an objectively better way for self-documentation. For example, I can totally see how imperative-first would mess up people with neurodivergant brains. Tangent -- Ruby takes a lot of inspiration from Perl.
- layer8 4y agoIt works well in cases where you have an operation that consists of a certain sequence of statements, where one of the statements has to be omitted in a particular atypical situation. Instead of having interrupt the sequence with an if, you just tag the particular statement with the omitting condition at the end. That’s also when unless tends to be intuitive, because it suggests an atypical condition.
- hosh 4y agoThat is usually where I used it too. When I started writing these as pipeline execution. Then I’ll use a maybe?() instead if the conditional does not need to depend on the result of a previous operation.