Ruby:
a || b
(no return
as last line is returned implicitly, no semicolon)
EDIT: As pointed out in the comments, this is not strictly equivalent, as it will return b
if a
is false
as well as if it’s nil
(these are the only two falsy values in Ruby).
Python:
return a or b
i like it because it reads like a sentence so it somewhat makes sense
and you can make it more comprehensive if you want to:
return a if a is not None else b
And no one on his team ever understood his code.
Sometimes being declarative is better than being “smart”
I’m confused on how this is difficult to understand. Put aside the fact that it’s just a regular operator that… I mean virtually everyone should know, how hard is it to google “what does ?? mean in [language]” which has the added benefit of learning a new operator that can clean up your code?
Well yeah but imagine you had to do that on most lines of the code? It would become very distracting imho. If you are in a team with people that have a lot experience and or will learn more anyway this is fine. But if you are in a team with not very good programmers which “will never learn” because they have other stuff to do, you should be careful when using code like this. Though I would prefer in the former of course.
I’m learning swift and I actually just discovered ??
today. Am I missing out in other languages?
Yes, it’s very useful when applied correctly.
I’m always disappointed when I remember, that I can’t use such a feature, because I’m stuck using Java.
I enjoy this:
return a.or(b);
But yeah, that requires an Option
type rather than null
pointers…
Is that Rust? Assuming a
is an Option (which would be close approximation of OP’s nullable type) and assuming b is not null, then this would be closer to the original idea:
a.unwrap_or(b)
It returns value of a
if it’s not None rather than Option.
Ah, true. Thanks.
Theoretically, it was supposed to be pseudo-code, secretly inspired by Rust, but I did get that one mixed up.
And I am actually even a fan of the word unwrap
there, because it follows a schema and you can have your IDE auto-complete all the things you can do with an Option
.
In many of these other languages, you just get weird collections of symbols which you basically have to memorize and which only cover rather specific uses.
Except there’s literally no change in performance as a normal compiler will treat those the same. It just looks nice and trim down the time an experienced dev reads and understands the code by around 200ms.