--- robots: noindex, nofollow tags: refactoring --- # Separate Query from Modifier > 練習用的 [REPL](https://repl.it/@yaosiang/SeparateQueryfromModifier) ```javascript= function alertForMiscreant(people) { for (const p of people) { if (p === "Don") { setOffAlarms(); // 除找出符合條件的 people 之外,又多做了一件事情,這是 side effect return "Don"; } if (p === "John") { setOffAlarms(); return "John"; } } return ""; } ``` 看得出來,迴圈裡做了兩件事情。 ```javascript= function alertForMiscreant(people) { for (const p of people) { if (p === "Don") { setOffAlarms(); return "Don"; } if (p === "John") { setOffAlarms(); return "John"; } } return ""; } function findMiscreant(people) { // copy 原 function,改名字 for (const p of people) { if (p === "Don") { setOffAlarms(); return "Don"; } if (p === "John") { setOffAlarms(); return "John"; } } return ""; } ``` 先複製一個 function,然後把不需要的任務刪除。 ```javascript= function alertForMiscreant(people) { for (const p of people) { if (p === "Don") { setOffAlarms(); return "Don"; } if (p === "John") { setOffAlarms(); return "John"; } } return ""; } function findMiscreant(people) { for (const p of people) { if (p === "Don") { // setOffAlarms(); // 刪除不需要的 code return "Don"; } if (p === "John") { // setOffAlarms(); // 刪除不需要的 code return "John"; } } return ""; } ``` ```javascript= // 其他呼叫端可以從以下的寫法 const found = alertForMiscreant(people); // 改成這樣的寫法 const found = findMiscreant(people); alertForMiscreant(people); ``` 原本的程式不需要回傳值了。 ```javascript= function alertForMiscreant(people) { for (const p of people) { if (p === "Don") { setOffAlarms(); return; // 這個 function 不需要回傳,直接 return } if (p === "John") { setOffAlarms(); return; } } return; } function findMiscreant(people) { for (const p of people) { if (p === "Don") { return "Don"; } if (p === "John") { return "John"; } } return ""; } ``` 甚至連額外的 found 變數都不需要了。 ```javascript= function alertForMiscreant(people) { // 因為 find 邏輯已經在 findMiscreant 內,可以直接呼叫使用 if (findMiscreant(people) !== "") setOffAlarms(); } ```