今日推薦開源項目:《有聲音的代碼 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/