前言
最近寫的幾個方法,事后看起來覺得有點重復了,想要重構試試,正好想起ramda,那就試試用ramda來重構,看下能否減少重復吧,
注: 這次重構主要為業余消遣,本文用到的代碼也不是原文, 只是仿照源代碼的特點寫的示例,如何撰寫代碼跟專案所處環境有關,所以本次重構方法僅為業余娛樂和學習,不對結果和方法作推薦,
重構前代碼
故事是這樣的,假設我有一個學生類:
function Student(name, score, age) {
this.name = name;
this.score = score;
this.age = age;
}
然后有一個學生陣列,并需要得到這些學生中的最低分, 那么學生陣列和求最低分的方法如下:
var students = [
new Student('Peter', 90, 18),
new Student('Linda', 92, 17),
new Student('Joe', 87, 19),
new Student('Sue', 91.5, 20),
]
function getMinScore(students) {
if (
!Array.isArray(students) ||
!students.every(student => student instanceof Student)
) {
return undefined;
}
return students.reduce(
(acc, student) => Math.min(acc, student.score),
Number.MAX_SAFE_INTEGER
);
}
嗯, 這代碼看著還行,至少自我感覺良好, 其中對型別判斷的部分,用typescript的話可以免去,咱這里沒用,就簡單直接點,
好,故事當然不會到這里就結束,否則就沒啥重構的了,
接下來,發現我還需要獲得學生中的最大年齡是多少, 好吧,很簡單啊,復制粘貼上面的再稍微改一下不就有了嗎? 如下:
function getMaxAge(students) {
if (
!Array.isArray(students) ||
!students.every(student => student instanceof Student)
) {
return undefined;
}
return students.reduce(
(acc, student) => Math.max(acc, student.age),
Number.MAX_SAFE_INTEGER
);
}
好了,代碼寫完,作業正常,收工,,,了嗎?
回頭看了看代碼,這兩個方法中,其實只有Math.min\Math.max和student.score\student.age不同,其他都一樣,這很不DRY啊,
看著不是很爽, 這時我想到了ramda,
能否用ramda,用組裝的方式來完成這兩個函式,以此減少重復呢?
好,說干就干,(下列重構基于個人經驗和認知,不對的地方歡迎指出共同討論)
重構ING
先來重溫下重構前的代碼:
點擊查看代碼
function getMinScore(students) {
if (
!Array.isArray(students) ||
!students.every(student => student instanceof Student)
) {
return undefined;
}
return students.reduce(
(acc, student) => Math.min(acc, student.score),
Number.MAX_SAFE_INTEGER
);
}
function getMaxAge(students) {
if (
!Array.isArray(students) ||
!students.every(student => student instanceof Student)
) {
return undefined;
}
return students.reduce(
(acc, student) => Math.max(acc, student.age),
Number.MAX_SAFE_INTEGER
);
}
這兩個方法做的事情基本可以拆分成以下步驟:
- 型別判斷,確定傳入引數是Student類實體的陣列
- 若型別錯誤,回傳undefined
- 若型別正確,遍歷陣列,并回傳最小/最大的score/age屬性值
好,先上個ramda的檔案地址: https://ramdajs.com/docs/#
型別判斷可以用以下方法實作:
const isInstanceof = (type) => (instance) => instance instanceof type;
const isStudent = isInstanceof(Student)
const allAreStudents = R.all(isStudent)
allAreStudents(students) => true
allAreStudents([1, 2, 3]) => false
這里的型別判斷,其實就是一個if else, 可以直接使用ramda的ifElse方法,下面再寫上型別錯誤時的處理,加起來就是:
const whileNotStudent = () => undefined
const processIfStudent = R.ifElse(allAreStudents, R.__, whileNotStudent)
熟悉ramda的同學肯定知道了,R.__是一個引數占位符,而ramda的方法幾乎都經過柯里化處理,當它的函式缺少足夠的引數時,執行后依然會回傳一個函式,當獲得全部所需引數時,才會真的執行被柯里化的方法,
所以上面這么呼叫,會讓processIfStudent成為一個需要一個引數的方法,這個引數會被傳遞給ifElse呼叫,
即下面兩種寫法等價:
假設我們有一個叫doSomething的函式
// 1
processIfStudent(doSomething)
// 2
R.ifElse(allAreStudents, doSomething, whileNotStudent)
這時我們需要的第一層邏輯就滿足了:
傳入引數是學生陣列時做XX, 不是時回傳undefined,
processIfStudent需要的引數,就是這個做XX的方法了,
接下來,我們先抽象一下我們需要做的事情,
無論是獲取最大還是最小, score還是age,我們要做的事情都可以抽象成:
1. 遍歷陣列
2. 用一個邏輯記錄下每次遍歷的結果,直至遍歷完成
3. 回傳這個結果
這個邏輯就是獲取最大或最小的某屬性了,
然后我們讓這個最大,最小和某屬性都可以被定制,
看了下ramda的檔案,我覺得我可以使用以下這些方法:
prop => 用于獲取屬性
minBy/maxBy => 通過兩個物件的某屬性進行比較并回傳較小或較大的物件
reduce => 用于遍歷陣列
compose => 用于組合方法,具體的后面一點再說
好了,方法選好了,就可以開始實施了,
先根據我的需求,寫了以下幾個方法:
// 獲取分數屬性
const getScore = R.prop('score')
// 獲取年齡屬性
const getAge = R.prop('age')
// 該函式可以回傳2個傳入引數中分數較小的那個
const minByScore = R.minBy(getScore)
// 該函式可以回傳2個傳入引數中年齡較大的那個
const maxByAge = R.maxBy(getAge)
// 該函式用reduce進行遍歷,可自定義遍歷所需的邏輯,和被遍歷的陣列
const reduceByHandler = handler => instances => R.reduce(
handler,
instances[0],
instances)
// 可以獲取傳入的陣列中,分數最小的陣列物件
const reduceMinScoreStudent = reduceByHandler(minByScore)
// 可以獲取傳入的陣列中,年齡最大的陣列物件
const reduceMaxAgeStudent = reduceByHandler(maxByAge)
到這里其實已經差不多了,使用上面的兩個reduce方法,可以得到分數最小和年齡最大的學生,但是我們現在需要的不是學生,而是那個數字,所以還需要用compose和prop來獲取得到的實體的具體屬性,即:
const reduceMinScore = R.compose(getScore, reduceMinScoreStudent)
const reduceMaxAge = R.compose(getAge, reduceMaxAgeStudent)
再套用回前面的processIfStudent方法,就能得到我們最終需要的方法了:
const getMinScore = processIfStudent(reduceMinScore)
const getMaxAge = processIfStudent(reduceMaxAge)
好了, 到這里, 我們終于得到我們需要的getMinScore和getMaxAge方法了,
直接用students呼叫一下,就能得到我們要的結果了:
const minScore = getMinScore(students)
console.log("minScore", minScore) // 87
const maxAge = getMaxAge(students)
console.log("maxAge", maxAge) // 20
以下是完整代碼:
點擊查看代碼
function Student(name, score, age) {
this.name = name;
this.score = score;
this.age = age;
}
var students = [
new Student('Peter', 90, 18),
new Student('Linda', 92, 17),
new Student('Joe', 87, 19),
new Student('Sue', 91.5, 20),
]
const isInstanceof = (type) => (instance) => instance instanceof type;
const isStudent = isInstanceof(Student)
const allAreStudents = R.all(isStudent)
const whileNotStudent = () => undefined
const processIfStudent = R.ifElse(allAreStudents, R.__, whileNotStudent)
const getScore = R.prop('score')
const getAge = R.prop('age')
const minByScore = R.minBy(getScore)
const maxByAge = R.maxBy(getAge)
const reduceByHandler = handler => instances => R.reduce(
handler,
instances[0],
instances)
const reduceMinScoreStudent = reduceByHandler(minByScore)
const reduceMaxAgeStudent = reduceByHandler(maxByAge)
const reduceMinScore = R.compose(getScore, reduceMinScoreStudent)`
const reduceMaxAge = R.compose(getAge, reduceMaxAgeStudent)
const getMinScore = processIfStudent(reduceMinScore)
const getMaxAge = processIfStudent(reduceMaxAge)
const minScore = getMinScore(students)
console.log("minScore", minScore)
const maxAge = getMaxAge(students)
console.log("maxAge", maxAge)
重構到此結束了, 回頭看看,好像還是有很多類似的代碼,例如score和age的方法都是成對出現,如reduceMinScore和reduceMaxAge,
是的,這些都很相似,但因為本身他們包含的邏輯很少,只是呼叫了相同的方法,但引數都不同,重復已經比之前少多了, 而且細粒度的拆分后,可讀性會好一點,也更方便除錯(函式式編程有時真的挺難除錯的),
最后
重構結束了, 再次宣告,這里的重構方法主要為娛樂和學習,大家是否要在專案中使用,還要根據自身專案情況而定, 上面的重構涉及很多小的方法和類似的方法,乍看起來好像代碼行數沒有少多少,但是,因為越靠上的方法,越獨立且業務無關,也就越是容易被復用,
當類似需求出現得越多, 小而精得方法被復用次數越多,代碼量的差距也會越大,我們每次需要重新寫的邏輯也就越少,
另外,如果上面哪里有更好的重構方法,也歡迎提出共同探討學習,
謝謝觀看,
原創不易,轉載請注明出處: https://www.cnblogs.com/bee0060/p/15704623.html
作者: bee0060
發布于: 博客園
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/386481.html
標籤:JavaScript
