本文主要介紹一下如何讓代碼整潔可讀的幾點建議,總體是為了讓代碼邏輯及結(jié)構(gòu)更加清晰,增加可讀性。
一、命名
一切命名都要使其有意義
1 名字要自說明
變量、函數(shù)、類等的名稱應(yīng)當(dāng)具備告訴你:它為什么存在、它做了什么事、應(yīng)該怎么用、等。
【如果名稱需要注釋來說明,需考慮是否更換名字】
意義不夠的變量命名,帶來閱讀的困難度
// 不清晰的變量命名
public List getThem() {
List list1 = new Array();
for(int[] x: theList) {
if(x[0] == 4) {
list1.add(x)
}
}
return list1
}
// 有意義的變量命名
public List getFlaggedCells() {
List flaggedCells = new Array()
for(int[] cell: gameBorad){
if(cell[STATUS_VALUE] == FLAGGED) {
flaggedCells.add(cell)
}
}
return flaggedCells
}
// 適當(dāng)?shù)姆庋b提升邏輯清晰度
public List getFlaggedCells() {
List flaggedCells = new Array()
for(int[] cell: gameBorad){
if(cell.isFlagged()) { // 判斷使用函數(shù)封裝
flaggedCells.add(cell)
}
}
return flaggedCells
}
2 使用讀得出來的名稱
以一個記錄日期的類為例,該類的變量記錄不同的時間
// 修改前
class DatRcd02 {
Date genymdhms
Date modymdhms;
String pazqint = '102'
}
// 修改后
class Customer {
Date generationTimestamp;
Date modificationTimestamp;
String recordId = '102'
}
3 有意義的數(shù)字或字符串字面值,用枚舉/常量/變量/函數(shù)封裝
switch (userStatus){
case 101:
case 100:
case 200:
}
// 封裝后
const USER_STATUS = {
LOGGED: 100,
INVALID: 101,
DELETED: 200,
}
// 使用
if(userStatus == USER_STATUS.LOGGED){}
4 類名或?qū)ο竺麘?yīng)該是名詞或名詞短語
Customer, WikiPage, AddressParser
5 方法名應(yīng)當(dāng)是動詞或動詞短語
deletePage, getCustomerAddress
6 善用行業(yè)名詞
二、函數(shù)
設(shè)計原則
- 短小
- 只做一件事
3/ 描述功能的名字
邏輯原則
寫代碼像寫文章一樣,能順利通暢的表達(dá)思路
-
自頂而下設(shè)計
讓代碼讀起來像是一系列自項向下的TO起頭段落是保持抽象層級協(xié)調(diào)一致的有效技巧。
image.png 函數(shù)內(nèi)語句在同一個抽象層級上
function reloadData() {
this.total = 0;
this.name = '';
this.tip: '';
const responseData = await api.getOrders(this.userId)
if(responseData){
this.name = responseData.name
this.tip = responseData.tip
reponseData.list.forEach(order => this.total += order.total)
}
}
// 抽象后
function reloadData() {
this.resetData()
this.loadData()
}
function resetData() {
this.total = 0;
this.name = '';
this.tip: '';
}
funtion loadData() {
const responseData = await api.getOrders(this.userId)
if(responseData){
this.name = responseData.name
this.tip = responseData.tip
reponseData.list.forEach(order => this.total += order.total)
}
}
參考地址: 《代碼整潔之道》
