Decomposing the statement Function (การย่อยฟังก์ชัน statement)
เวลา refactor function ที่เป็น Long Function แบบนี้ ผมจะพยายามในใจหาจุดที่แบ่งส่วนต่าง ๆ ของพฤติกรรมโดยรวมออกจากกัน ชิ้นแรกที่สะดุดตาผมคือ switch statement ตรงกลาง
function statement (invoice, plays) {
let totalAmount = 0;
let volumeCredits = 0;
let result = `Statement for ${invoice.customer}\n`;
const format = new Intl.NumberFormat("en-US",
{ style: "currency", currency: "USD",
minimumFractionDigits: 2 }).format;
for (let perf of invoice.performances) {
const play = plays[perf.playID];
let thisAmount = 0;
switch (play.type) {
case "tragedy":
thisAmount = 40000;
if (perf.audience > 30) {
thisAmount += 1000 * (perf.audience - 30);
}
break;
case "comedy":
thisAmount = 30000;
if (perf.audience > 20) {
thisAmount += 10000 + 500 * (perf.audience - 20);
}
thisAmount += 300 * perf.audience;
break;
default:
throw new Error(`unknown type: ${play.type}`);
}
// add volume credits
volumeCredits += Math.max(perf.audience - 30, 0);
// add extra credit for every ten comedy attendees
if ("comedy" === play.type) volumeCredits += Math.floor(perf.audience / 5);
// print line for this order
result += ` ${play.name}: ${format(thisAmount/100)} (${perf.audience} seats)\n`;
totalAmount += thisAmount;
}
result += `Amount owed is ${format(totalAmount/100)}\n`;
result += `You earned ${volumeCredits} credits\n`;
return result;
}
เมื่อมอง code ชิ้นนี้ ผมสรุปได้ว่ามันกำลังคำนวณค่าใช้จ่ายสำหรับ performance หนึ่งรอบ ข้อสรุปนั้นคือความเข้าใจเชิงลึกเกี่ยวกับ code แต่ดังที่ Ward Cunningham กล่าวไว้ ความเข้าใจนี้อยู่ในหัวของผม—ซึ่งเป็นรูปแบบการจัดเก็บที่ฉาวโฉ่ว่าไม่จีรัง ผมต้องทำให้มันคงอยู่ถาวร ด้วยการย้ายมันจากหัวกลับเข้าไปใน code วิธีนั้น หากวันหลังกลับมาดู code จะบอกเองว่ามันทำอะไร— ผมไม่ต้องมานั่งคิดใหม่
วิธีใส่ความเข้าใจนั้นลงใน code คือเปลี่ยนชิ้น code นั้นให้เป็นฟังก์ชันของตัวเอง ตั้งชื่อตามสิ่งที่มันทำ—ประมาณว่า amountFor(aPerformance) . เวลาผมอยากเปลี่ยน code ชิ้นหนึ่งให้เป็นฟังก์ชันแบบนี้ ผมมีขั้นตอนที่ลดโอกาสทำพลาดได้ ผมเขียนขั้นตอนนี้ลงไว้ และเพื่อให้อ้างอิงง่ายก็ตั้งชื่อมันว่า Extract Function ( 106 ) .
ขั้นแรก ผมต้องสำรวจใน code ชิ้นนั้นว่ามี variable ใดบ้างที่จะหลุดออกจาก scope เมื่อแยก code ออกเป็น function ของตัวเองแล้ว ในกรณีนี้มีสามตัว: perf , play , และ thisAmount . สองตัวแรกถูกใช้ใน code ที่แยกออกไปแต่ไม่ถูกแก้ค่า จึงส่งเข้าไปเป็น parameter ได้ variable ที่ถูกแก้ค่าต้องดูแลมากหน่อย ที่นี่มีตัวเดียว จึงคืนค่าออกมาจาก function ได้ และยังย้ายการ initialize เข้าไปไว้ใน code ที่แยกออกมาได้ด้วย เมื่อทำครบจะได้แบบนี้:
function statement…
function amountFor(perf, play) {
let thisAmount = 0;
switch (play.type) {
case "tragedy":
thisAmount = 40000;
if (perf.audience > 30) {
thisAmount += 1000 * (perf.audience - 30);
}
break;
case "comedy":
thisAmount = 30000;
if (perf.audience > 20) {
thisAmount += 10000 + 500 * (perf.audience - 20);
}
thisAmount += 300 * perf.audience;
break;
default:
throw new Error(`unknown type: ${play.type}`);
}
return thisAmount;
}
เวลาผมใช้ header แบบ “ function someName… ” ตัวเอียงนำหน้า code บางชิ้น นั่นหมายความว่า code ที่ตามมาอยู่ภายใน scope ของฟังก์ชัน ไฟล์ หรือ class ที่ชื่ออยู่ใน header นั้น โดยปกติแล้วภายใน scope นั้นจะมี code อื่นอีกที่ผมไม่แสดง เพราะไม่ได้พูดถึงมันในตอนนี้
code statement เดิมตอนนี้เรียก function นี้เพื่อเติมค่าให้ thisAmount :
top level…
function statement (invoice, plays) {
let totalAmount = 0;
let volumeCredits = 0;
let result = `Statement for ${invoice.customer}\n`;
const format = new Intl.NumberFormat("en-US",
{ style: "currency", currency: "USD",
minimumFractionDigits: 2 }).format;
for (let perf of invoice.performances) {
const play = plays[perf.playID];
let thisAmount = amountFor(perf, play);
// add volume credits
volumeCredits += Math.max(perf.audience - 30, 0);
// add extra credit for every ten comedy attendees
if ("comedy" === play.type) volumeCredits += Math.floor(perf.audience / 5);
// print line for this order
result += ` ${play.name}: ${format(thisAmount/100)} (${perf.audience} seats)\n`;
totalAmount += thisAmount;
}
result += `Amount owed is ${format(totalAmount/100)}\n`;
result += `You earned ${volumeCredits} credits\n`;
return result;
พอเปลี่ยนเสร็จ ผมจะ compile และ test ทันทีเพื่อดูว่าทำอะไรพังหรือเปล่า การ test หลัง refactoring ทุกครั้งเป็นนิสัยที่สำคัญ—ต่อให้การเปลี่ยนนั้นจะเล็กน้อยแค่ไหนก็ตาม ความผิดพลาดเกิดขึ้นได้ง่าย—อย่างน้อยผมก็รู้สึกว่ามันง่ายสำหรับผม การ test หลังการเปลี่ยนแต่ละครั้งหมายความว่า เวลาผมทำพลาด ผมมีโค้ดที่เปลี่ยนไปเพียงเล็กน้อยให้พิจารณาเพื่อหาจุดผิด ซึ่งทำให้หาและแก้ได้ง่ายกว่ามาก นี่คือแก่นแท้ของกระบวนการ refactoring: เปลี่ยนเล็ก ๆ แล้ว test หลังการเปลี่ยนทุกครั้ง ถ้าผมพยายามทำทีเดียวหลายอย่าง ความผิดพลาดจะบังคับให้ผมเข้าสู่การ debugging ที่ยุ่งยากซึ่งอาจกินเวลานาน การเปลี่ยนเล็ก ๆ ซึ่งทำให้ feedback loop สั้นลง คือกุญแจที่จะเลี่ยงความยุ่งเหยิงนั้น
ที่ผมใช้คำว่า compile ที่นี่หมายถึงการทำอะไรก็ตามที่จำเป็นเพื่อให้ JavaScript รันได้ เนื่องจาก JavaScript รันได้โดยตรง บางครั้งมันอาจไม่ต้องทำอะไรเลย แต่ในกรณีอื่นอาจต้องย้าย code ไปยัง output directory และ/หรือใช้ processor อย่างเช่น Babel [ babel ] .
Refactoring เปลี่ยนโปรแกรมเป็นขั้นเล็ก ๆ ดังนั้นถ้าคุณทำพลาด ก็จะหาจุดที่ bug อยู่ได้ง่าย
เนื่องจากนี่คือ JavaScript ผมจึงสามารถแยก amountFor ออกเป็น nested function ของ statement ได้ ซึ่งช่วยได้เพราะแปลว่าผมไม่ต้องส่งข้อมูลที่อยู่ใน scope ของฟังก์ชันแม่ให้กับฟังก์ชันที่เพิ่งแยกออกมา ในกรณีนี้มันไม่ได้สร้างความแตกต่างอะไร แต่ก็เป็นเรื่องหนึ่งที่ลดภาระไปได้
ในกรณีนี้ test ผ่านหมด ขั้นต่อไปของผมคือ commit การเปลี่ยนแปลงนั้นลง version control system ในเครื่องของผมเอง ผมใช้ version control system เช่น git หรือ mercurial ที่ให้ผม commit แบบส่วนตัวได้ ผมจะ commit หลัง refactoring ที่สำเร็จทุกครั้ง เพื่อว่าถ้าทำอะไร messed up ทีหลัง จะได้กลับไปสู่สถานะที่ทำงานได้ง่าย ๆ จากนั้นผมค่อย squash การเปลี่ยนแปลงหลาย ๆ ครั้งให้เป็น commit ที่มีนัยสำคัญขึ้นก่อนจะ push ขึ้น shared repository
Extract Function ( 106 ) เป็น refactoring ที่นิยมทำให้เป็นอัตโนมัติ ถ้าผมเขียน Java ผมคงกดคีย์ลัดใน IDE โดยสัญชาตญาณเพื่อทำ refactoring นี้ ในขณะที่ผมเขียนหนังสือเล่มนี้ ยังไม่มีเครื่องมือ JavaScript ที่รองรับ refactoring นี้อย่างแข็งแรง ผมจึงต้องทำด้วยมือ มันไม่ยากนัก เพียงแต่ต้องระวัง variable ที่ scope อยู่ใน local นั้นให้ดี
หลังใช้ Extract Function ( 106 ) เสร็จ ผมจะย้อนกลับไปดูสิ่งที่แยกออกมา ว่ามีอะไรง่าย ๆ ที่ทำได้ทันทีเพื่อทำให้ฟังก์ชันที่แยกออกมานั้นชัดเจนขึ้นไหม สิ่งแรกที่ผมทำคือเปลี่ยนชื่อ variable บางตัวให้ชัดเจนขึ้น เช่น เปลี่ยน thisAmount เป็น result .
function statement…
function amountFor(perf, play) {
let result = 0;
switch (play.type) {
case "tragedy":
result = 40000;
if (perf.audience > 30) {
result += 1000 * (perf.audience - 30);
}
break;
case "comedy":
result = 30000;
if (perf.audience > 20) {
result += 10000 + 500 * (perf.audience - 20);
}
result += 300 * perf.audience;
break;
default:
throw new Error(`unknown type: ${play.type}`);
}
return result;
}
มาตรฐานการเขียนโค้ดของผมคือต้องเรียก return value ออกจาก function ว่า “result” เสมอ แบบนั้นแล้วผมจะรู้บทบาทของมันเสมอ จากนั้นผมก็ compile, test, และ commit อีกครั้ง แล้วค่อยจัดการกับ argument ตัวแรก
function statement…
function amountFor(aPerformance, play) {
let result = 0;
switch (play.type) {
case "tragedy":
result = 40000;
if (aPerformance.audience > 30) {
result += 1000 * (aPerformance.audience - 30);
}
break;
case "comedy":
result = 30000;
if (aPerformance.audience > 20) {
result += 10000 + 500 * (aPerformance.audience - 20);
}
result += 300 * aPerformance.audience;
break;
default:
throw new Error(`unknown type: ${play.type}`);
}
return result;
}
อีกครั้ง นี่คือการทำตามสไตล์การเขียนโค้ดของผม ด้วยภาษาที่ type แบบ dynamic อย่าง JavaScript การจดจำ type ของตัวแปรไว้มีประโยชน์—ผมจึงตั้งชื่อ parameter โดยรวม type ไว้ในชื่อเป็นค่าเริ่มต้น ผมใช้คำนำหน้านาม (a/an) เว้นแต่จะมีข้อมูลเกี่ยวกับบทบาทเฉพาะบางอย่างที่ควรใส่ลงในชื่อ ผมเรียนรู้ธรรมเนียมนี้จาก Kent Beck [ Beck SBPP ] และยังคงเห็นว่ามันมีประโยชน์เรื่อยมา
ใครก็ตามที่โง่พอเขียน code ที่คอมพิวเตอร์เข้าใจได้ โปรแกรมเมอร์ที่ดีเขียน code ที่มนุษย์เข้าใจได้
การเปลี่ยนชื่อนี้คุ้มกับความพยายามไหม? แน่นอนที่สุด code ที่ดีควรสื่อสารอย่างชัดเจนว่ามันกำลังทำอะไรอยู่ และชื่อ variable คือกุญแจสู่ code ที่ชัดเจน อย่ากลัวที่จะเปลี่ยนชื่อเพื่อเพิ่มความชัดเจน ด้วยเครื่องมือ find-and-replace ที่ดี มันมักจะไม่ยาก การ test และ static typing ในภาษาที่รองรับ จะช่วยชี้จุดที่คุณมองข้ามไป และด้วยเครื่องมือ refactoring อัตโนมัติ การเปลี่ยนชื่อแม้แต่ function ที่ใช้กันอย่างแพร่หลายก็เป็นเรื่องง่ายดาย
สิ่งต่อไปที่คิดจะเปลี่ยนชื่อคือ parameter play แต่ผมมีชะตากรรมอื่นรอมันอยู่
Removing the play Variable (กำจัดตัวแปร play)
เมื่อผมพิจารณา parameter ของ amountFor ผมจะดูว่ามันมาจากไหน aPerformance มาจาก variable ของ loop ดังนั้นมันจึงเปลี่ยนไปตาม iteration ของ loop ตามธรรมชาติ แต่ play คำนวณมาจาก performance ดังนั้นจึงไม่จำเป็นต้องส่งมันเข้ามาเป็น parameter เลย—ผมแค่คำนวณมันใหม่ภายใน amountFor ก็ได้ เวลาผมย่อย function ที่เป็น Long Function ผมชอบกำจัด variable แบบ play เพราะ temporary variable สร้างชื่อที่อยู่ใน local scope มากมาย ซึ่งทำให้การแยกโค้ดซับซ้อนขึ้น Refactoring ที่ผมจะใช้ตรงนี้คือ Replace Temp with Query ( 178 ) .
ผมเริ่มด้วยการแยกส่วนขวาของ assignment ออกเป็น function
function statement…
function playFor(aPerformance) {
return plays[aPerformance.playID];
}
top level…
function statement (invoice, plays) {
let totalAmount = 0;
let volumeCredits = 0;
let result = `Statement for ${invoice.customer}\n`;
const format = new Intl.NumberFormat("en-US",
{ style: "currency", currency: "USD",
minimumFractionDigits: 2 }).format;
for (let perf of invoice.performances) {
const play = playFor(perf);
let thisAmount = amountFor(perf, play);
// add volume credits
volumeCredits += Math.max(perf.audience - 30, 0);
// add extra credit for every ten comedy attendees
if ("comedy" === play.type) volumeCredits += Math.floor(perf.audience / 5);
// print line for this order
result += ` ${play.name}: ${format(thisAmount/100)} (${perf.audience} seats)\n`;
totalAmount += thisAmount;
}
result += `Amount owed is ${format(totalAmount/100)}\n`;
result += `You earned ${volumeCredits} credits\n`;
return result;
ผม compile-test-commit แล้วจึงใช้ Inline Variable ( 123 ) .
top level…
function statement (invoice, plays) {
let totalAmount = 0;
let volumeCredits = 0;
let result = `Statement for ${invoice.customer}\n`;
const format = new Intl.NumberFormat("en-US",
{ style: "currency", currency: "USD",
minimumFractionDigits: 2 }).format;
for (let perf of invoice.performances) {
const play = playFor(perf);
let thisAmount = amountFor(perf, playFor(perf));
// add volume credits
volumeCredits += Math.max(perf.audience - 30, 0);
// add extra credit for every ten comedy attendees
if ("comedy" === playFor(perf).type) volumeCredits += Math.floor(perf.audience / 5);
// print line for this order
result += ` ${playFor(perf).name}: ${format(thisAmount/100)} (${perf.audience} seats)\n`;
totalAmount += thisAmount;
}
result += `Amount owed is ${format(totalAmount/100)}\n`;
result += `You earned ${volumeCredits} credits\n`;
return result;
ผม compile-test-commit พอ inline แล้ว ผมก็ใช้ Change Function Declaration ( 124 ) กับ amountFor เพื่อลบ parameter play ออก ผมทำเป็นสองขั้นตอน ขั้นแรก ใช้ฟังก์ชันใหม่ภายใน amountFor .
function statement…
function amountFor(aPerformance, play) {
let result = 0;
switch (playFor(aPerformance).type) {
case "tragedy":
result = 40000;
if (aPerformance.audience > 30) {
result += 1000 * (aPerformance.audience - 30);
}
break;
case "comedy":
result = 30000;
if (aPerformance.audience > 20) {
result += 10000 + 500 * (aPerformance.audience - 20);
}
result += 300 * aPerformance.audience;
break;
default:
throw new Error(`unknown type: ${playFor(aPerformance).type}`);
}
return result;
}
ผม compile-test-commit แล้วจึงลบ parameter ทิ้ง
top level…
function statement (invoice, plays) {
let totalAmount = 0;
let volumeCredits = 0;
let result = `Statement for ${invoice.customer}\n`;
const format = new Intl.NumberFormat("en-US",
{ style: "currency", currency: "USD",
minimumFractionDigits: 2 }).format;
for (let perf of invoice.performances) {
let thisAmount = amountFor(perf, playFor(perf));
// add volume credits
volumeCredits += Math.max(perf.audience - 30, 0);
// add extra credit for every ten comedy attendees
if ("comedy" === playFor(perf).type) volumeCredits += Math.floor(perf.audience / 5);
// print line for this order
result += ` ${playFor(perf).name}: ${format(thisAmount/100)} (${perf.audience} seats)\n`;
totalAmount += thisAmount;
}
result += `Amount owed is ${format(totalAmount/100)}\n`;
result += `You earned ${volumeCredits} credits\n`;
return result;
function statement…
function amountFor(aPerformance, play) {
let result = 0;
switch (playFor(aPerformance).type) {
case "tragedy":
result = 40000;
if (aPerformance.audience > 30) {
result += 1000 * (aPerformance.audience - 30);
}
break;
case "comedy":
result = 30000;
if (aPerformance.audience > 20) {
result += 10000 + 500 * (aPerformance.audience - 20);
}
result += 300 * aPerformance.audience;
break;
default:
throw new Error(`unknown type: ${playFor(aPerformance).type}`);
}
return result;
}
แล้วก็ compile-test-commit อีกครั้ง
Refactoring นี้ทำให้โปรแกรมเมอร์บางคนตกใจ เดิมที code ที่ใช้หาข้อมูล play ถูกเรียกครั้งเดียวในแต่ละรอบของ loop แต่ตอนนี้มันถูกเรียกสามครั้ง ผมจะพูดถึงความสัมพันธ์ระหว่าง refactoring และ performance ทีหลัง แต่ตอนนี้ขอแค่สังเกตว่าการเปลี่ยนนี้ไม่น่าจะกระทบ performance อย่างมีนัยสำคัญ และต่อให้กระทบ การปรับปรุง performance ของ code base ที่ถูกจัดโครงสร้างมาอย่างดีแล้วก็ทำได้ง่ายกว่ามาก
ประโยชน์ใหญ่ของการกำจัด local variable คือมันทำให้การแยกโค้ดทำได้ง่ายขึ้นมาก เพราะมี local scope ให้จัดการน้อยลง ที่จริงแล้ว ปกติผมจะเก็บ local variable ออกก่อนที่จะแยกโค้ดอะไรทั้งสิ้น
พอจัดการ argument ของ amountFor เสร็จ ผมก็ย้อนกลับไปดูจุดที่มันถูกเรียก มันถูกใช้เพื่อตั้งค่า temporary variable ที่ไม่มีการแก้ค่าอีกต่อไป ผมจึงใช้ Inline Variable ( 123 ) .
top level…
function statement (invoice, plays) {
let totalAmount = 0;
let volumeCredits = 0;
let result = `Statement for ${invoice.customer}\n`;
const format = new Intl.NumberFormat("en-US",
{ style: "currency", currency: "USD",
minimumFractionDigits: 2 }).format;
for (let perf of invoice.performances) {
// add volume credits
volumeCredits += Math.max(perf.audience - 30, 0);
// add extra credit for every ten comedy attendees
if ("comedy" === playFor(perf).type) volumeCredits += Math.floor(perf.audience / 5);
// print line for this order
result += ` ${playFor(perf).name}: ${format(amountFor(perf)/100)} (${perf.audience} seats)\n`;
totalAmount += amountFor(perf);
}
result += `Amount owed is ${format(totalAmount/100)}\n`;
result += `You earned ${volumeCredits} credits\n`;
return result;
Extracting Volume Credits (การแยกการคำนวณ Volume Credits)
นี่คือสถานะปัจจุบันของ body ของ function statement :
top level…
function statement (invoice, plays) {
let totalAmount = 0;
let volumeCredits = 0;
let result = `Statement for ${invoice.customer}\n`;
const format = new Intl.NumberFormat("en-US",
{ style: "currency", currency: "USD",
minimumFractionDigits: 2 }).format;
for (let perf of invoice.performances) {
// add volume credits
volumeCredits += Math.max(perf.audience - 30, 0);
// add extra credit for every ten comedy attendees
if ("comedy" === playFor(perf).type) volumeCredits += Math.floor(perf.audience / 5);
// print line for this order
result += ` ${playFor(perf).name}: ${format(amountFor(perf)/100)} (${perf.audience} seats)\n`;
totalAmount += amountFor(perf);
}
result += `Amount owed is ${format(totalAmount/100)}\n`;
result += `You earned ${volumeCredits} credits\n`;
return result;
ตอนนี้ผมได้ประโยชน์จากการกำจัด variable play แล้ว เพราะมันทำให้การแยกการคำนวณ volume credits ทำได้ง่ายขึ้น ด้วยการกำจัด variable ที่อยู่ใน local scope ตัวหนึ่งออกไป
ผมยังต้องจัดการกับอีกสองตัวที่เหลือ เหมือนเดิม perf ส่งเข้าไปได้ง่าย ๆ แต่ volumeCredits ซับซ้อนกว่านิดหน่อย เพราะมันเป็น accumulator ที่ถูกแก้ค่าในทุก ๆ รอบของ loop ทางที่ดีที่สุดของผมคือ initialize ตัวแปรเงาของมันภายใน function ที่แยกออกมา แล้วค่อย return มันออกมา
function statement…
function volumeCreditsFor(perf) {
let volumeCredits = 0;
volumeCredits += Math.max(perf.audience - 30, 0);
if ("comedy" === playFor(perf).type) volumeCredits += Math.floor(perf.audience / 5);
return volumeCredits;
}
top level…
function statement (invoice, plays) {
let totalAmount = 0;
let volumeCredits = 0;
let result = `Statement for ${invoice.customer}\n`;
const format = new Intl.NumberFormat("en-US",
{ style: "currency", currency: "USD",
minimumFractionDigits: 2 }).format;
for (let perf of invoice.performances) {
volumeCredits += volumeCreditsFor(perf);
// print line for this order
result += ` ${playFor(perf).name}: ${format(amountFor(perf)/100)} (${perf.audience} seats)\n`;
totalAmount += amountFor(perf);
}
result += `Amount owed is ${format(totalAmount/100)}\n`;
result += `You earned ${volumeCredits} credits\n`;
return result;
ผมลบ comment ที่ไม่จำเป็นออก (ซึ่งในกรณีนี้มันชวนเข้าใจผิดจริง ๆ ด้วย)
ผม compile-test-commit กับสิ่งที่ทำมา แล้วจึงเปลี่ยนชื่อ variable ภายใน function ใหม่
function statement…
function volumeCreditsFor(aPerformance) {
let result = 0;
result += Math.max(aPerformance.audience - 30, 0);
if ("comedy" === playFor(aPerformance).type) result += Math.floor(aPerformance.audience / 5);
return result;
}
ผมแสดงมันเป็นขั้นตอนเดียว แต่จริง ๆ แล้วเหมือนครั้งก่อน ผมเปลี่ยนชื่อทีละชื่อ และ compile-test-commit หลังการเปลี่ยนแต่ละครั้ง
Removing the format Variable (กำจัดตัวแปร format)
ลองดู method หลัก statement อีกครั้ง:
top level…
function statement (invoice, plays) {
let totalAmount = 0;
let volumeCredits = 0;
let result = `Statement for ${invoice.customer}\n`;
const format = new Intl.NumberFormat("en-US",
{ style: "currency", currency: "USD",
minimumFractionDigits: 2 }).format;
for (let perf of invoice.performances) {
volumeCredits += volumeCreditsFor(perf);
// print line for this order
result += ` ${playFor(perf).name}: ${format(amountFor(perf)/100)} (${perf.audience} seats)\n`;
totalAmount += amountFor(perf);
}
result += `Amount owed is ${format(totalAmount/100)}\n`;
result += `You earned ${volumeCredits} credits\n`;
return result;
อย่างที่ผมบอกไว้ก่อนหน้านี้ temporary variable อาจเป็นปัญหาได้ มันมีประโยชน์เฉพาะภายใน routine ของตัวเองเท่านั้น ดังนั้นมันจึงส่งเสริมให้ routine ยาวและซับซ้อน ขั้นต่อไปของผมคือแทนที่ variable พวกนั้นบางตัว ตัวที่ง่ายที่สุดคือ format นี่เป็นกรณีของการ assign function ให้กับ temp ซึ่งผมชอบแทนที่ด้วยการประกาศเป็น function แบบปกติ
function statement…
function format(aNumber) {
return new Intl.NumberFormat("en-US",
{ style: "currency", currency: "USD",
minimumFractionDigits: 2 }).format(aNumber);
}
top level…
function statement (invoice, plays) {
let totalAmount = 0;
let volumeCredits = 0;
let result = `Statement for ${invoice.customer}\n`;
for (let perf of invoice.performances) {
volumeCredits += volumeCreditsFor(perf);
// print line for this order
result += ` ${playFor(perf).name}: ${format(amountFor(perf)/100)} (${perf.audience} seats)\n`;
totalAmount += amountFor(perf);
}
result += `Amount owed is ${format(totalAmount/100)}\n`;
result += `You earned ${volumeCredits} credits\n`;
return result;
ถึงแม้การเปลี่ยนจาก variable ที่เก็บ function ไปเป็นการประกาศ function ปกติจะถือเป็น refactoring แต่ผมไม่ได้ตั้งชื่อมัน และไม่รวมมันไว้ในแคตตาล็อก มี refactoring หลายตัวที่ผมรู้สึกว่าไม่สำคัญพอจะใส่ไว้ ตัวนี้ทั้งทำง่ายและค่อนข้างพบได้ยาก ผมจึงไม่คิดว่ามันคุ้มที่จะใส่
ผมไม่ค่อยชอบชื่อนี้—“format” ไม่ได้สื่อความหมายว่ามันกำลังทำอะไรได้มากพอ “formatAsUSD” จะยาวเกินไป เพราะมันถูกใช้ใน string template โดยเฉพาะภายใน scope เล็ก ๆ แบบนี้ ผมคิดว่าประเด็นที่ควรเน้นตรงนี้คือมันกำลังจัดรูปแบบจำนวนเงินเป็นสกุลเงิน ผมจึงเลือกชื่อที่สื่อแบบนั้นและใช้ Change Function Declaration ( 124 ) .
top level…
function statement (invoice, plays) {
let totalAmount = 0;
let volumeCredits = 0;
let result = `Statement for ${invoice.customer}\n`;
for (let perf of invoice.performances) {
volumeCredits += volumeCreditsFor(perf);
// print line for this order
result += ` ${playFor(perf).name}: ${usd(amountFor(perf))} (${perf.audience} seats)\n`;
totalAmount += amountFor(perf);
}
result += `Amount owed is ${usd(totalAmount)}\n`;
result += `You earned ${volumeCredits} credits\n`;
return result;
function statement…
function usd(aNumber) {
return new Intl.NumberFormat("en-US",
{ style: "currency", currency: "USD",
minimumFractionDigits: 2 }).format(aNumber/100);
}
การตั้งชื่อทั้งสำคัญและยุ่งยาก การแตก function ใหญ่ให้เป็น function เล็ก ๆ จะเพิ่มคุณค่าก็ต่อเมื่อชื่อดี ถ้าชื่อดี ผมก็ไม่ต้องอ่าน body ของ function เพื่อดูว่ามันทำอะไร แต่การตั้งชื่อให้ถูกต้องตั้งแต่ครั้งแรกนั้นยาก ผมจึงใช้ชื่อที่ดีที่สุดที่นึกออก ณ ตอนนั้น และไม่ลังเลที่จะเปลี่ยนชื่อมันทีหลัง บ่อยครั้งที่ต้องผ่าน code บางชิ้นเป็นรอบที่สองก่อนจะรู้ว่าชื่อที่ดีที่สุดจริง ๆ คืออะไร
ระหว่างที่เปลี่ยนชื่อ ผมก็ย้ายการหารด้วย 100 ที่ซ้ำซ้อนเข้าไปใน function ด้วย การเก็บเงินเป็นจำนวนเต็มเซนต์เป็นแนวทางที่พบได้ทั่วไป—มันเลี่ยงอันตรายของการเก็บค่าเงินที่มีเศษสตางค์เป็น float แต่ก็ยังให้ผมใช้ operator ทางคณิตศาสตร์ได้ อย่างไรก็ตาม เมื่อใดที่ผมอยากแสดงตัวเลขจำนวนเต็มแบบเพนนีนั้น ผมต้องใช้ทศนิยม function จัดรูปแบบของผมจึงควรจัดการการหารให้
Removing Total Volume Credits (กำจัดตัวแปร Total Volume Credits)
variable เป้าหมายตัวต่อไปของผมคือ volumeCredits นี่เป็นกรณีที่ซับซ้อนกว่า เพราะมันถูกสะสมระหว่าง iteration ของ loop ขั้นแรกของผมคือใช้ Split Loop ( 227 ) เพื่อแยกการสะสมค่า volumeCredits ออกมา
top level…
function statement (invoice, plays) {
let totalAmount = 0;
let volumeCredits = 0;
let result = `Statement for ${invoice.customer}\n`;
for (let perf of invoice.performances) {
// print line for this order
result += ` ${playFor(perf).name}: ${usd(amountFor(perf))} (${perf.audience} seats)\n`;
totalAmount += amountFor(perf);
}
for (let perf of invoice.performances) {
volumeCredits += volumeCreditsFor(perf);
}
result += `Amount owed is ${usd(totalAmount)}\n`;
result += `You earned ${volumeCredits} credits\n`;
return result;
พอทำแบบนั้นเสร็จ ผมก็ใช้ Slide Statements ( 223 ) เพื่อย้าย declaration ของ variable ไปไว้ติดกับ loop
top level…
function statement (invoice, plays) {
let totalAmount = 0;
let result = `Statement for ${invoice.customer}\n`;
for (let perf of invoice.performances) {
// print line for this order
result += ` ${playFor(perf).name}: ${usd(amountFor(perf))} (${perf.audience} seats)\n`;
totalAmount += amountFor(perf);
}
let volumeCredits = 0;
for (let perf of invoice.performances) {
volumeCredits += volumeCreditsFor(perf);
}
result += `Amount owed is ${usd(totalAmount)}\n`;
result += `You earned ${volumeCredits} credits\n`;
return result;
การรวบรวมทุกอย่างที่แก้ค่า variable volumeCredits ไว้ด้วยกันทำให้การใช้ Replace Temp with Query ( 178 ) ทำได้ง่ายขึ้น เหมือนครั้งก่อน ขั้นแรกคือใช้ Extract Function ( 106 ) กับการคำนวณโดยรวมของ variable
function statement…
function totalVolumeCredits() {
let volumeCredits = 0;
for (let perf of invoice.performances) {
volumeCredits += volumeCreditsFor(perf);
}
return volumeCredits;
}
top level…
function statement (invoice, plays) {
let totalAmount = 0;
let result = `Statement for ${invoice.customer}\n`;
for (let perf of invoice.performances) {
// print line for this order
result += ` ${playFor(perf).name}: ${usd(amountFor(perf))} (${perf.audience} seats)\n`;
totalAmount += amountFor(perf);
}
let volumeCredits = totalVolumeCredits();
result += `Amount owed is ${usd(totalAmount)}\n`;
result += `You earned ${volumeCredits} credits\n`;
return result;
เมื่อแยกทุกอย่างออกมาเสร็จแล้ว ผมก็ใช้ Inline Variable ( 123 ) :
top level…
function statement (invoice, plays) {
let totalAmount = 0;
let result = `Statement for ${invoice.customer}\n`;
for (let perf of invoice.performances) {
// print line for this order
result += ` ${playFor(perf).name}: ${usd(amountFor(perf))} (${perf.audience} seats)\n`;
totalAmount += amountFor(perf);
}
result += `Amount owed is ${usd(totalAmount)}\n`;
result += `You earned ${totalVolumeCredits()} credits\n`;
return result;
ขอหยุดสักครู่เพื่อพูดถึงสิ่งที่เพิ่งทำไป ประการแรก ผมรู้ว่าผู้อ่านจะกังวลเรื่อง performance กับการเปลี่ยนนี้อีกครั้ง เพราะหลายคนระแวงการวน loop ซ้ำ แต่ส่วนใหญ่แล้ว การรัน loop แบบนี้อีกครั้งมีผลต่อ performance เพียงเล็กน้อยจนแทบมองไม่เห็น ถ้าคุณจับเวลาการทำงานของ code ก่อนและหลัง refactoring นี้ คุณคงไม่เห็นความเปลี่ยนแปลงด้านความเร็วที่มีนัยสำคัญ— และนั่นคือสิ่งที่เกิดขึ้นเป็นปกติ โปรแกรมเมอร์ส่วนใหญ่ แม้กระทั่งคนที่มีประสบการณ์ มักตัดสินได้ไม่ดีว่า code ทำงานอย่างไรจริง ๆ สัญชาตญาณหลายอย่างของเราถูกหักล้างด้วย compiler อัจฉริยะ เทคนิค caching สมัยใหม่ และอื่น ๆ Performance ของ software มักขึ้นอยู่กับ code เพียงไม่กี่ส่วน และการเปลี่ยนที่อื่นไม่ได้สร้างความแตกต่างที่รับรู้ได้
แต่ “ส่วนใหญ่” ไม่เหมือนกับ “ทุกครั้ง” บางครั้ง refactoring อาจมีนัยสำคัญต่อ performance ถึงอย่างนั้น ผมก็มักจะลงมือทำมัน เพราะการปรับแต่ง performance ของ code ที่ถูกจัดโครงสร้างมาอย่างดีทำได้ง่ายกว่ามาก ถ้าผมสร้างปัญหา performance ที่มีนัยสำคัญระหว่าง refactoring ผมจะใช้เวลาปรับแต่ง performance ทีหลัง อาจนำไปสู่การย้อน refactoring บางอย่างที่ทำไว้ก่อนหน้า—แต่ในกรณีส่วนใหญ่ เนื่องจากการ refactoring ผมกลับสามารถใช้เทคนิคปรับปรุง performance ที่ได้ผลกว่าได้แทน สุดท้ายผมได้ code ที่ทั้งชัดเจนกว่าและเร็วกว่า
ดังนั้น คำแนะนำโดยรวมของผมเรื่อง performance กับการ refactoring คือ: ในกรณีส่วนใหญ่คุณควรเพิกเฉยต่อมัน ถ้า refactoring ของคุณทำให้ช้าลง ให้ refactor ให้เสร็จก่อน แล้วค่อยปรับแต่ง performance ทีหลัง
ประเด็นที่สองที่อยากให้คุณสังเกตคือขั้นตอนที่ใช้กำจัด volumeCredits นั้นเล็กเพียงใด นี่คือสี่ขั้นตอน แต่ละขั้นตอนตามด้วยการ compile, test, และ commit ลง repository code ในเครื่องของผม:
-
Split Loop ( 227 ) เพื่อแยกการสะสมค่าออกมา
-
Slide Statements ( 223 ) เพื่อย้าย code initialize ไปไว้ติดกับการสะสมค่า
-
Extract Function ( 106 ) เพื่อสร้างฟังก์ชันสำหรับคำนวณยอดรวม
-
Inline Variable ( 123 ) เพื่อกำจัดตัวแปรให้หมดไป
ผมสารภาพว่าผมไม่ได้ใช้ขั้นตอนสั้น ๆ แบบนี้เสมอไป—แต่เมื่อใดที่สิ่งต่าง ๆ เริ่มยาก ปฏิกิริยาแรกของผมคือก้าวให้สั้นลง โดยเฉพาะอย่างยิ่ง ถ้า test ล้มเหลวระหว่าง refactoring และผมหาสาเหตุกับแก้ไขไม่ได้ในทันที ผมจะย้อนกลับไปยัง commit ดี ๆ ครั้งล่าสุด แล้วทำสิ่งที่เพิ่งทำใหม่ด้วยขั้นตอนที่เล็กลง วิธีนั้นใช้ได้ผลเพราะผม commit ถี่มาก และเพราะขั้นตอนเล็ก ๆ คือกุญแจสู่การเคลื่อนที่อย่างรวดเร็ว โดยเฉพาะเวลาทำงานกับ code ยาก ๆ
จากนั้นผมก็ทำลำดับเดิมซ้ำเพื่อกำจัด totalAmount ผมเริ่มด้วยการ split loop (compile-test-commit) จากนั้น slide การ initialize variable (compile-test-commit) แล้วจึงแยก function ออกมา มีจุดสะดุดอยู่อย่างหนึ่ง: ชื่อที่ดีที่สุดสำหรับ function คือ “totalAmount” แต่นั่นคือชื่อของ variable และผมไม่สามารถมีทั้งคู่พร้อมกันได้ ผมจึงตั้งชื่อมั่ว ๆ ให้ function ใหม่ตอนแยกมันออกมา (และ compile-test-commit)
function statement…
function appleSauce() {
let totalAmount = 0;
for (let perf of invoice.performances) {
totalAmount += amountFor(perf);
}
return totalAmount;
}
top level…
function statement (invoice, plays) {
let result = `Statement for ${invoice.customer}\n`;
for (let perf of invoice.performances) {
result += ` ${playFor(perf).name}: ${usd(amountFor(perf))} (${perf.audience} seats)\n`;
}
let totalAmount = appleSauce();
result += `Amount owed is ${usd(totalAmount)}\n`;
result += `You earned ${totalVolumeCredits()} credits\n`;
return result;
จากนั้นผม inline variable (compile-test-commit) และเปลี่ยนชื่อ function ให้สมเหตุสมผลขึ้น (compile-test-commit)
top level…
function statement (invoice, plays) {
let result = `Statement for ${invoice.customer}\n`;
for (let perf of invoice.performances) {
result += ` ${playFor(perf).name}: ${usd(amountFor(perf))} (${perf.audience} seats)\n`;
}
result += `Amount owed is ${usd(totalAmount())}\n`;
result += `You earned ${totalVolumeCredits()} credits\n`;
return result;
function statement…
function totalAmount() {
let totalAmount = 0;
for (let perf of invoice.performances) {
totalAmount += amountFor(perf);
}
return totalAmount;
}
ผมยังถือโอกาสเปลี่ยนชื่อภายใน function ที่แยกออกมาให้เป็นไปตามธรรมเนียมของผมด้วย
function statement…
function totalAmount() {
let result = 0;
for (let perf of invoice.performances) {
result += amountFor(perf);
}
return result;
}
function totalVolumeCredits() {
let result = 0;
for (let perf of invoice.performances) {
result += volumeCreditsFor(perf);
}
return result;
}