Replace Nested Conditional with Guard Clauses (แทนที่เงื่อนไขที่ซ้อนกันด้วย Guard Clauses)

A figure illustrated how the refactoring technique is used to replace the nested conditional expressions with guard clauses.

การแสดงในรูปแบบแผนภาพแสดงคำสั่ง if-else ที่ซ้อนกัน ซึ่งกำลังถูกแทนที่ด้วย guard clauses code จริงอ่านว่า function getPayAmount() { let result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } code หลังการ refactoring อ่านว่า function getPayAmount() { if (isDead) return deadAmount(); if (isSeparated) return separatedAmount(); if (isRetired) return retiredAmount(); return normalPayAmount(); }

Motivation (แรงจูงใจ)

ผมมักพบว่า conditional expressions มาในสองสไตล์ ในสไตล์แรก ทั้งสองแขนงของเงื่อนไขเป็นส่วนหนึ่งของพฤติกรรมปกติ ส่วนในสไตล์ที่สอง แขนงหนึ่งเป็นพฤติกรรมปกติ แต่อีกแขนงหนึ่งบ่งบอกถึงสภาวะที่ไม่ปกติ

conditional สองแบบนี้มีเจตนาที่ต่างกัน—และเจตนานี้ควรปรากฏให้เห็นใน code ถ้าทั้งสองแขนงเป็นส่วนหนึ่งของพฤติกรรมปกติ ผมจะใช้ conditional ที่มีแขนง if และแขนง else แต่ถ้าเงื่อนไขเป็นสภาวะที่ไม่ปกติ ผมจะตรวจสอบเงื่อนไขและ return ทันทีถ้ามันเป็นจริง การตรวจสอบแบบนี้มักถูกเรียกว่า guard clause

ประเด็นสำคัญของ Replace Nested Conditional with Guard Clauses คือการเน้นน้ำหนัก ถ้าผมใช้โครงสร้าง if-then-else แสดงว่าผมกำลังให้น้ำหนักกับแขนง if และแขนง else เท่า ๆ กัน นี่สื่อให้ผู้อ่านเห็นว่าแขนงทั้งสองมีความเป็นไปได้และความสำคัญพอ ๆ กัน ในทางกลับกัน guard clause บอกว่า "นี่ไม่ใช่แก่นของ function นี้ และถ้ามันเกิดขึ้น ให้ทำบางอย่างแล้วออกไป"

ผมมักพบว่าตัวเองใช้ Replace Nested Conditional with Guard Clauses เมื่อทำงานกับโปรแกรมเมอร์ที่ถูกสอนให้ method มีทางเข้า (entry point) และทางออก (exit point) อย่างละหนึ่งจุดเท่านั้น ทางเข้าเพียงจุดเดียวถูกบังคับโดยภาษาโปรแกรมสมัยใหม่อยู่แล้ว แต่ทางออกเพียงจุดเดียวนั้นไม่ใช่กฎที่มีประโยชน์จริง ๆ ความชัดเจนคือหลักการสำคัญ: ถ้า method ชัดเจนกว่าด้วยทางออกจุดเดียว ก็ใช้ทางออกจุดเดียว ไม่เช่นนั้นก็ไม่ต้อง

Mechanics (ขั้นตอนการทำ)

  • เลือกเงื่อนไขที่อยู่ชั้นนอกสุดซึ่งต้องถูกแทนที่ แล้วเปลี่ยนมันให้เป็น guard clause

  • test

  • ทำซ้ำตามความจำเป็น

  • ถ้า guard clauses ทั้งหมด return ผลลัพธ์เดียวกัน ให้ใช้ Consolidate Conditional Expression ( 263 )

Example (ตัวอย่าง)

นี่คือ code สำหรับคำนวณจำนวนเงินที่ต้องจ่ายให้พนักงานคนหนึ่ง มันเกี่ยวข้องเฉพาะตอนที่พนักงานยังทำงานอยู่กับบริษัท ดังนั้นมันจึงต้องตรวจสอบอีกสองกรณีที่ไม่เกี่ยวข้อง

function payAmount(employee) {
  let result;
  if(employee.isSeparated) {
    result = {amount: 0, reasonCode: "SEP"};
  }
  else {
    if (employee.isRetired) {
      result = {amount: 0, reasonCode: "RET"};
    }
    else {
      // logic to compute amount
      lorem.ipsum(dolor.sitAmet);
      consectetur(adipiscing).elit();
      sed.do.eiusmod = tempor.incididunt.ut(labore) && dolore(magna.aliqua);
      ut.enim.ad(minim.veniam);
      result = someFinalComputation();
    }
  }
  return result;
}

การซ้อน conditional ตรงนี้บดบังความหมายที่แท้จริงของสิ่งที่เกิดขึ้น จุดประสงค์หลักของ code นี้ใช้ได้ก็ต่อเมื่อเงื่อนไขเหล่านี้ไม่เป็นจริง ในสถานการณ์แบบนี้ เจตนาของ code จะอ่านเข้าใจได้ชัดเจนกว่าด้วย guard clauses

เช่นเดียวกับการเปลี่ยนแปลง refactoring อื่น ๆ ผมชอบเดินทีละเล็กทีละน้อย ดังนั้นผมจึงเริ่มจากเงื่อนไขบนสุด

function payAmount(employee) {
  let result;
  if (employee.isSeparated) return {amount: 0, reasonCode: "SEP"};
  if (employee.isRetired) {
    result = {amount: 0, reasonCode: "RET"};
  }
  else {
    // logic to compute amount
    lorem.ipsum(dolor.sitAmet);
    consectetur(adipiscing).elit();
    sed.do.eiusmod = tempor.incididunt.ut(labore) && dolore(magna.aliqua);
    ut.enim.ad(minim.veniam);
    result = someFinalComputation();
  }
  return result;
}

ผม test การเปลี่ยนแปลงนั้น แล้วไปต่อที่เงื่อนไขถัดไป

function payAmount(employee) {
  let result;
  if (employee.isSeparated) return {amount: 0, reasonCode: "SEP"};
  if (employee.isRetired)   return {amount: 0, reasonCode: "RET"};
  // logic to compute amount
  lorem.ipsum(dolor.sitAmet);
  consectetur(adipiscing).elit();
  sed.do.eiusmod = tempor.incididunt.ut(labore) && dolore(magna.aliqua);
  ut.enim.ad(minim.veniam);
  result = someFinalComputation();
  return result;
}

ถึงจุดนี้ variable result ไม่ได้ทำอะไรที่เป็นประโยชน์อีกต่อไป ผมจึงลบมันทิ้ง

function payAmount(employee) {
  let result;
  if (employee.isSeparated) return {amount: 0, reasonCode: "SEP"};
  if (employee.isRetired)   return {amount: 0, reasonCode: "RET"};
  // logic to compute amount
  lorem.ipsum(dolor.sitAmet);
  consectetur(adipiscing).elit();
  sed.do.eiusmod = tempor.incididunt.ut(labore) && dolore(magna.aliqua);
  ut.enim.ad(minim.veniam);
  return someFinalComputation();
}

กฎคือ คุณจะได้สตรอว์เบอร์รีเพิ่มอีกหนึ่งลูกทุกครั้งที่ลบ mutable variable (ตัวแปรที่แก้ค่าได้) ทิ้ง

Example: Reversing the Conditions (ตัวอย่าง: การกลับด้านเงื่อนไข)

ตอนที่ทบทวนต้นฉบับของหนังสือรุ่นแรก Joshua Kerievsky ชี้ให้เห็นว่าเรามักทำ Replace Nested Conditional with Guard Clauses โดยการกลับด้าน conditional expressions ยิ่งไปกว่านั้น เขายังยกตัวอย่างให้ผมด้วย ทำให้ผมไม่ต้องตรากตรำจินตนาการเพิ่ม

function adjustedCapital(anInstrument) {
  let result = 0;
  if (anInstrument.capital > 0) {
    if (anInstrument.interestRate > 0 && anInstrument.duration > 0) {
      result = (anInstrument.income / anInstrument.duration) * anInstrument.adjustmentFactor;
    }
  }
  return result;
}

เช่นเดิม ผมแทนที่ทีละอัน แต่ครั้งนี้ผมกลับด้านเงื่อนไขตอนที่ใส่ guard clause เข้าไป

function adjustedCapital(anInstrument) {
  let result = 0;
  if (anInstrument.capital <= 0) return result;
  if (anInstrument.interestRate > 0 && anInstrument.duration > 0) {
    result = (anInstrument.income / anInstrument.duration) * anInstrument.adjustmentFactor;
  }
  return result;
}

conditional ถัดไปซับซ้อนขึ้นอีกหน่อย ผมจึงทำเป็นสองขั้น ขั้นแรก ผมแค่เพิ่ม not เข้าไป

function adjustedCapital(anInstrument) {
  let result = 0;
  if (anInstrument.capital <= 0) return result;
  if (!(anInstrument.interestRate > 0 && anInstrument.duration > 0)) return result;
  result = (anInstrument.income / anInstrument.duration) * anInstrument.adjustmentFactor;
  return result;
}

การทิ้ง not ไว้ใน conditional แบบนั้นทำให้สมองของผมบิดไปมาในมุมที่เจ็บปวด ผมจึงทำให้มันง่ายขึ้น:

function adjustedCapital(anInstrument) {
  let result = 0;
  if (anInstrument.capital <= 0) return result;
  if (anInstrument.interestRate <= 0 || anInstrument.duration <= 0) return result;
  result = (anInstrument.income / anInstrument.duration) * anInstrument.adjustmentFactor;
  return result;
}

บรรทัดทั้งสองมีเงื่อนไขที่ให้ผลลัพธ์เดียวกัน ดังนั้นผมจึงใช้ Consolidate Conditional Expression ( 263 )

function adjustedCapital(anInstrument) {
  let result = 0;
  if (   anInstrument.capital      <= 0
      || anInstrument.interestRate <= 0
      || anInstrument.duration     <= 0) return result;
  result = (anInstrument.income / anInstrument.duration) * anInstrument.adjustmentFactor;
  return result;
}

variable result กำลังทำสองอย่างตรงนี้ ค่าแรกที่ตั้งเป็นศูนย์บ่งบอกว่าควร return อะไรเมื่อ guard clause ทำงาน ส่วนค่าที่สองคือผลลัพธ์การคำนวณสุดท้าย ผมสามารถกำจัดมันได้ ซึ่งทั้งลบการใช้งานซ้ำซ้อนของมันและทำให้ผมได้สตรอว์เบอร์รีมาหนึ่งลูก

function adjustedCapital(anInstrument) {
  if (   anInstrument.capital      <= 0
      || anInstrument.interestRate <= 0
      || anInstrument.duration     <= 0) return 0;
  return (anInstrument.income / anInstrument.duration) * anInstrument.adjustmentFactor;
}