寫程式碼不只是寫給機器執行,更是寫給人閱讀。本文整理自 Dojo Toolkit 官方公布的 JavaScript 風格指南,規則細緻、可操作性強,非常值得團隊借鑑。以下內容由 i.feelinglucky 翻譯整理。
指南開篇有句話值得記住:Any violation to this guide is allowed if it enhances readability. 也就是說,只要某種寫法能讓程式碼更好讀,違反規則是被允許的。規則的目的是可讀性,不是教条。
Dojo 核心 API 採用的命名約定如下:
| 結構 | 規則 | 備註 |
|---|---|---|
| 模組(module) | 全小寫 | 不要使用多個單字拼接 |
| 類別(class) | 駝峰式(mixedCase) | — |
| 公開方法 | 混合式 | 外部呼叫也可採用 lower_case() |
| 公開變數 | 混合式 | — |
| 常數 | 駝峰或全大寫 | — |
以下幾項並非強制,但官方建議採用:
| 結構 | 規則 |
|---|---|
| 私有方法 | 混合式,前綴下劃線,例如 _mixedCase |
| 私有變數 | 混合式,前綴下劃線,例如 _mixedCase |
| 方法參數 | 混合式,例如 _mixedCase、mixedCase |
| 區域變數 | 混合式,例如 _mixedCase、mixedCase |
Account、EventHandler。var NodeTypes = {
Element : 1,
DOCUMENT : 2
};
getInnerHtml()、getXml()、XmlDocument。obj.getSomeValue()。var MyClass = function(){
var _buffer;
this.doSomething = function(){
};
}
this._somePrivateVariable = statement;setTopic(topic),其中 topic 就是 Topic 型別。getHandler() 而非 getEventHandler()。MouseEventHandler 而不是 MseEvtHdlr;同時也別把命名空間重複放進名稱,寫 dojo.events.mouse.Handler 而不是 dojo.events.mouse.MouseEventHandler。EventHandler → UIEventHandler → MouseEventHandler。在語意清楚的前提下,名稱可以精簡,例如 MouseEventHandler 勝於 MouseUIEventHandler。leftComboBox、TopScrollPane。isNotError、isNotFound 都不合格。縮進使用 4 個空白字元的定位。若你的編輯器支援檔案標籤,可以加上這行讓格式更容易辨識(使用 Vim 的讀者可自行取捨):
// vim:ts=4:noet:tw=0:
換行處要讓程式碼看起來完整、合邏輯:
var someExpression = Expression1
+ Expression2
+ Expression3;
var o = someObject.get(
Expression1,
Expression2,
Expression3
);
表達式的縮進應與變數宣告保持一致;函數參數也要有明確且一致的縮進。
一般區塊:
while (!isDone){
doSomething();
isDone = moreToDo();
}
if 敘述:
if (someCondition){
statements;
} else if (someOtherCondition){
statements;
} else {
statements;
}
for 敘述:
for (initialization; condition; update){
statements;
}
while 敘述:
while (!isDone) {
doSomething();
isDone = moreToDo();
}
do … while 敘述:
do {
statements;
} while (condition);
switch 敘述:
switch (condition) {
case ABC:
statements;
// fallthrough
case DEF:
statements;
break;
default:
statements;
break;
}
try … catch 敘述:
try {
statements;
} catch (ex) {
statements;
} finally {
statements;
}
單行的 if–else、while 或 for 也必須加上大括號,但可以寫成一行:
if (condition){ statement; }
while (condition){ statement; }
for (initialization; condition; update){ statement; }
var foo = function(){};)、if、return、switch、this、try、void、while、with。function foo(){};)、in、instanceof、new、throw、typeof、var。doSomething(someParameter); 而非 doSomething (someParameter)。函數與物件的基本描述包含三部分:summary(一句話說明目的)、description(較完整的描述)、returns(說明回傳內容,不含型別)。
function(){
// summary: Soon we will have enough treasure to rule all of New Jersey.
// description: Or we could just get a new roomate.
// returns: Look, a Bananarama tape!
}
物件函數(無回傳值):
{
// summary: Dingle, engage the rainbow machine!
// description:
// Tell you what, I wish I was--oh my g--that beam,
// coming up like that, the speed, you might wanna adjust that.
}
當函數的宣告與呼叫關係不明顯時,可以用類別包裝函數來承載文件說明:
dojo.declare(
"foo",
null,
{
// summary: Phew, this sure is relaxing, Frylock.
// description:
// Thousands of years ago, before the dawn of
// man as we knew him, there was Sir Santa of Claus.
// returns: Unless Carl pays tribute to the Elfin Elders in space.
}
);
注意:這種寫法只在函數沒有具名參數時有效,否則註解會被忽略。
簡單型別可以直接寫在參數列上:
function(/*String*/ foo, /*int*/ bar)...
可變型別的修飾符:? 代表可選參數,... 代表數量不確定,[] 代表陣列。
function(/*String?*/ foo, /*int...*/ bar, /*String[]*/ baz)...
如果想補充描述,可以把說明移到函數主體的開頭,格式為「*key* ~*type*~ 描述」:
function (foo, bar) {
// foo: String
// used for being the first parameter
// bar: int
// used for being the second parameter
}
由於實例變數、原型變數與外部變數的宣告方式相同,容易混淆,建議在變數最先出現的位置標明名稱、型別與作用域。
function foo() {
// myString: String
// times: int
// How many times to print myString
// separator: String
// What to print out in between myString
this.myString = "placeholder text";
this.times = 5;
}
foo.prototype.setString = function (myString) {
this.myString = myString;
}
foo.prototype.toString = function() {
for (var i = 0; i < this.times; i++) {
dojo.debug(this.myString);
dojo.debug(foo.separator);
}
}
foo.separator = "=====";
物件內的成員,用與其宣告處一致的寫法標註:
{
// key: String
// A simple value
key: "value",
// key2: String
// Another simple value
}
同一個函數可能回傳多種型別,因此每個 return 後面都要標註型別。若全部同型別就寫該型別,若型別不一則標為 mixed。
function() {
if (arguments.length) {
return "You passed argument(s)"; // String
} else {
return false; // Boolean
}
}
若你想先寫出流程草稿,可以用 /* 加上至少五個等號包住,例如 /*===== 與 =====*/,實作完成後再決定是否移除。
/*=====
module.pseudo.kwArgs = {
// url: String
// The location of the file
url: "",
// mimeType: String
// text/html, text/xml, etc
mimeType: ""
}
=====*/
function(/*module.pseudo.kwArgs*/ kwArgs){
dojo.debug(kwArgs.url);
dojo.debug(kwArgs.mimeType);
}
原文出處:dojotoolkit.org/developer/StyleGuide 翻譯:i.feelinglucky(gracecode.com)