by nickelcitymario · 3y ago · 0 comments
Why? Because it allows you to express yourself more elegantly.
The click-bait title is misleading. It's meant to ridicule "unless", but actually achieves the opposite.
If you were to write the title of the post as code, it would be:
unless !ruby_dev
read article
end
That would be a terrible use of "unless"! That should clearly say "if ruby_dev", not "unless !ruby_dev".But what if you wanted to write an article meant for anyone other than ruby developers?
Which of the following is better?
if !ruby_dev
or unless ruby_dev
Both work, but I consider the second option more elegant. Just as I wouldn't verbally say "if you're not a ruby developer" rather than "unless you're a ruby developer".Honestly, I don't see the issue. It's a style matter. Just use it properly. All language can be abused if you try hard enough.
This is not a contrived example. I regularly find myself having to read some code in a language in which I am not proficient. Stuff like ’unless’ is such a pointless obstacle in these scenarios.
So ”elegance” doesn’t come free. The cost is a loss of transferable knowledge from other languages. Your intuition is that this cost is low relative to the benefit of ”elegance,” I have the opposite intuition. Why stray from such universal conventions in favour of one person’s subjective aesthetic preference?
And if you go on that direction, almost the everything on the language is a larger roadblock than an oddly placed conditional.
What do you think is more important: the speed at which C programmers can navigate your code base, or one person’s subjective idea of ”elegance”?
Specifically about Ruby, with it's infinite levels of metaprograming and "you can even redefine the meaning of blank space" philosophy, it's not 'unless' that will stop anybody.
That said, when reading code, I often have to pause and mentally translate "unless" to "if not". This is especially true for more complex logic.
Elegant, yes. Additional mental overhead at times, certainly.
You say there is a difficult time transferring knowledge from other languages when they see the `unless`. That's fair.
My response to that is that, to idiomatically think in Ruby is write code that reads well, and `unless` fits that. Every language has an idiomatic way in which one thinks and reasons with the language. While there are principles that can be transferred over across languages, the way to think in that language does not necessarily transfer. The Ruby community has a heavy emphasis on creating embedded DSLs that seems natural enough to written English, and the Ruby community's style guide is written for that.
In contrast to Ruby, Python has idioms that seem to be the inverse of Ruby. The intuitions on what is good, idiomatic Ruby is counter-intuitive in Python. This even extends to the design of Ruby bundler vs. Python virtualenv/pip. As a long time Rubyist, Python rubs me the wrong way (what is intuitive in Python is counter-intuitive in Ruby) until I realized that I used to write that style of code a long time ago with Pascal.
I do like `unless` in Ruby, but only when it is the one liner form and the exception happens pretty rarely. The multi line form often takes a lot of effort to parse for me if it is more than a very simple expression.
Python exposes those methods. What you see is what you get. Classes and objects are not considered as autonomous agents so much as data structures bound with functions that can operate on it.
More controversially than “unless” is Ruby’s way of calling an anonymous function. Almost every other language, if “f” is a function, you can call it with f(). In Ruby, an anonymous function is an object, and you call it by sending a message “.call()”; the shorthand for “call” being “f.()”. Everything is an object.
This trips up even polygots who like Ruby. But if your mind can shift in such a way where that is ever seen intuitive, then you’re probably well on your way to being able to think in Ruby. (Assuming someone _wants_ to think that way).
I want to suggest a slight reframing: instead of saying: "It is not all about cost-benefit," you could say "here is an addition to the 'benefits' column that hasn't been considered yet."
It's a totally reasonable argument; much better than "elegance." This was my main problem: that the critique of `unless` was much more plausible than the defence.
However, we don’t always make decisions purely on cost vs benefit. Some types of decisions, such as strategic thinking, involves unfair advantages. If cost-benefits are reasoned from a finite space in which one can find the optimal choice, unfair advantages cheats that, and operates on a potentially infinite space with imperfect information.
Not that I am saying Ruby or Python are unfair advantages :-) I’m just saying that cost-benefit is not the only way in which one can decide on something, and may not be appropriate for every situation. Being able to think in a language can potentially change how you think, and framing that as a benefit can be problematic.
I explored Ruby because I wanted to explore eloquence, semantics, and pattern languages (in the Christopher Alexander sense). I spent over ten years on it until I had my fill. Now I am exploring concurrency, reliability, uncertainty, self-healing and distributed systems — Elixir and Kubernetes. And while I still use Ruby in some tooling, it doesn’t give me the joy that Elixir does.
A statement that forces you to switch out of inaccurate skiming mode is insanely useful
Practically speaking, that's not how I know Ruby to be written. The convention I follow is to use `unless` when there is no `else` case and only when there is no negation in the expression.
I do wonder if it's an issue of "unless" being misused? Programmers using it just for fun rather than considering whether it's the best choice in context?
When I come across an `unless`, I can't use them; I have to come back out into "conscious reading" mode, or something like that. Makes me crazy.
do_something unless already_done?That said, I feel it's really down to double+ negation being hard to handle. `if` with a single negation is fine; `unless` is automatically a negation, so you're just off to a bad start on that front. I feel like the only viable use is in a case like Rust's `let … else { diverge }` where anything that fails the condition is guaranteed to diverge (typically, return) and I can just ignore it when reading the overall codeflow. But Ruby mixes that up and does `diverge unless …` which puts the diverging part "up front" and "in the way" for such readings.
Weirdly, Ruby was one of the first languages I learned early in my career, and at the time I had no problem with `unless`. But after years of experience with other languages, I similarly feel that `if` statements now trigger the fast pattern matching circuits in my brain, while `unless` makes me do a double-take and basically translate it into `if not`
At first I thought I was just becoming dumber with age, but I like your explanation better :P
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?THING if logical condition
Filter First is far better self-documentation: if condition THING
The truth is there is a balance in all languages. Nearly every word was invented to prevent having to say a string of other words to mean the same thing.
"Unless" is a single word to mean "If not". I consider that elegant.
However, some languages take this too far, in my opinion. German famously has a word for nearly everything. I'm not sure that's elegant, in that it requires learning a far greater number of words.
English has many words that I wouldn't consider elegant, simply because they're uncommon or convoluted. Never use a 10 dollar word when a 5 cent word will do.
So, if, like me and the ruby community, you prefer to optimize for developer happiness, "unless" is an elegant choice.
If you prefer to optimize for peak computing performance, if may be more computationally efficient use "if not".
But, _unless_ you're saying that you never use the word "unless" in everyday language, I think we can agree it's a good word that has good applications. I don't see why that wouldn't be true in programming.
That's not quite how it works though, right? Compound words are exactly that, combining two or more words to narrow down the meaning, without having to invent a new word. It's almost like "if not" vs "unless"...
Side note: ancient Greek didn't use spaces, and many other languages (Thai and Written Chinese are the ones with which I'm most familiar) either don't use spaces or make spaces optional. The distinction between a phrase and a word gets a bit blurry at times, and I find the distinction is seldom useful, particularly when making comparisons across languages.
Ruby inherits the Perl philosophy of "There's more than one way to do it". Compare with Python, and its "There should be one — and preferably only one — obvious way to do it."
It's true that it makes the compiler less elegant, but Ruby optimizes for the programmer at the expense of the compiler.
"count" is only equivalent to "length" and "size" when called with no argument and no block, and should be slower for that case (it includes a comparison of arity and a call to rb_block_given_p() in MRI before it returns the array length).
IMHO, something ‶elegant″ in programming is not something that can't be built form something else (or we will all end up in writing only CMOVs), but something that conveys the meaning of its author precisely and concisely – which makes it inherently subjective. I'm in the `unless` team, I can perfectly understand if you are in the `no unless` team, but this argument does not make a lot of sense.
The very ergonomic solution to map a computation to every element of a sequence is `map`. In this case, `for` is filled with bookkeeping that does not matter.
But there are enough people on this thread who feel differently that it makes me wonder if maybe we're wrong. If code is meant to be read and understood by all, and if "unless" is confusing to a large number of people, maybe those of us who like it should knock it off.
I do find it more elegant and easier to read, but maybe you and I can process double negatives easier than the anti-unless crowd are able to process "unless" logic.
If that's the case, I'd be willing to sacrifice my preference for "unless" for the greater good.
Could you give an example of a double negative in this case?
I ask because using "if" does not lend itself to double negatives in my experience, but just thinking about "unless" I see double negatives being an issue (since unless is already negating the operand).
I would likely not be a programmer if it weren’t for Ruby and it doing things different.
I had tried to learn programming for years (JavaScript, Python, Java, C#), none of it stuck or progressed beyond following tutorials and one of the things I had serious issues with was negation.
Then I came across Ruby and it just kinda clicked into place like no other language had. With Ruby I was able to do my own things within a month.
Now I don’t really have a problem picking up other languages anymore. But there’s others out there right now struggling to learn programming and there should be as many programming languages doing things different as possible to increase the chance that they come across one that is obvious for the way they think.
This idea of there should only be one way of doing things is poison in my opinion.
Which is why unless is such a hard concept for people to grasp, not just in code, but also in regular English.
At least the "if not" makes the negation explicit, which can then be easily eliminated using several different techniques (early return, swap with the else condition) if the negation is confusing enough.
However, "unless" necessarily includes negation because that's how the word is defined.
This is the first I've heard about this confusion over the word "unless" in English.
In spoken English I do notice that most often the "unless" comes after a statement. Example: "I'll be there on time, unless the bus is late." That is more clear (to me) than "I'll be there on time, if the bus is not late." Maybe not by coincidence, I tend to like "unless" when it follows the action in in Ruby code, too.
Go to the store and get milk, if not we already have some.
I confess at first I thought they were somewhat superfluous, but they are more readable now that I'm used to them. Completely agreed on it being stylistic, mainly.
Sure, I understand the "elegant" aspect, two symbols are shortened to one (although I'd argue that's not that important when it comes to clarity and legibility).
But every time I read "unless" in code it's quite jarring. I have to consciously translate it to "if not", and even then seeing the "unless" keeps tripping me off, perhaps because it's awkward in English to start a sentence out of the blue with "unless".
The `unless` keyword makes the interpreter slightly more complicated and is another piece of language the human brain needs to recognize. It may seem inconsequential, but grains of sand make a hill, as they say.
My ideal language would leave out pretty much anything that can be achieved with more basic constructs. It would of course have if-else, and leave out `unless`, but there would also be no switch statements or ternaries. Branching must be done with if-else or by looking up a value in a hash. No `for` or `while` loops because a simple `loop` construct with `continue` and `break` statements can do everything that `for` and `while` could do in other languages. No classes or inheritance because they're magical and they can be effectively simulated by the end developer if that's what they really want.
What I think would be really cool is to have a language with a syntax like Ruby but with only the most basic of programming language constructs.
You can simulate the loop behaviour if that's what you really want
Structured programming is, I believe, a good idea for the vast majority of use cases. Though one can technically use structured programming while using goto, encouraging goto can therefore allow programmers to go down a path that is counterproductive. It's basically the opposite end of the spectrum from OOP where encouragement of rampant objectiveness and inheritance makes programmers write code that is way too complicated.
There's absolutely a place for goto. I once made a "language" (actually YAML) specifically for developing for the Amazon Alexa platform, and it used something similar to goto called "go to scene" and "go to random". For that sort of thing, goto can be much more practical and even easier to reason about than "better" constructs in general purpose high-level programming languages. It's just not something I would consider appropriate for the kind of language I am proposing, though I still ponder on it.
Though, I think it's rare to expand a pattern match/switch into an if-else tree, and much more common to expand an if-else into a 2-way pattern match/switch.
If you're really keen on such a language, you could fairly easily implement such a language as a pre-commit hook source code re-formatter so that all of the source in your repository is in your favorite language subset.
Therefore, coming from a computer science background I don't like 'unless'.
(For context: I dropped out of comp sci and took a job as a web dev ~18 years ago. Never looked back. But have ended up learning more about copywriting and marketing than computer science along the way.)
I always have to stop at an unless because the double-negative is really hard to evaluate in the mind IMHO.
IMHO unless leads to unnecessary nesting. In your example, it reads like _most_ people are ruby dev. I try to keep the most-often excecuted flow as flat as possible (happy path) and just try to nest for additional/special cases. Unless just tries to do... different.
The if !ruby_dev (read as "if not ruby_dev") is so much easier.
The one place I’ll often use unless is things like:
return unless valid
raise unless h.key?(k)
I think it might have something to do with:1. How abundantly clear it is that the condition is a Boolean; and
2. The “false” condition indicating a “no work to do” situation.
I think I only use them for postfix return, break, next, and raise.
“Unless” is a conjunction, and its presence creates a double negative with the end of the sentence making the sentence extra clunky (“unless you’re a Ruby dev, you shouldn’t read this article.”)
A few iterations later, we get to the correct syntax, “read this article if you’re a Ruby dev.”
if !ruby_dev
or unless ruby_dev
As a ruby dev of 5+ years, I still have an easier time with `if !ruby_dev`. I have to translate `unless` to `if !` every single time to grok something. Almost like an extra step in an algebraic expression being simplified.The `unless` is idiomatic to the Ruby way of thinking.
Also note that unless itself contains another negative ( < medieval onlesse)
It's just easy to see if more than one conditions are evaluated:
if (!ruby_dev && cpp_dev)
vs
unless (ruby_dev && !cpp_dev)
if (true) and if not(true) is simple and elegant, and doesn't require any person on my team to stop their flow to puzzle out what the code is supposed to be doing at that point.
You want a well-justified, inclusive, and consistent yet adaptable style when collaborating with people. It would be selfish to gatekeep a policy without regard for those principles.
Let me put it this way: Are there _any_ programming paradigms that don't get poorly used? We need to learn how to use our tools well, not reduce them to banality.
Everyone's lazy or overwhelmed at some point, and it made mistakes too easy to make (the problem is that it overtightens the lug nuts because the ease of use removes the proper physical feedback).
In situations where you don't have the bandwidth to perfectly educate everyone and enforce rules, sometimes it's easier to limit the toolset. A tire iron can be misused too, but it's a little harder.
raise(“a long error string”) unless valid
This reads much worse, when the string pushes the line near max width, than: valid or raise(“..
Of course it’s another idiom to learn but it’s not a difficult one when used simply.