开源日报 每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,坚持阅读《开源日报》,保持每日学习的好习惯。
今日推荐开源项目:《有声音的代码 rockstar》
今日推荐英文原文:《Did You Know There’s an Elvis Operator?》

今日推荐开源项目:《有声音的代码 rockstar》传送门:GitHub链接
推荐理由:写代码,自然也能够算是一门艺术——你可以把代码写的很简洁,很易懂,很高效,或者是很能让人唱出来。这个项目是一个编程语言,目的就是要让程序代码在可以运行的同时也可以像歌词一样,因为这样“似乎很有意思”。尽管这样在操作上更为繁琐复杂,但是这样的代码读起来将会更有趣味性(或者说唱起来),而且这样你就可以很轻松的把你的程序们贴在墙上了,这还会让你变得像个很酷的歌手。

今日推荐英文原文:《Did You Know There’s an Elvis Operator?》作者:Jonathan Hsu
原文链接:https://medium.com/better-programming/did-you-know-theres-an-elvis-operator-1406cb364929
推荐理由:给运算符起名的人到底是怎么想的呢……

Did You Know There’s an Elvis Operator?

What other clever operator names are out there?


Photo by Greg Ortega on Unsplash
After Python 3.8 released the Walrus Operator and I began experimenting with it, I couldn’t help but be impressed with the creativity in naming. I mean, it really does look like a walrus. So I asked myself the question: what other clever operator names are out there?

This led me to the Elvis operator, ?:, which is named after its resemblance to his famous hair. While I can’t say this is the “king” of operators, I found it valuable enough to share.

What Is the Elvis Operator?

Like other operators with colloquial names, Elvis has a technical or formal name as well. Falling in the class of binary assignment operators — meaning it takes two operands used for assignment — the Elvis operator is a “logical or” for the purpose of assignment to a variable (or constant).

Also called a null-safety, the Elvis operator will take the first of two operands if that value’s boolean expression is true; otherwise, the second value is taken.
// example is language agnostic
// assume variable 'a' is null

// This would store the default string
my_var = a ?: "a default string"
The intention of the Elvis operator is to condense a ternary operator statement where the boolean evaluation of the “if true” value is the determinant expression.
// examples are language agnostic

// ternary example
my_var = a ? a : b

// expanded if/else example
if(a) {
   my_var = a
} else {
   my_var = b
}

Does My Language Have the Elvis Operator?

Most likely, yes; although it may not bear resemblance to the King. The specific character sequence “?:" is present in many languages, such as C, C++, Kotlin, Groovy, and ColdFusion.

In PHP’s implementation of the ternary operator, the middle operand may be omitted, in which case the ternary operator resembles the Elvis operator and behaves the same.

In Python, JavaScript, Ruby, and Perl, the Elvis operator does not exist; however, the OR operator (||,or) functions similarly. In these cases, the determination between assigning the first or second operand is not entirely dependent on the first being null, but rather the first being truthy; or evaluating to a true result. What this means is that empty strings, empty arrays/lists, and undefined keys in objects/dictionaries evaluate to false and cause the second operand to be assigned.

JavaScript example:
let name = "";let user = name || "Default Name"; # Default Name
Python example:
person = {
   "first_name": "Jonathan",
   "last_name": "Hsu"
}middle_initial = person['middle_name'][0] or None # None

Why Would I Use the Elvis Operator?

The primary reason to use the Elvis operator is to consolidate statements for clarity. This consolidation is not only visual, but in the event a in our example above is a long function, the Elvis operator has the potential to influence performance as well.

I’ve found the primary reason for using the Elvis operator is to safeguard against null or undefined values; hence I gravitate towards its identity as a null-safety. For me, this most often presents itself when dealing with Python command-line scripts that take in arguments.
import argparseparser = argparse.ArgumentParser(description='')
parser.add_argument('--server', dest='server', help='iFormBuilder server name (ie. app.iformbuilder.com)')

args = parser.parse_args()
server = args.server or ""
The intent is to provide default values in a concise manner in the event an argument is not supplied in the command line.

Why would I want a default value for an argument? Two reasons:

First, oftentimes subsequent functions are expecting a specific data type such as a string. Rather than pass along an undefined or null value, I can use this technique to assign an empty string.

Secondly, if I want to avoid the hindrance of entering in all arguments at the command line, or I want to simplify execution for a specific customer, I can skip the arguments (assuming I’ve made them optional) and set the customer’s specific values as the second operand.
import argparseparser = argparse.ArgumentParser(description='')
parser.add_argument('--server', dest='server', help='iFormBuilder server name (ie. app.iformbuilder.com)')

args = parser.parse_args()
server = args.server or "default.iformbuilder.com"

Conclusion

You can make use of the Elvis/null-safety/short-circuiting OR operator in your code to safeguard against null values and to provide default assignment values when the primary option fails.
下载开源日报APP:https://openingsource.org/2579/
加入我们:https://openingsource.org/about/join/
关注我们:https://openingsource.org/about/love/