What Are Large Functions Anyway? (ฟังก์ชันขนาดใหญ่คืออะไรกันแน่?)

ลองนึกภาพฟังก์ชัน gi ของผมจากเมื่อนานมาแล้วอีกครั้ง สมมติว่ามันถูกเขียนด้วย Java และเริ่มต้นแบบนี้:

public class GraphicInterpreter {
  public void gi() {
    int i;
    int j;

    …
  }
}

ขณะที่เราเลื่อนดูโค้ด 3,000 บรรทัดของฟังก์ชัน gi เราสังเกตเห็นคำสั่ง if หนึ่งคำสั่ง:

    if (…) {
      …
      i++;
      j++;
      …
    }

เราตัดสินใจว่าอยากจะดึงเนื้อหาภายในคำสั่ง if นั้นออกมาเป็นเมธอดใหม่ เราจึงเลือกเนื้อหาด้วยเมาส์ แล้วเรียกใช้เมนู Extract Method แต่ IDE กลับแจ้งว่าไม่สามารถดึงเมธอดนั้นออกมาได้ เพราะโค้ดมีการแก้ไขตัวแปรโลคัลถึง สอง ตัว ถ้าโค้ดแก้ไขตัวแปรโลคัลเพียงตัวเดียว IDE ก็คงสามารถคืนค่าตัวแปรใหม่จาก เมธอดที่ดึงออกมาได้ แต่ IDE ไม่มีวิธีที่ดีในการคืนค่าตัวแปรสองตัวพร้อมกัน (ก็นี่มันภาษา Java ไม่ใช่ Go นี่นา)

แล้วเราควรทำอย่างไร? เราจะดึงเนื้อหาภายในคำสั่ง if นั้นออกมาเป็นฟังก์ชันใหม่ได้อย่างไร? ลองทำแบบนี้ดูไหม:

public class GraphicInterpreter {
  private int i;
  private int j;

  public void gi() {
    …
    if (…) {
      …
      i++;
      j++;
      …
    }
  }
}

ผมรู้ว่าคุณกำลังคิดอะไรอยู่: "โอ้ไม่นะ! คุณเลื่อนตัวแปรโลคัลขึ้นไปเป็นตัวแปรอินสแตนซ์! นี่มันละเมิด encapsulation ชัดๆ!" ก็จริงครับ ผมทำแบบนั้น แต่ตอนนี้ผมสามารถดึงเนื้อหาภายในคำสั่ง if ของผมออกมาเป็นฟังก์ชันใหม่ได้ เพราะตัวแปรทั้งสองยังคงอยู่ในสโคปภายในคลาส:

public class GraphicInterpreter {
  private int i;
  private int j;
  public void gi() {

    …
    if (…) {
      f();
    }
  }

  private void f() {
    …
    i++;
    j++;
    …
  }
}

มาทำแบบนี้ต่อไปเรื่อยๆ กันเถอะ เราพบคำสั่ง if และ while อีกมากมายที่เนื้อหาภายในเข้าไปจัดการกับ i และ j ซึ่งเราสามารถดึงออกมาได้ เราดึงเนื้อหาที่ย่อหน้าเข้าไปทีละชั้นออกมาเรื่อยๆ แล้วผลลัพธ์คืออะไร?

ผลลัพธ์คือกลุ่มเมธอดจำนวนมากที่ใช้ตัวแปรอินสแตนซ์ i และ j แล้วคุณเรียกอะไรที่มีเมธอดหลายตัวคอยจัดการกับชุดตัวแปรชุดหนึ่ง? คุณก็เรียกมันว่า คลาส ใช่ไหมล่ะ?

ทีนี้ ลองคิดเรื่องนี้ให้ดีๆ

ฟังก์ชันขนาดใหญ่ทุกตัวแท้จริงแล้วกำลังซ่อนคลาส (หรือมากกว่านั้น) เอาไว้ข้างในของมัน

เพราะฟังก์ชันขนาดใหญ่ทุกตัวมีชุดตัวแปรโลคัลและชุดของบล็อกที่ย่อหน้าเข้าไปซึ่งจัดการกับตัวแปร เหล่านั้น ตัวแปรเหล่านั้นควรจะเป็นฟิลด์ของคลาสจริงๆ และบล็อกที่ย่อหน้าเข้าไปเหล่านั้นควรจะเป็นเมธอดของ คลาสนั้น

แต่ขอยืมสไตล์ของ George Carlin สักหน่อย บางทีผมอาจจะไปไกลเกินไปและเร็วเกินไปสักนิด งั้นมาดูตัวอย่างกันดีกว่า

ขอแนะนำตัวอย่าง Video Store อันโด่งดังจากหนังสือ Refactoring ฉบับพิมพ์ครั้งแรกอันยอดเยี่ยมของ Martin Fowler ย้อนกลับไปปี 1999 Martin เขียนตัวอย่างเล็กๆ นี้ด้วยภาษา Java แต่ในที่นี้เราจะมาดูมันในภาษา Go แทน แต่ไม่ต้องกลัวไป ถ้าคุณ ไม่รู้จัก Go ก็เข้าใจได้ไม่ยากเลย

อันดับแรกคือเทสต์ ซึ่ง Martin ไม่ได้ รวมไว้ในหนังสือของเขาเมื่อนานมาแล้ว

———customer_test.go———
package GoVideoStore

import (
  "testing"
)

var customer *Customer

func setup() {
  customer = NewCustomer("Fred")
}

func assertEquals(t *testing.T, expected string, statement string) {
  if statement != expected {
    t.Errorf("\nExpected:\n%s\n\nGot:\n%s", expected, statement)
  }
}

func TestSingleNewReleaseStatement(t *testing.T) {
  setup()
  customer.addRental(NewRental(NewMovie("The Cell", NewRelease), 3))
  assertEquals(t,
    "Rental Record for Fred\n"+
      "\tThe Cell\t9.0\n"+
      "Amount owed is 9.0\n"+
      "You earned 2 frequent renter points",
    customer.statement())
}

func TestDualNewReleaseStatement(t *testing.T) {
  setup()
  customer.addRental(NewRental(NewMovie("The Cell", NewRelease), 3))
  customer.addRental(NewRental(
                       NewMovie("The Tigger Movie", NewRelease), 3))
  assertEquals(t,
    "Rental Record for Fred\n"+
      "\tThe Cell\t9.0\n"+
      "\tThe Tigger Movie\t9.0\n"+
      "Amount owed is 18.0\n"+
      "You earned 4 frequent renter points",
    customer.statement())
}

func TestSingleChildrensStatement(t *testing.T) {
  setup()
  customer.addRental(NewRental(
                       NewMovie("The Tigger Movie", Childrens), 3))
  assertEquals(t,
    "Rental Record for Fred\n"+
      "\tThe Tigger Movie\t1.5\n"+
      "Amount owed is 1.5\n"+
      "You earned 1 frequent renter points",
    customer.statement())
}

func TestMultipleRegularStatement(t *testing.T) {
  setup()
  customer.addRental(NewRental(
                       NewMovie("Plan 9 from Outer Space", Regular),
                       1))
  customer.addRental(NewRental(NewMovie("8 1/2", Regular), 2))
  customer.addRental(NewRental(NewMovie("Eraserhead", Regular), 3))
  assertEquals(t,
    "Rental Record for Fred\n"+
      "\tPlan 9 from Outer Space\t2.0\n"+
      "\t8 1/2\t2.0\n"+
      "\tEraserhead\t3.5\n"+
      "Amount owed is 7.5\n"+
      "You earned 3 frequent renter points",
    customer.statement())
}

แล้วก็มีโค้ดที่ผ่านเทสต์เหล่านี้ด้วย

———Customer.go———
package GoVideoStore

import "fmt"

type Customer struct {
  name    string
  rentals []*Rental
}

func NewCustomer(name string) *Customer {
  return &Customer{name: name}
}

func (customer *Customer) addRental(rental *Rental) {
  customer.rentals = append(customer.rentals, rental)
}

func (customer *Customer) statement() string {
  totalAmount := 0.0
  frequentRenterPoints := 0
  result := "Rental Record for " + customer.name + "\n"
  for _, rental := range customer.rentals {
    thisAmount := 0.0
    switch rental.movie.movieType {
    case NewRelease:
      thisAmount += float64(rental.daysRented * 3)
    case Regular:
      thisAmount += 2
      if rental.daysRented > 2 {
        thisAmount += float64(rental.daysRented-2) * 1.5
      }
    case Childrens:
      thisAmount += 1.5
      if rental.daysRented > 3 {
        thisAmount += float64(rental.daysRented-3) * 1.5
      }
    }
    frequentRenterPoints++
    if rental.movie.movieType == NewRelease && rental.daysRented > 1 {
      frequentRenterPoints++
    }
    result += fmt.Sprintf("\t%s\t%.1f\n", rental.movie.title, thisAmount)
    totalAmount += thisAmount
  }
  return result +
    fmt.Sprintf(
      "Amount owed is %.1f\nYou earned %d frequent renter points",
      totalAmount, frequentRenterPoints)
}
———Rental.go———
package GoVideoStore

type Rental struct {
  movie      *Movie
  daysRented int
}

func NewRental(movie *Movie, daysRented int) *Rental {
  return &Rental{movie: movie, daysRented: daysRented}
}

———Movie.go———
package GoVideoStore

const (
  Regular int = iota
  NewRelease
  Childrens
)

type Movie struct {
  title     string
  movieType int
}

func NewMovie(title string, movieType int) *Movie {
  return &Movie{title: title, movieType: movieType}
}

สิ่งแรกที่เราจะทำคือจัดการกับเทสต์ก่อน เทสต์เหล่านี้ต้องการการออกแบบที่ดีกว่านี้ เพราะเทสต์เหล่านั้นมันช่าง ยุ่งเหยิง เหลือเกิน! เหตุผลมีดังนี้

  • เทสต์ทั้งหมดดำเนินการผ่าน UI สตริงของ statement คือ UI นั่นเอง และมันไม่คงที่ ฝ่ายการตลาดจะเปลี่ยนสตริงเหล่านั้นได้ตามใจชอบ ตัวอย่างเช่น ถ้าคน ฝ่ายการตลาดบอกว่าหัวข้อของแต่ละ statement ควรเป็น Rental Statement for… แทนที่จะเป็น Rental Record for… เทสต์ทุกตัวก็จะพังและต้องแก้ไข นั่นทำให้เทสต์เปราะบาง ดังนั้น แทนที่จะ ทดสอบรูปแบบของ statement ซ้ำๆ หลายครั้ง เราควรทดสอบมันแค่ครั้งเดียว ส่วนเทสต์อื่นๆ ควรมุ่งเน้นไปที่ ค่าที่คำนวณได้

  • ชื่ออย่าง Fred และ The Cell ไม่ได้บอกอะไรเราเลยว่ากำลังทดสอบอะไรอยู่ ชื่อเหล่านั้นควรถูกเปลี่ยนเพื่อช่วยให้ผู้อ่านเทสต์ เข้าใจว่าเทสต์เหล่านั้นกำลังพูดถึงอะไร โดยทั่วไปแล้ว เทสต์ไม่ควรมีข้อมูลจากระบบจริงอยู่ในนั้น เทสต์ควรมี ข้อมูลที่อธิบายเจตนาของเทสต์นั้นๆ

  • เทสต์เหล่านี้ยืดยาวเกินไป เราน่าจะทำให้มันกระชับขึ้นได้บ้าง โดยใช้ตัวแปรสำหรับหนัง และ composed assertion

———customer_test.go———
package GoVideoStore

import (
  "testing"
)

var customer *Customer
var newRelease1 *Movie
var newRelease2 *Movie
var childrensMovie *Movie
var regular1 *Movie
var regular2 *Movie
var regular3 *Movie

func setup() {
  customer = NewCustomer("Customer Name")
  newRelease1 = NewMovie("New Release 1", NewRelease)
  newRelease2 = NewMovie("New Release 2", NewRelease)
  childrensMovie = NewMovie("Childrens", Childrens)
  regular1 = NewMovie("Regular 1", Regular)
  regular2 = NewMovie("Regular 2", Regular)
  regular3 = NewMovie("Regular 3", Regular)
}

func assertStringsEqual(t *testing.T, expected string, actual string) {
  if actual != expected {
    t.Errorf("\nExpected:\n%s\n\nGot:\n%s", expected, actual)
  }
}

func assertIntsEqual(t *testing.T, expected int, actual int) {
  if actual != expected {
    t.Errorf("\nExpected:%d Got:%d", expected, actual)
  }
}

func assertFloatsEqual(t *testing.T, expected float64, actual float64)
{
  if actual != expected {
    t.Errorf("\nExpected:%f Got:%f", expected, actual)
  }
}

func assertOwedAndPoints(t *testing.T, owed float64, points int) {
  customer.statement()
  assertFloatsEqual(t, owed, customer.totalAmount)
  assertIntsEqual(t, points, customer.frequentRenterPoints)
}

func TestTotalsForOneNewRelease(t *testing.T) {
  setup()
  customer.addRental(NewRental(newRelease1, 3))
  assertOwedAndPoints(t, 9.0, 2)
}

func TestTotalsForTwoNewReleases(t *testing.T) {
  setup()
  customer.addRental(NewRental(newRelease1, 3))
  customer.addRental(NewRental(newRelease2, 3))
  assertOwedAndPoints(t, 18.0, 4)
}

func TestTotalsForOneChildrensMovie(t *testing.T) {
  setup()
  customer.addRental(NewRental(childrensMovie, 3))
  assertOwedAndPoints(t, 1.5, 1)
}

func TestTotalsForManyRegularMovies(t *testing.T) {
  setup()
  customer.addRental(NewRental(regular1, 1))
  customer.addRental(NewRental(regular2, 2))
  customer.addRental(NewRental(regular3, 3))
  assertOwedAndPoints(t, 7.5, 3)
}

func TestStatementFormat(t *testing.T) {
  setup()
  customer.addRental(NewRental(regular1, 1))
  customer.addRental(NewRental(regular2, 2))
  customer.addRental(NewRental(regular3, 3))
  assertStringsEqual(t,
    "Rental Record for Customer Name\n"+
      "\tRegular 1\t2.0\n"+
      "\tRegular 2\t2.0\n"+
      "\tRegular 3\t3.5\n"+
      "Amount owed is 7.5\n"+
      "You earned 3 frequent renter points",
    customer.statement())
}

จำได้ไหมว่าในการพูดคุยเรื่อง gi ตอนที่ผมละเมิด encapsulation ด้วยการย้ายตัวแปรโลคัลบางตัวไปเป็นฟิลด์ของคลาสที่ห่อหุ้มมันไว้? การเปลี่ยนแปลงที่ผมทำ กับเทสต์ทำให้ผมต้องทำแบบเดียวกันกับโค้ดที่ใช้งานจริงด้วย ผมย้ายตัวแปรโลคัล totalAmount และ frequentRenterPoints ไปเป็นตัวแปรอินสแตนซ์ของคลาส Customer

———Customer.go———
…
type Customer struct {
  name                 string
  rentals              []*Rental
  totalAmount          float64
  frequentRenterPoints int
}
…

คุณคงจำได้ว่าเหตุผลที่ผมบอกว่าเราต้องละเมิด encapsulation ก็เพื่อรองรับการดึงฟังก์ชันออกมา ดังนั้น มาลงมือดึงกันเลยดีกว่า คุณกำลังจะได้เห็นผม ดึงจนกว่าจะหมดแรง นี่คือรอบแรก

———Customer.go———
package GoVideoStore

import "fmt"

type Customer struct {
  name                 string
  rentals              []*Rental
  totalAmount          float64
  frequentRenterPoints int
}

func NewCustomer(name string) *Customer {
  return &Customer{name: name}
}

func (customer *Customer) addRental(rental *Rental) {
  customer.rentals = append(customer.rentals, rental)
}

func (customer *Customer) makeStatement() string {
  customer.clearTotals()
  return
    customer.makeHeader() +
    customer.makeDetails() +
    customer.makeFooter()
}

func (customer *Customer) clearTotals() {
  customer.totalAmount = 0.0
  customer.frequentRenterPoints = 0
}

func (customer *Customer) makeHeader() string {
  return "Rental Record for " + customer.name + "\n"
}

func (customer *Customer) makeDetails() string {
  rentalDetails := ""
  for _, rental := range customer.rentals {
    rentalDetails += customer.makeDetail(rental)
  }
  return rentalDetails
}

func (customer *Customer) makeDetail(rental *Rental) string {
  amount := customer.determineAmount(rental)
  customer.frequentRenterPoints += customer.determinePoints(rental)
  customer.totalAmount += amount
  return customer.formatDetail(rental, amount)
}

func (customer *Customer) determineAmount(rental *Rental) float64 {
  amount := 0.0
  switch rental.movie.movieType {
  case NewRelease:
    amount += float64(rental.daysRented * 3)
  case Regular:
    amount += 2
    if rental.daysRented > 2 {
      amount += float64(rental.daysRented-2) * 1.5
    }
  case Childrens:
    amount += 1.5
    if rental.daysRented > 3 {
      amount += float64(rental.daysRented-3) * 1.5
    }
  }
  return amount
}

func (customer *Customer) determinePoints(rental *Rental) int {
  if rental.movie.movieType == NewRelease && rental.daysRented > 1 {
    return 2
  }
  return 1
}

func (customer *Customer)
formatDetail(rental *Rental, amount float64) string {
  return fmt.Sprintf("\t%s\t%.1f\n", rental.getTitle(), amount)
}

func (customer *Customer) makeFooter() string {
  return fmt.Sprintf("Amount owed is %.1f\n"+
    "You earned %d frequent renter points",
    customer.totalAmount, customer.frequentRenterPoints)
}

ผมนึกภาพออกว่าพวกคุณบางคนที่คล่อง Golang คงกำลังวิ่งหนีด้วยความสยดสยองอยู่ตอนนี้ 5 ถ้าใช่ ผมขอโทษด้วย—ผมไม่ใช่โปรแกรมเมอร์ Golang ที่เก่งกาจนัก ส่วนคนอื่นๆ อาจกำลังกรีดร้องขณะวิ่งลงไปตาม ทางเดินเพราะฟังก์ชันเล็กจิ๋วเหล่านั้น เต็มไปหมด อาาาาาร์ก!

5 . ดูหมายเหตุ Future Bob ใกล้ตอนท้ายของตัวอย่างนี้

แต่เดี๋ยวก่อน ย้อนกลับไปตอนนี้เลย แล้วลองอ่านฟังก์ชัน makeStatement นั้นดูอีกที ผมจะรอ

คุณสร้าง statement ได้อย่างไร? คุณล้างค่ารวม (totals) ก่อน แล้วค่อยประกอบ header, details และ footer เข้าด้วยกันเป็น สตริงเดียว

ทีนี้ ถ้าคุณลองคิดดูดี ๆ นั่นคือขั้นตอนระดับสูง (high-level procedure) จริง ๆ แล้วนี่คือขั้นตอนระดับสูงของรายงานส่วนใหญ่ด้วย เพราะรายงานส่วนใหญ่ประกอบไปด้วย header, รายละเอียดชุดหนึ่ง และ footer

ดังนั้น สำหรับใครที่กังวลว่าการแยกฟังก์ชัน (extract) แบบนี้ทั้งหมดจะบดบัง intent ของโค้ด ผมขอบอกว่าสิ่งที่เกิดขึ้นจริงกลับตรงกันข้ามเลย การแยกฟังก์ชันได้ เผยให้เห็น intent ระดับสูงของโค้ดชัดเจนขึ้น และย้ายรายละเอียดระดับล่างไปไว้ในฟังก์ชันอื่นแทน ซึ่งจะไม่มารบกวนคุณอีก ถ้ามีคนบอกให้คุณไปแก้บั๊กใน footer ของ statement นี้ ตอนนี้คุณก็รู้แล้วว่าต้องไปที่ไหน: ฟังก์ชัน makeFooter นั่นเอง

โค้ดนี้สุภาพ มันสุภาพเพราะเมื่อผู้อ่านที่น่าสงสารมองดูโค้ดนี้ แทบไม่มีอะไรต้องถอดรหัสเลย ผู้อ่านไม่ต้องมานั่งจ้องและครุ่นคิดกับสตริง ตัวแปร ลูป และคำสั่ง if ต่าง ๆ แทนที่จะเป็นแบบนั้น ผู้อ่านจะเห็นข้อความ policy ง่าย ๆ ที่พร้อมชี้ทางไปยังคำตอบของคำถามใด ๆ ที่พวกเขาอาจมี

เพราะโค้ดนี้สุภาพ ก็พูดได้อย่างเป็นธรรมว่าโค้ดต้นฉบับนั้นหยาบคาย แล้วเราก็คงไม่อยากหยาบคายกันใช่ไหม ล่ะ?

มาต่อกันเลย จะเห็นได้ง่ายมากว่าจะทำ clearTotals อย่างไร การสร้าง header และ footer ก็ชัดเจนเช่นกัน ส่วนการสร้าง details ก็แค่ทำ loop วนผ่าน rentals ทั้งหมดแล้วเรียก makeDetail เท่านั้นเอง

คุณสร้าง detail ได้อย่างไร? คุณ determine amount ก่อน แล้ว determine points แล้วค่อย format detail โอ้โห! มันจะชัดเจนไปกว่านี้ได้อีกไหม?

การ format detail ก็ชัดเจนพอ ๆ กัน แต่ฟังก์ชัน determine ทั้งสองตัวนั้นมีปัญหาอยู่นิดหน่อย

ลองดูเมธอดทั้งหมดนี้ อาร์กิวเมนต์ตัวแรกจะเป็น customer *Customer เสมอ นี่เป็นแค่วิธีของ Go ในการบอกว่าฟังก์ชันนี้เป็นส่วนหนึ่งของคลาส Customer ทีนี้ลองดู body ของฟังก์ชันทั้งหมด จะสังเกตได้ว่าทุกฟังก์ชันใช้อาร์กิวเมนต์ customer ยกเว้น formatDetail , determineAmount และ determinePoints เราจะจัดการกับ formatDetail กันทีหลัง ตอนนี้ ในฟังก์ชัน determine ทั้งสองตัวมีโค้ดจำนวนมากที่ไม่ได้เกี่ยวข้องกับคลาส Customer ที่มันควรจะสังกัดอยู่เลย ดังนั้น … บางทีมันอาจไม่ได้เป็นของคลาสนั้นก็ได้

แล้วมีอะไรอีกที่ถูกส่งเข้าไปในฟังก์ชัน determine เหล่านั้น? ก็คือ Rental นั่นเอง! ดังนั้นบางทีฟังก์ชัน determine ทั้งสองตัวนี้อาจควรอยู่ในคลาส Rental มาย้ายมันไปกันเลย

———Customer.go———
func (customer *Customer) makeDetail(rental *Rental) string {
  amount := rental.determineAmount()
  customer.frequentRenterPoints += rental.determinePoints()
  customer.totalAmount += amount
  return customer.formatDetail(rental, amount)
}

———Rental.go———
Package GoVideoStore

type Rental struct {
  movie      *Movie
  daysRented int
}

func (rental Rental) getTitle() string {
  return rental.movie.title
}

func (rental Rental) determineAmount() float64 {
  amount := 0.0
  switch rental.movie.movieType {
  case NewRelease:
    amount += float64(rental.daysRented * 3)
  case Regular:
    amount += 2
    if rental.daysRented > 2 {
      amount += float64(rental.daysRented-2) * 1.5
    }
  case Childrens:
    amount += 1.5
    if rental.daysRented > 3 {
      amount += float64(rental.daysRented-3) * 1.5
    }
  }
  return amount
}

func (rental Rental) determinePoints() int {
  if rental.movie.movieType == NewRelease && rental.daysRented > 1 {
    return 2
  }
  return 1
}

func NewRental(movie *Movie, daysRented int) *Rental {
  return &Rental{movie: movie, daysRented: daysRented}
}

เทสต์ทั้งหมดยังผ่านเหมือนเดิมโดยไม่ต้องแก้ไขอะไรเลย เทสต์ไม่รู้เลยว่ามีการเปลี่ยนแปลงพื้นฐานด้าน design เกิดขึ้น นั่นหมายความว่าเทสต์มี design ที่ทนทานต่อการเปลี่ยนแปลงได้!

แต่มีบางอย่างที่มหัศจรรย์ยิ่งกว่านั้นเกิดขึ้น business rules ทั้งหมดที่เคยอยู่ในคลาส Customer ได้ย้ายหนีไปอยู่ที่ Rental หมดแล้ว ตอนนี้คลาส Customer เหลือแค่เรื่องการ format statement เท่านั้น—การคำนวณทางธุรกิจ นอกจากยอดรวมเล็กน้อย ตอนนี้ไปอยู่ใน Rental กันหมดแล้ว

เรื่องนี้ทำให้เกิดคำถามว่าทำไมคลาส Customer ถึงถูกตั้งชื่อแบบนั้น มันไม่ได้เกี่ยวกับ customer อีกต่อไปแล้ว—ถ้ามันเคยเกี่ยวจริง ๆ ตั้งแต่แรก ตอนนี้ทุกอย่างเกี่ยวกับ rental statement ล้วน ๆ ดังนั้นชื่อที่ควรจะเป็นก็คือ: RentalStatement นั่นเอง

———RentalStatement.go———
…
type RentalStatement struct {
  name                 string
  rentals              []*Rental
  totalAmount          float64
  frequentRenterPoints int
}
…

แต่ทีนี้มาลองพิจารณาคลาส Rental กันดูบ้าง ฟังก์ชัน determine ผูกติด (coupled) กับคลาส Rental อย่างมาก เพราะมันใช้ทั้งฟิลด์ movie และ daysRented นั่นบ่งบอกถึง cohesion ที่แข็งแรง แต่อย่างไรก็ตาม ฟังก์ชัน determine ก็ยังผูกติดกับคลาส Movie อย่างมากด้วยเช่นกัน และนั่นเป็นเรื่องที่น่ากังวลอยู่บ้าง

การผูกติดกับ Movie นั้นเป็นเรื่องของ movieType ทั้งหมด ฟิลด์ type นี้ถูกใช้เพื่อเลือก business rules ต่าง ๆ สำหรับคำนวณ amount และ points ดังนั้นทำไมฟิลด์ type และ type constants ถึงอยู่ในคลาส Movie ล่ะ?

เทสต์ต้นฉบับมีเบาะแสอยู่ ถ้าคุณย้อนกลับไปดู คุณจะเห็นว่า "The Tigger Movie" ถูกพิจารณาว่าเป็นทั้ง NewRelease และ Childrens ในเวลาเดียวกัน นั่นบ่งบอกว่าหนังเรื่องหนึ่งสามารถถูกเช่าเป็น new release แล้วภายหลังถูกเช่าเป็นหนังเด็กก็ได้ และนั่นก็บ่งบอกว่าฟิลด์ type จริง ๆ แล้วควรจะเป็นของ Rental มาลองทำแบบนั้นกันดู

———Rental.go———
…
type Rental struct {
  movie      *Movie
  daysRented int
  rentalType int
}

const (
  Regular int = iota
  NewRelease
  Childrens
)
…
func NewRental(movie *Movie, rentalType int, daysRented int) *Rental {
  return &Rental{
    movie:      movie,
    rentalType: rentalType,
    daysRented: daysRented}
}
…

การเปลี่ยนแปลงนี้ส่งผลกระทบต่อเทสต์ เพราะ constructor ของ NewRental ถูกเปลี่ยนให้รวม type เข้าไปด้วย แต่โดยรวมแล้วนี่เป็นการเปลี่ยนแปลงที่รวดเร็วพอสมควร อย่างไรก็ตาม มันทำให้เกิดคำถามอีกข้อหนึ่ง เมื่อใดก็ตามที่คุณมีคำสั่ง switch ที่ทำงานกับ type code นั้น คุณอาจจะอยากพิจารณาใช้ polymorphic dispatch แทน

ทำไมล่ะ? เพราะคำสั่ง switch ก็เหมือนกับหนูเจอร์บิล (gerbil)—ถ้าปล่อยไว้นานพอ มันจะขยายพันธุ์เต็มไปทั่วโค้ดของคุณจนล้นออกมา อันที่จริงตอนนี้ก็มีคำสั่ง switch ตัวน้อย ๆ กำลังเติบโตอยู่ในเมธอด determinePoints แล้วด้วย

ใน Chapter 12 , “ Objects and Data Structures ,” เราจะพูดถึงข้อดีข้อเสียของคำสั่ง switch กัน ตอนนี้ลองมาดูกันว่าจะกำจัดมันออกไปได้ไหมด้วยการสร้าง type hierarchy

———RentalType.go———
package GoVideoStore

type RentalType interface {
  determineAmount(daysRented int) float64
  determinePoints(daysRented int) int
}

———Rental.go———
package GoVideoStore

type Rental struct {
  movie      *Movie
  daysRented int
  rentalType RentalType
}

func (rental Rental) getTitle() string {
  return rental.movie.title
}

func (rental Rental) determineAmount() float64 {
  return rental.rentalType.determineAmount(rental.daysRented)
}

func (rental Rental) determinePoints() int {
  return rental.rentalType.determinePoints(rental.daysRented)
}

func NewRental(movie *Movie,
               rentalType RentalType,
               daysRented int) *Rental {
  return &Rental{
    movie:      movie,
    rentalType: rentalType,
    daysRented: daysRented}
}

———NewReleaseRental.go———
package GoVideoStore

type NewReleaseRental struct{}

func (rentalType NewReleaseRental)
determineAmount(daysRented int) float64 {
  return float64(daysRented * 3)
}

func (rentalType NewReleaseRental) determinePoints(daysRented int) int {
  if daysRented > 1 {
    return 2
  }
  return 1
}

———ChildrensRental.go———
package GoVideoStore

type ChildrensRental struct{}

func (rentalType ChildrensRental)
determineAmount(daysRented int) float64 {
  amount := 1.5
  if daysRented > 3 {
    amount += float64(daysRented-3) * 1.5
  }
  return amount
}

func (rentalType ChildrensRental) determinePoints(daysRented int) int {
  return 1
}

———RegularRental.go———
package GoVideoStore

type RegularRental struct{}

func (rentalType RegularRental) determineAmount(daysRented int) float64
{
  amount := 2.0
  if daysRented > 2 {
    amount += float64(daysRented-2) * 1.5
  }
  return amount
}

func (rentalType RegularRental) determinePoints(daysRented int) int {
  return 1
}

นี่คือการ dispatch แบบ polymorphic ที่สวยงามทีเดียว ตอนนี้กฎธุรกิจทั้งหมดของแต่ละประเภทถูกห่อหุ้ม (encapsulate) ไว้อย่างปลอดภัยภายใน type ของมันเอง และ Rental ก็ไม่สนใจเลยว่ากำลังใช้ type ไหนอยู่ แน่นอนว่า test ต้องเปลี่ยนไปด้วย แต่เปลี่ยนแค่นิดเดียว นี่คือตัวอย่าง หนึ่งเพื่อให้เห็นภาพ

———RentalStatementTest.go———
func TestTotalsForOneNewRelease(t *testing.T) {
  setup()
  statement.addRental(NewRental(newRelease1, NewReleaseRental{}, 3))
  assertOwedAndPoints(t, 9.0, 2)
}

คลาส Movie แทบจะว่างเปล่าเลยตอนนี้

———Movie.go———
package GoVideoStore

type Movie struct {
  title string
}

func NewMovie(title string) *Movie {
  return &Movie{title: title}
}

และคลาส RentalStatement ก็สนใจแค่เรื่องการจัดรูปแบบของใบแจ้งหนี้เท่านั้น—นี่จึงเป็นเหตุผลที่ฟังก์ชัน FormatDetail ควรอยู่ที่นั่น แม้ว่ามันจะไม่ได้ใช้ field ใดๆ ของ RentalStatement เลยก็ตาม

ทีนี้ลองมาพิจารณาสิ่งที่เราเพิ่งทำไปกัน ไดอะแกรมด้านล่างแสดงภาพก่อนและหลัง

Images

ขั้นตอนการทำความสะอาดของเราได้แยกกฎธุรกิจออกจากกฎการจัดรูปแบบ จากนั้นก็ย้าย กฎธุรกิจเหล่านั้นเข้าไปใน Rental ก่อน แล้วค่อยแตกย่อยลงไปเป็น hierarchy แบบ polymorphic เยี่ยมมาก! และระหว่างนั้นเราก็พบว่า ชื่อและแนวคิดบางอย่างผิดพลาด—ซึ่งเป็นเรื่องปกติทีเดียว เวลาที่คุณทำความสะอาดโค้ด คุณจะเห็นสิ่งที่ถูกซ่อนอยู่ มาก่อนหน้านี้

สุดท้ายนี้ สังเกตว่ามีขอบเขตทางสถาปัตยกรรม (architectural boundary) ก่อตัวขึ้นใต้ RentalType ผมไม่ได้วาดมันไว้ แต่คุณควรจะรู้สึกได้ กฎธุรกิจเล็กๆ น้อยๆ เหล่านั้นถูกแยกออก จากนโยบายระดับสูงใน RentalStatement และ Rental ตอนนี้เมื่อความต้องการเปลี่ยนแปลง เราสามารถเพิ่ม RentalType ใหม่ๆ ได้อีกมากมาย และไม่มีโค้ดส่วนไหนต้องเปลี่ยนแปลงเพื่อรองรับการเปลี่ยนแปลงเหล่านั้นเลย นี่คือหลักการ Open–Closed Principle (OCP) ที่ทำงานอยู่

ดังนั้น จำได้ไหมที่ผมบอกว่าฟังก์ชันขนาดใหญ่มักซ่อนคลาสไว้เสมอ? นั่นคือสิ่งที่เราพบที่นี่ ฟังก์ชัน statement ขนาดใหญ่ตัวเดียวในโค้ดต้นฉบับถูกแตกออกและกระจายไปยังคลาสใหม่สามคลาสและคลาสเดิมอีกหนึ่งคลาส

Images Future Bob:

Robert Laszczak บังเอิญไปเจอบน GitHub และเห็นความพยายามอันน้อยนิดกับ Golang ข้างต้น เขาใจดีเสนอ บล็อกโพสต์พร้อมข้อปรับปรุงตัวอย่างนี้ให้สอดคล้องกับสไตล์ทั่วไปของ Golang มากขึ้น คุณสามารถดูได้ ที่ https://threedots.tech/clean-code/ สำหรับตัวผมเอง ในฐานะมือใหม่ด้าน Golang ผมเห็นด้วยกับการเปลี่ยนแปลงส่วนใหญ่ของเขา แต่ผมชอบตั้งชื่อยาวกว่านิดหน่อย และใส่คำนำหน้า getter ของผมด้วย get

Extraction and Classes (การแตกส่วนและคลาส)

ลองพิจารณาโค้ด Java ต่อไปนี้สำหรับแก้สมการกำลังสอง คลาสนี้เป็นเพียง namespace ที่สะดวกสำหรับ ฟังก์ชัน solve

import java.util.Arrays;
import java.util.List;

import static java.util.Arrays.asList;

public class QuadraticFormula {
  public static List<Double> solve(double a, double b, double c) {
    if (a == 0) {
      if (b == 0) {
        return asList();
      }
      return asList(-c / b);
    } else {
      double d = b * b - 4 * a * c;
      if (d > 0) {
        double sqrtd = Math.sqrt(d);
        double x1 = (-b + sqrtd) / (2 * a);
        double x2 = (-b - sqrtd) / (2 * a);
        return asList(x1, x2);
      } else if (d == 0) {
        return asList(-b / (2 * a));
      } else {
        return asList();
      }
    }
  }
}

โค้ดนี้ค่อนข้างตรงไปตรงมา แต่ลองสมมติกันว่ามันซับซ้อนและยุ่งยากกว่าที่แสดงไว้ตรงนี้ และสมมติด้วยว่ามันกำลังจะ เติบโต ไปตามเวลา เราอาจปรับปรุงความอ่านง่ายได้ด้วยการแตกส่วนง่ายๆ สองสามครั้งและตั้งชื่อใหม่บ้าง

import java.util.List;
import static java.util.Arrays.asList;

public class QuadraticFormula {
  public static List<Double> solve(double a, double b, double c) {
    if (a == 0)
      return linearSolution(b, c);
    return quadraticSolution(a, b, c);
  }

  private static List<Double> linearSolution(double b, double c) {
    if (b == 0)
      return asList();
    return asList(-c / b);
  }

  private static
  List<Double> quadraticSolution(double a, double b, double c) {
    double discriminant = b * b - 4 * a * c;
    if (discriminant < 0)
      return complexSolution();
    if (discriminant == 0)
      return singleQuadraticSolution(a, b);
    return twoQuadraticSolutions(a, b, discriminant);
  }

  private static List<Double> complexSolution() {
    return asList();
  }

  private static
  List<Double> singleQuadraticSolution(double a, double b) {
    return asList(-b / (2 * a));
  }

  private static List<Double>
  twoQuadraticSolutions(double a, double b, double discriminant) {
    double sqrtd = Math.sqrt(discriminant);
    double x1 = (-b + sqrtd) / (2 * a);
    double x2 = (-b - sqrtd) / (2 * a);
    return asList(x1, x2);
  }
}

ทีนี้อีกครั้ง เพื่อประโยชน์ในการยกตัวอย่าง เราสมมติว่านี่คือระบบที่ซับซ้อนกว่านี้มากและมีแนวโน้ม จะเติบโต ผมหวังว่าคุณจะเห็นด้วยว่าการแตกส่วนได้ช่วยจัดระเบียบโค้ดให้ดีขึ้นบ้าง จนอาจทำให้บางสิ่ง ที่ซับซ้อนกว่านี้อ่านง่ายขึ้นเล็กน้อย แต่เมื่อทำแบบนี้แล้ว เรากลับพลาดโอกาสที่จะใช้ประโยชน์ จากคลาส แทนที่จะส่ง argument ไปมาระหว่างฟังก์ชันที่แตกออกมาทั้งหมดนั้น เราสามารถโหลดค่าเหล่านั้นเข้าไปใน ตัวแปรภายในคลาสได้

import java.util.List;

import static java.util.Arrays.asList;

public class QuadraticFormula {
  private static double a, b, c, discriminant;

  public static List<Double> solve(double a, double b, double c) {
    QuadraticFormula.a = a;
    QuadraticFormula.b = b;
    QuadraticFormula.c = c;
    if (a == 0)
      return linearSolution();
    return quadraticSolution();
  }

  private static List<Double> linearSolution() {
    if (b == 0)
      return asList();
    return asList(-c / b);
  }

  private static List<Double> quadraticSolution() {
    discriminant = b * b - 4 * a * c;
    if (discriminant < 0)
      return complexSolution();
    if (discriminant == 0)
      return singleQuadraticSolution();
    return twoQuadraticSolutions();
  }

  private static List<Double> complexSolution() {
    return asList();
  }

  private static List<Double> singleQuadraticSolution() {
    return asList(-b / (2 * a));
  }

  private static List<Double> twoQuadraticSolutions() {
    double sqrtd = Math.sqrt(discriminant);
    double x1 = (-b + sqrtd) / (2 * a);
    double x2 = (-b - sqrtd) / (2 * a);
    return asList(x1, x2);
  }
}

วิธีนี้ทำให้ทุกอย่างสะอาดขึ้นเล็กน้อย ในโมดูลที่ซับซ้อนกว่านี้ วิธีนี้อาจทำให้สิ่งต่างๆ สะอาดขึ้น อย่างมาก อย่างไรก็ตาม มันมีความเสี่ยง ตัวแปร static เหล่านั้นอาจถูกทำให้เสียหายได้ในสภาพแวดล้อมแบบ multithreaded ซึ่งแก้ไขได้ง่ายๆ ด้วยการเปลี่ยนฟังก์ชันและตัวแปรทั้งหมดจาก static ให้เป็น instance method และตัวแปรแทน แต่ผมจะไม่กังวลเรื่องนั้นในตัวอย่างนี้

สรุปแล้วก็คือ บางครั้งเมื่อเราแตกฟังก์ชันออกมา มันสะดวกและสะอาดกว่าที่จะปล่อยให้ฟังก์ชันเหล่านั้น สื่อสารกันผ่านตัวแปรใน scope (คลาส) ที่บรรจุมันไว้

ทีนี้ลองมาดูปัญหานี้ในภาษา functional อย่าง Clojure กันบ้าง

(defn quad [a b c]
  (let [discriminant (- (* b b) (* 4 a c))]
    (cond
      (zero? a)
      (if (zero? b)
        []
        [(/ (- c) b)])

      (zero? discriminant)
      [(/ (- b) (* 2 a))]

      (neg? discriminant)
      []

      :else
      (let [sqrt-desc (Math/sqrt discriminant)
            x1 (/ (+ (- b) sqrt-desc) (* 2 a))
            x2 (/ (- (- b) sqrt-desc) (* 2 a))]
        [x1 x2]))))

นี่มันสวยงามมาก ผมคงไม่อยากปรับปรุงมันด้วยการแตกส่วน แต่อีกครั้ง ลองสมมติว่านี่เป็น ฟังก์ชันที่ใหญ่และซับซ้อนกว่านี้มาก เราจะแตกฟังก์ชันเพื่อปรับปรุงมันได้อย่างไร?

(defn quad [a b c]
  (let [discriminant (- (* b b) (* 4 a c))
        linear-solution
        (fn []
          (if (zero? b)
            []
            [(/ (- c) b)]))

        single-solution
        (fn []
          [(/ (- b) (* 2 a))])

        two-solutions
        (fn []
          (let [sqrt-desc (Math/sqrt discriminant)
                x1 (/ (+ (- b) sqrt-desc) (* 2 a))
                x2 (/ (- (- b) sqrt-desc) (* 2 a))]
            [x1 x2]))]

    (cond
      (zero? a) (linear-solution)
      (zero? discriminant) (single-solution)
      (neg? discriminant) []
      :else (two-solutions))))

โอเค ทีนี้เป็นครั้งสุดท้าย ขอย้ำว่าเรากำลังสมมติว่าโมดูลนี้ใหญ่และซับซ้อนกว่านี้ คำสั่ง cond ตัวสุดท้ายนั้นดูดีทีเดียว สังเกตว่าเราไม่ได้ส่ง argument ไปให้ฟังก์ชันที่แตกออกมาเลย เพราะ ฟังก์ชันใน Clojure สร้างวัตถุชนิดหนึ่งที่มีตัวแปรและฟังก์ชันอยู่ใน scope ของมันเอง สังเกตด้วยว่า ตัวแปรเหล่านั้นไม่ใช่ static ดังนั้นความกังวลเรื่อง concurrency ของเราจึงหายไป