Ninja code
学而不思则罔,思而不学则殆。過去的工程師使用這些技巧,讓別人看不懂程式碼。
Brevity is the soul of wit
極簡的極致,相看兩不厭,只有一行碼。
// taken from a well-known javascript library
i = i ? i < 0 ? Math.max(0, len + i) : i : 0;
One-letter variables
一個字母的變數,沒人知道代表的意思。
Use abbreviations
只有通靈王能知道縮寫代表的意思,盡情使用吧!
list
→lst
.userAgent
→ua
.browser
→brsr
.…etc
Soar high. Be abstract.
最適合變數的名稱
data
value
乍看之下很正常,實際上沒有任何意義。用資料類型命名,
str
num
找不到更多變數,後面加數字
item2
data1
Smart synonyms
對於同樣的事情用不同前綴,不同的兩件事情用相同的前綴。
displayMessage
vsshowName
(顯示在螢幕上)printPage
(印出來) vsprintText
(顯示在螢幕上)
Reuse names
重複使用已存在的變數,更進階的用法式在函式中間重新使用。
function ninjaFunction(elem) {
// 20 lines of code working with elem
elem = clone(elem);
// 20 more lines, now working with the clone of the elem!
}
Underscores for fun
在變數前使用 _
__
而且沒人知道他們代表的意思。
降低可讀性
花很長時間弄清楚下畫線的意思
Show your love
寫的一堆沒用的形容詞,superElement
megaFrame
niceItem
。
Overlap outer variables
let user = authenticateUser();
function render() {
let user = anotherValue();
...
...many lines...
...
... // <-- a programmer wants to work with user here and...
...
}
Side-effects everywhere!
isReady()
checkPermission()
假設只會執行內部運算不會影響函式外的變數,結果使用時改變了外面的變數或返回的值不是布林值,你同事的表情一臉矇逼爽!
Powerful functions!
函數不只執行一個動作時,你的同事用不著這個函式,他就不會來煩你了。
Last updated
Was this helpful?