max-lines-per-function
強制函式中的最大程式碼行數
有些人認為大型函式是一種程式碼異味。大型函式往往會做很多事情,並且很難追蹤正在發生的事情。許多程式碼風格指南規定了函式可以包含的行數限制。此規則可以幫助強制執行該風格。
規則詳細資訊
此規則強制每個函式的最大行數,以幫助維護並降低複雜性。
為什麼不使用 max-statements
或其他複雜度測量規則來代替?
如下例所示,巢狀的長方法鏈通常會分成多行以提高可讀性
function() {
return m("div", [
m("table", {className: "table table-striped latest-data"}, [
m("tbody",
data.map(function(db) {
return m("tr", {key: db.dbname}, [
m("td", {className: "dbname"}, db.dbname),
m("td", {className: "query-count"}, [
m("span", {className: db.lastSample.countClassName}, db.lastSample.nbQueries)
])
])
})
)
])
])
}
max-statements
只會將此回報為 1 個語句,儘管它是 16 行程式碼。complexity
只會回報複雜度為 1max-nested-callbacks
只會回報 1max-depth
將回報深度為 0
選項
此規則具有以下可使用物件指定的選項
-
"max"
(預設值為50
) 強制函式中的最大行數。 -
"skipBlankLines"
(預設值為false
) 忽略僅由空白組成的行。 -
"skipComments"
(預設值為false
) 忽略僅包含註解的行。 -
"IIFEs"
(預設值為false
) 包含 IIFE 中包含的任何程式碼。
或者,您可以為 max
選項指定單一整數
"max-lines-per-function": ["error", 20]
等同於
"max-lines-per-function": ["error", { "max": 20 }]
程式碼
此規則對於特定最大值的不正確程式碼範例
在遊樂場中開啟
/*eslint max-lines-per-function: ["error", 2]*/
在遊樂場中開啟
/*eslint max-lines-per-function: ["error", 3]*/
在遊樂場中開啟
/*eslint max-lines-per-function: ["error", 4]*/
此規則對於特定最大值的正確程式碼範例
在遊樂場中開啟
/*eslint max-lines-per-function: ["error", 3]*/
function foo() {
var x = 0;
}
在遊樂場中開啟
/*eslint max-lines-per-function: ["error", 4]*/
function foo() {
// a comment
var x = 0;
}
在遊樂場中開啟
/*eslint max-lines-per-function: ["error", 5]*/
function foo() {
// a comment followed by a blank line
var x = 0;
}
skipBlankLines
此規則使用 { "skipBlankLines": true }
選項的不正確程式碼範例
在遊樂場中開啟
/*eslint max-lines-per-function: ["error", {"max": 2, "skipBlankLines": true}]*/
此規則使用 { "skipBlankLines": true }
選項的正確程式碼範例
在遊樂場中開啟
/*eslint max-lines-per-function: ["error", {"max": 3, "skipBlankLines": true}]*/
function foo() {
var x = 0;
}
skipComments
此規則使用 { "skipComments": true }
選項的不正確程式碼範例
在遊樂場中開啟
/*eslint max-lines-per-function: ["error", {"max": 2, "skipComments": true}]*/
此規則使用 { "skipComments": true }
選項的正確程式碼範例
在遊樂場中開啟
/*eslint max-lines-per-function: ["error", {"max": 3, "skipComments": true}]*/
function foo() {
// a comment
var x = 0;
}
IIFEs
此規則使用 { "IIFEs": true }
選項的不正確程式碼範例
在遊樂場中開啟
/*eslint max-lines-per-function: ["error", {"max": 2, "IIFEs": true}]*/
(());
()();
此規則使用 { "IIFEs": true }
選項的正確程式碼範例
在遊樂場中開啟
/*eslint max-lines-per-function: ["error", {"max": 3, "IIFEs": true}]*/
(function(){
var x = 0;
}());
(() => {
var x = 0;
})();
何時不使用它
如果您不關心函式中的行數,則可以關閉此規則。
相關規則
版本
此規則在 ESLint v5.0.0 中引入。