DEV Community

Todsapon Boontap
Todsapon Boontap

Posted on

 

Builder: design pattern

สวัสดีครับ Devs ถ้าเรื่อง code quality สำคัญสำหรับคุณ เราคือเพื่อนกัน

Devs เรา code กันมา เราน่าจะเคยเห็น class ที่การจะสร้าง instance ของพี่เขาเนี่ย
require parameters เยอะ หรือบาง instance ต้องการการ set runtime config ค่าบางอย่างเพื่อให้เขาทำงานได้ถูกต้อง ดังตัวอย่างง่ายๆ ดังนี้

ClassGenerator มีหน้าที่ gen code ออกมาเป็น string ธรรมดา
ตาม config ที่มีให้อย่างในภาพด้านล่าง

Alt Text

จากภาพสังเกตุว่าใน function generate จะมีส่วนที่มีปัญหานิดหน่อย

Alt Text

ตรงนี้
ถ้าเกิดเรา config parentClass แต่ไม่กำหนด isExtends เป็น true
code ที่ gen ออกมาก็จะไม่ มีสวน extends parent class ให้
ซึ่งมันไม่ใช่ expected behavior

ซึ่งสิ่งที่อาจเป็นปัญหาคร่าวๆ คือ

  1. Devs คนอื่นๆ หรือ ตัวเราเอง ที่ใช้ object นี้ต่ออาจลืม setter บางตัวได้
  2. จากข้อบน อาจทำให้เกิด unexpected behavior ได้

ทีนี้ Builder pattern จะมาช่วยเราอย่างไรบ้าง
โดยตาม theory บอกว่า

  • builder ทำให้การสร้าง หรือ config object ที่มีความ complex ให้ง่ายขึ้น
  • builder นั้นเป็นอิสระจาก object อื่นๆด้วยครับ

Welcome Builder class

Alt Text

สังเกตุว่า class Builder นี้ใน function parentClass
ผมกำหนดให้ไปเลยว่า ถ้ามีการ set parent class เข้ามา
isExtends ต้องเป็น true เลย ซึ่งก็จะลดความซับซ้อน ไปได้ครับ

ซึ่งวิธีการเรียกใช้เป็นแบบนี้

Alt Text

code เราที่เขียน เพื่อนมาดูต่อก็ จะรู้สึก มีอารยธรรมครับผม

ทีนี้ด้วยความเป็นคนจุกจิก ไม่พอใจอะไรง่ายๆ ครับ ฮ่าๆ
แล้วมันทำได้ดีกว่านี้อีกไหม ?
คำตอบคือได้ครับ

ขอแนะนำให้รู้จักสิ่งที่เรียกว่า Fluent Builder pattern
ซึ่งเขาก็คือ builder แหละ แต่เป็น style ที่สวยขึ้น useful มากกว่า
โดยเราจะ implement ได้ดังนี้

Alt Text

ซึ่งสิ่งที่เราเพิ่มเติมขึ้น เราให้ class builder นี้ return ตัวเขาเองออกมาทุกครั้ง
เพื่อให้เราสามารถ ทำ chain configuration ได้ เพื่อให้เราเรียกใช้ แบบนี้ได้ครับ

Alt Text

เป็นงัยบ้างครับ สำหรับ Builder pattern
ทีนี้เรารู้จักการเขียนแบบนี้ Team เรา หรือเราจาก อนาคต
จะรู้สึกว่าได้ร่วมงานกับ คนที่มีอารธรรมที่สูงส่งกว่าครับ

หวังว่าเพื่อนๆ Devs จะลองเอาไป implement กันดูนะครับ

Top comments (0)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!