Replace Subclass with Delegate (การแทนที่ Subclass ด้วย Delegate)
แผนภาพแสดงการแทนที่ subclass ด้วย delegate อยู่ด้านบน โดย code จริงด้านล่างคือ class Order { get daysToShip() { return this._warehouse.daysToShip; } } class PriorityOrder extends Order { get daysToShip() { return this._priorityPlan.daysToShip; } } code หลัง refactoring คือ class Order { get daysToShip() { return (this._priorityDelegate) ? this._priorityDelegate.daysToShip : this._warehouse.daysToShip; } } class PriorityOrderDelegate { get daysToShip() { return this._priorityPlan.daysToShip } }
Motivation (แรงจูงใจ)
ถ้าผมมี object บางตัวที่มีพฤติกรรมต่างกันไปตามหมวดหมู่ กลไกธรรมชาติที่จะใช้แทนสิ่งนี้คือ inheritance ผมใส่ข้อมูลและพฤติกรรมร่วมทั้งหมดไว้ใน superclass แล้วให้แต่ละ subclass เพิ่มและ override feature ตามที่ ต้องการ ภาษาเชิง object ทำให้การ implement เรื่องนี้ง่าย จึงกลายเป็นกลไกที่คุ้นเคย
แต่ inheritance ก็มีข้อเสีย ข้อที่เห็นได้ชัดที่สุดคือ มันเป็นไพ่ที่ใช้ได้ครั้งเดียว ถ้าผมมีเหตุผลมากกว่าหนึ่งข้อที่ต้องทำให้สิ่งต่าง ๆ แตกต่างกัน ผมจะใช้ inheritance ได้กับแกนของความแตกต่างเพียงแกนเดียวเท่านั้น ดังนั้น ถ้าผมอยากให้พฤติกรรมของคนแตกต่างกัน ตามช่วงอายุและตามระดับรายได้ ผมก็จะได้ subclass สำหรับคนหนุ่มกับคนสูงอายุ หรือคนรวยกับคนจน—แต่ไม่ได้ทั้งสองอย่าง
ปัญหาต่อมาคือ inheritance สร้างความสัมพันธ์ที่ใกล้ชิดมากระหว่าง class การเปลี่ยนแปลงใดก็ตามที่ผมอยากทำกับ parent สามารถทำลาย child ได้ง่าย ๆ ดังนั้นผมจึงต้องระมัดระวังและเข้าใจว่า child สืบทอดจาก superclass อย่างไร ปัญหานี้เลวร้ายลงเมื่อ logic ของสอง class อยู่ในคนละ module และดูแลโดยคนละทีม
Delegation จัดการปัญหาทั้งสองข้อนี้ได้ ผมสามารถ delegate ไปยัง class ต่าง ๆ มากมายด้วยเหตุผลที่ต่างกัน Delegation เป็นความสัมพันธ์ปกติระหว่าง object—ดังนั้นผมจึงมี interface ที่ชัดเจนให้ทำงานด้วย ซึ่ง coupling น้อยกว่า subclassing มาก มันจึงเป็นเรื่องธรรมดาที่จะเจอปัญหาของ subclassing แล้วใช้ Replace Subclass with Delegate
มีหลักการยอดนิยมอยู่ว่า: "Favor object composition over class inheritance" (โดยที่ composition ก็คือ delegation นั่นเอง) หลายคนตีความว่านี่แปลว่า "inheritance เป็นสิ่งอันตราย" และอ้างว่าเราไม่ควรใช้ inheritance เลย ผมใช้ inheritance บ่อย ๆ ส่วนหนึ่งเพราะผมรู้เสมอว่าผมใช้ Replace Subclass with Delegate ได้ ถ้าจำเป็นต้องเปลี่ยนมันทีหลัง Inheritance เป็นกลไกที่มีค่า ซึ่งทำงานได้โดยไม่มีปัญหาส่วนใหญ่ของเวลา ดังนั้นผมจึงหยิบมันขึ้นมาก่อน แล้วค่อยขยับไปใช้ delegation เมื่อมันเริ่มเสียดสี การใช้งานแบบนี้จริง ๆ แล้วสอดคล้องกับหลักการดังกล่าว—ซึ่งมาจากหนังสือ Gang of Four [ gof ] ที่อธิบายว่า inheritance และ composition ทำงานร่วมกันอย่างไร หลักการนี้ถือกำเนิดขึ้นเพื่อตอบโต้การใช้งาน inheritance เกินจำเป็น
ผู้ที่คุ้นเคยกับหนังสือ Gang of Four อาจพบว่าการคิดถึง refactoring นี้ว่าเป็นการแทนที่ subclass ด้วย State หรือ Strategy pattern นั้นช่วยได้มาก pattern ทั้งสองนี้มีโครงสร้างเหมือนกัน กล่าวคืออาศัย host ที่ delegate ไปยัง hierarchy ที่แยกต่างหาก ไม่ใช่ทุกกรณีของ Replace Subclass with Delegate ที่ต้องมี inheritance hierarchy สำหรับ delegate (ดังตัวอย่างแรกด้านล่าง) แต่การตั้ง hierarchy สำหรับ state หรือ strategy มักจะมีประโยชน์
Mechanics (ขั้นตอนการทำ)
-
ถ้ามี caller ของ constructor จำนวนมาก ให้ใช้ Replace Constructor with Factory Function ( 334 ) .
-
สร้าง class ว่างสำหรับ delegate constructor ของมันควรรับข้อมูลเฉพาะของ subclass รวมถึงโดยปกติแล้วจะมีการอ้างกลับ (back-reference) ไปยัง superclass ด้วย
-
เพิ่ม field ใน superclass เพื่อเก็บ delegate
-
แก้การสร้าง subclass เพื่อให้มัน initialize field delegate ด้วย instance ของ delegate
ทำได้ใน factory function หรือใน constructor ถ้า constructor บอกได้อย่างน่าเชื่อถือว่าจะต้องสร้าง delegate ที่ถูกต้องหรือไม่
-
เลือก method ของ subclass ที่จะย้ายไปยัง class delegate
-
ใช้ Move Function ( 198 ) ย้ายมันไปยัง class delegate อย่าลบ code ที่ delegate ออกจากต้นทาง
ถ้า method ต้องการองค์ประกอบที่ควรย้ายไปที่ delegate ก็ย้ายมัน ถ้ามันต้องการองค์ประกอบที่ควรอยู่ที่ superclass ให้เพิ่ม field ใน delegate ที่อ้างถึง superclass
-
ถ้า method ต้นทางมี caller ภายนอก class ให้ย้าย code ที่ delegate ของ method ต้นทางจาก subclass ขึ้นไปที่ superclass โดยมี guard เป็นการตรวจสอบว่า delegate มีอยู่หรือไม่ ถ้าไม่มี ให้ใช้ Remove Dead Code ( 237 ) .
ถ้ามีมากกว่าหนึ่ง subclass และคุณเริ่มมี code ซ้ำกันระหว่างพวกมัน ให้ใช้ Extract Superclass ( 375 ) . ในกรณีนี้ method ที่ delegate บน superclass ต้นทางไม่ต้องมี guard อีกต่อไป ถ้าพฤติกรรม default ถูกย้ายไปที่ delegate superclass แล้ว
-
test
-
ทำซ้ำจนกว่า method ทั้งหมดของ subclass จะถูกย้ายครบ
-
หา caller ทั้งหมดของ constructor ของ subclass แล้วเปลี่ยนให้ใช้ constructor ของ superclass
-
test
-
ใช้ Remove Dead Code ( 237 ) กับ subclass
Example (ตัวอย่าง)
ผมมี class ที่ใช้ทำการจอง (booking) สำหรับโชว์หนึ่ง
class Booking…
constructor(show, date) {
this._show = show;
this._date = date;
}
มี subclass สำหรับการจองแบบพรีเมียม (premium booking) ที่คิดคำนึงถึงของแถมต่าง ๆ ที่มีให้
class PremiumBooking extends Booking…
constructor(show, date, extras) {
super(show, date);
this._extras = extras;
}
มีการเปลี่ยนแปลงอยู่หลายอย่างที่ premium booking ทำกับสิ่งที่มันสืบทอดจาก superclass ตามแบบฉบับของการเขียนโปรแกรมโดยใช้ความแตกต่างแบบนี้ ในบางกรณี subclass จะ override method บน superclass ในบางกรณีมันก็เพิ่ม method ใหม่ที่เกี่ยวข้องกับ subclass เท่านั้น ผมจะไม่ลงรายละเอียดทั้งหมด แต่จะเลือกกรณีที่น่าสนใจสองสามกรณีมาเล่า
อย่างแรกคือ override ธรรมดา การจองทั่วไปมีบริการพูดคุยหลังโชว์ (talkback) แต่เฉพาะในวันที่ไม่ใช่ช่วงพีค
class Booking…
get hasTalkback() {
return this._show.hasOwnProperty('talkback') && !this.isPeakDay;
}
Premium booking override เมธอดนี้เพื่อให้มี talkback ทุกวัน
class PremiumBooking…
get hasTalkback() {
return this._show.hasOwnProperty('talkback');
}
การหาราคา (price) ก็เป็น override ที่คล้ายกัน แต่มีจุดพลิกผันตรงที่ method ของพรีเมียมเรียก method ของ superclass
class Booking…
get basePrice() {
let result = this._show.price;
if (this.isPeakDay) result += Math.round(result * 0.15);
return result;
}
class PremiumBooking…
get basePrice() {
return Math.round(super.basePrice + this._extras.premiumFee);
}
ตัวอย่างสุดท้ายคือตอนที่ premium booking เสนอพฤติกรรมที่ไม่มีบน superclass
class PremiumBooking…
get hasDinner() {
return this._extras.hasOwnProperty('dinner') && !this.isPeakDay;
}
Inheritance ทำงานได้ดีกับตัวอย่างนี้ ผมสามารถเข้าใจ base class ได้โดยไม่ต้องเข้าใจ subclass subclass ถูกนิยามเพียงแค่บอกว่ามันต่างจาก base case อย่างไร—ทั้งลด duplication และสื่อสารอย่างชัดเจนว่าความแตกต่างที่มัน นำเข้ามาคืออะไร
จริง ๆ แล้วมันก็ไม่ได้สมบูรณ์แบบอย่างที่ย่อหน้าเมื่อกี้บอก มีหลายสิ่งในโครงสร้างของ superclass ที่มีเหตุผลเพียงเพราะมี subclass—เช่น method ที่ถูกจัดโครงสร้างมาเพื่อให้ง่ายต่อการ override พฤติกรรมที่ถูกต้องตามชนิด ดังนั้นแม้ส่วนใหญ่ผมจะแก้ base class ได้โดยไม่ต้องเข้าใจ subclass แต่ก็มีบางโอกาสที่การไม่ใส่ใจ subclass แบบนี้จะนำพาผมไปสู่การทำลาย subclass โดยการแก้ superclass อย่างไรก็ตาม ถ้าโอกาสแบบนั้นเกิดขึ้นไม่บ่อยนัก inheritance ก็คุ้มค่า—ขอแค่ผมมี test ที่ดีพอจะจับได้ว่า subclass พัง
ถ้าอย่างนั้นทำไมผมถึงอยากเปลี่ยนสถานการณ์ที่มีความสุขแบบนั้นด้วยการใช้ Replace Subclass with Delegate ล่ะ? Inheritance เป็นเครื่องมือที่ใช้ได้ครั้งเดียว—ดังนั้นถ้าผมมีเหตุผลอื่นที่ต้องใช้ inheritance และคิดว่ามันจะให้ประโยชน์มากกว่า premium booking subclass ผมก็ต้องจัดการ premium booking ด้วยวิธีอื่น และบางทีผมอาจต้องเปลี่ยนจากการจองแบบ default ไปเป็นการจองแบบพรีเมียมแบบ dynamic—เช่น รองรับ method aBooking.bePremium() . ในบางกรณี ผมหลีกเลี่ยงสิ่งนี้ได้โดยการสร้าง object ใหม่ทั้งใบ (ตัวอย่างที่พบบ่อยคือตอนที่ HTTP request โหลดข้อมูลใหม่จาก server) แต่บางครั้งผมจำเป็นต้องแก้ data structure โดยไม่ต้องสร้างมันใหม่จากศูนย์ และการแทนที่การจองเพียงรายการเดียวที่ถูกอ้างถึงจากหลาย ๆ ที่นั้นก็ทำได้ยาก ในสถานการณ์แบบนั้น การยอมให้ booking สลับจาก default เป็นพรีเมียมและกลับไปกลับมาได้นั้นมีประโยชน์
เมื่อความต้องการเหล่านี้ผุดขึ้นมา ผมต้องใช้ Replace Subclass with Delegate ผมมี client ที่เรียก constructor ของ สอง class เพื่อทำการจอง:
booking client
aBooking = new Booking(show,date);
premium client
aBooking = new PremiumBooking(show, date, extras);
การลบ subclass จะเปลี่ยนทั้งหมดนี้ ดังนั้นผมจึงชอบที่จะ encapsulate การเรียก constructor ด้วย Replace Constructor with Factory Function ( 334 ) .
top level…
function createBooking(show, date) {
return new Booking(show, date);
}
function createPremiumBooking(show, date, extras) {
return new PremiumBooking (show, date, extras);
}
booking client
aBooking = createBooking(show, date);
premium client
aBooking = createPremiumBooking(show, date, extras);
ตอนนี้ผมสร้าง class delegate ใหม่ parameter ของ constructor คือ parameter ที่ใช้เฉพาะใน subclass ประกอบกับการอ้างกลับ (back-reference) ไปยัง object booking ผมต้องใช้มันเพราะ method ของ subclass หลายตัว ต้องการเข้าถึงข้อมูลที่เก็บใน superclass Inheritance ทำให้เรื่องนี้ทำได้ง่าย แต่กับ delegate ผมจำเป็นต้องมี back-reference
class PremiumBookingDelegate…
constructor(hostBooking, extras) {
this._host = hostBooking;
this._extras = extras;
}
ตอนนี้ผมเชื่อม delegate ตัวใหม่เข้ากับ object booking โดยการแก้ factory function สำหรับ premium bookings
top level…
function createPremiumBooking(show, date, extras) {
const result = new PremiumBooking (show, date, extras);
result._bePremium(extras);
return result;
}
class Booking…
_bePremium(extras) {
this._premiumDelegate = new PremiumBookingDelegate(this, extras);
}
ผมใช้ underscore นำหน้า _bePremium เพื่อสื่อว่ามันไม่ควรเป็นส่วนหนึ่งของ public interface ของ Booking . แน่นอน ถ้าจุดประสงค์ของการทำ refactoring นี้คือการยอมให้ booking กลายเป็นพรีเมียมได้ มันก็เป็น public method ได้
อีกทางหนึ่ง ผมสามารถทำการเชื่อมต่อทั้งหมดใน constructor ของ Booking ได้ ในการทำเช่นนั้น ผมต้องมีวิธีส่งสัญญาณให้ constructor รู้ว่าเรามี premium booking อาจเป็น parameter พิเศษ หรือแค่การใช้ extras ถ้าผมมั่นใจได้ว่ามันจะถูกส่งมาทุกครั้งที่ใช้กับ premium booking ตรงนี้ผมชอบความชัดเจนของการทำผ่าน factory function มากกว่า
เมื่อโครงสร้างพร้อมแล้ว ก็ถึงเวลาเริ่มย้ายพฤติกรรม กรณีแรกที่ผมจะพิจารณาคือ override ธรรมดาของ hasTalkback . นี่คือ code เดิม:
class Booking…
get hasTalkback() {
return this._show.hasOwnProperty('talkback') && !this.isPeakDay;
}
class PremiumBooking…
get hasTalkback() {
return this._show.hasOwnProperty('talkback');
}
ผมใช้ Move Function ( 198 ) ย้าย method ของ subclass ไปที่ delegate เพื่อให้มันเข้ากับบ้านใหม่ ผมจึงเปลี่ยนเส้นทางการเข้าถึงข้อมูลของ superclass ทั้งหมดผ่านการเรียก _host .
class PremiumBookingDelegate…
get hasTalkback() {
return this._host._show.hasOwnProperty('talkback');
}
class PremiumBooking…
get hasTalkback() {
return this._premiumDelegate.hasTalkback;
}
ผม test เพื่อให้แน่ใจว่าทุกอย่างทำงาน แล้วลบ method ใน subclass ทิ้ง:
class PremiumBooking…
get hasTalkback() {
return this._premiumDelegate.hasTalkback;
}
ผมรัน test ณ จุดนี้ โดยคาดว่าบางตัวจะล้มเหลว
ตอนนี้ผมปิดท้ายการย้ายโดยการเพิ่ม dispatch logic ใน method ของ superclass ให้ใช้ delegate ถ้ามันมีอยู่
class Booking…
get hasTalkback() {
return (this._premiumDelegate)
? this._premiumDelegate.hasTalkback
: this._show.hasOwnProperty('talkback') && !this.isPeakDay;
}
กรณีถัดไปที่ผมจะดูคือ base price
class Booking…
get basePrice() {
let result = this._show.price;
if (this.isPeakDay) result += Math.round(result * 0.15);
return result;
}
class PremiumBooking…
get basePrice() {
return Math.round(super.basePrice + this._extras.premiumFee);
}
กรณีนี้เกือบจะเหมือนเดิม แต่มีจุดพลิกผันคือการเรียก super ที่น่าปวดหัว (ซึ่งพบได้บ่อยมากในกรณีการขยาย subclass แบบนี้) เมื่อผมย้าย code ของ subclass ไปที่ delegate ผมจะต้องเรียกกรณีของ parent—แต่ผมไม่สามารถเรียก this._host._basePrice ตรง ๆ ได้ เพราะจะจบลงด้วยการวนซ้ำไม่รู้จบ (endless recursion)
ผมมีทางเลือกสองสามทางตรงนี้ ทางหนึ่งคือใช้ Extract Function ( 106 ) กับการคำนวณ base เพื่อให้ผมแยก dispatch logic ออกจากการคำนวณราคาได้ (การย้ายที่เหลือก็เหมือนเดิม)
class Booking…
get basePrice() {
return (this._premiumDelegate)
? this._premiumDelegate.basePrice
: this._privateBasePrice;
}
get _privateBasePrice() {
let result = this._show.price;
if (this.isPeakDay) result += Math.round(result * 0.15);
return result;
}
class PremiumBookingDelegate…
get basePrice() {
return Math.round(this._host._privateBasePrice + this._extras.premiumFee);
}
อีกทางหนึ่ง ผมสามารถตีกรอบ method ของ delegate ใหม่ให้เป็นการขยาย method base ได้
class Booking…
get basePrice() {
let result = this._show.price;
if (this.isPeakDay) result += Math.round(result * 0.15);
return (this._premiumDelegate)
? this._premiumDelegate.extendBasePrice(result)
: result;
}
class PremiumBookingDelegate…
extendBasePrice(base) {
return Math.round(base + this._extras.premiumFee);
}
ทั้งสองวิธีใช้ได้ดีพอสมควรตรงนี้ ผมชอบวิธีหลังเล็กน้อยเพราะมันสั้นกว่าเล็กน้อย
กรณีสุดท้ายคือ method ที่มีอยู่บน subclass เท่านั้น
class PremiumBooking…
get hasDinner() {
return this._extras.hasOwnProperty('dinner') && !this.isPeakDay;
}
ผมย้ายมันจาก subclass ไปที่ delegate:
class PremiumBookingDelegate…
get hasDinner() {
return this._extras.hasOwnProperty('dinner') && !this._host.isPeakDay;
}
จากนั้นผมก็เพิ่ม dispatch logic ให้ Booking :
class Booking…
get hasDinner() {
return (this._premiumDelegate)
? this._premiumDelegate.hasDinner
: undefined;
}
ใน JavaScript การเข้าถึง property ที่ไม่ได้ถูกนิยามบน object จะคืนค่า undefined ผมจึงทำแบบนั้นตรงนี้ (ถึงแม้สัญชาตญาณทุกอย่างของผมจะอยากให้มันโยน error ซึ่งจะเป็นเช่นนั้นในภาษาเชิง object แบบ dynamic อื่น ๆ ที่ผมคุ้นเคย)
เมื่อผมย้ายพฤติกรรมทั้งหมดออกจาก subclass ได้แล้ว ผมก็เปลี่ยน factory method ให้คืนค่า superclass—และ เมื่อรัน test แล้วมั่นใจว่าทุกอย่างปกติดี ก็ลบ subclass ทิ้ง
top level…
function createPremiumBooking(show, date, extras) {
const result = new PremiumBooking (show, date, extras);
result._bePremium(extras);
return result;
}
class PremiumBooking extends Booking ...
นี่เป็นหนึ่งใน refactoring ที่ผมรู้สึกว่าการ refactor เพียงอย่างเดียวไม่ได้ทำให้ code ดีขึ้น Inheritance จัดการสถานการณ์นี้ได้ดีมาก ในขณะที่การใช้ delegation ต้องเพิ่ม dispatch logic, การอ้างอิงสองทาง และดังนั้นจึงเพิ่มความซับซ้อนเป็นพิเศษ Refactoring นี้ก็ยังอาจคุ้มค่า เพราะข้อได้เปรียบของการมีสถานะพรีเมียมที่ mutable หรือความจำเป็นที่ต้องใช้ inheritance เพื่อวัตถุประสงค์อื่น อาจมีน้ำหนักมากกว่าข้อเสียของการเสีย inheritance ไป
Example: Replacing a Hierarchy (ตัวอย่าง: การแทนที่ Hierarchy)
ตัวอย่างก่อนหน้านี้แสดงการใช้ Replace Subclass with Delegate กับ subclass ตัวเดียว แต่ผมทำแบบเดียวกันกับ hierarchy ทั้งหมดได้
function createBird(data) {
switch (data.type) {
case 'EuropeanSwallow':
return new EuropeanSwallow(data);
case 'AfricanSwallow':
return new AfricanSwallow(data);
case 'NorweigianBlueParrot':
return new NorwegianBlueParrot(data);
default:
return new Bird(data);
}
}
class Bird {
constructor(data) {
this._name = data.name;
this._plumage = data.plumage;
}
get name() {return this._name;}
get plumage() {
return this._plumage || "average";
}
get airSpeedVelocity() {return null;}
}
class EuropeanSwallow extends Bird {
get airSpeedVelocity() {return 35;}
}
class AfricanSwallow extends Bird {
constructor(data) {
super (data);
this._numberOfCoconuts = data.numberOfCoconuts;
}
get airSpeedVelocity() {
return 40 - 2 * this._numberOfCoconuts;
}
}
class NorwegianBlueParrot extends Bird {
constructor(data) {
super (data);
this._voltage = data.voltage;
this._isNailed = data.isNailed;
}
get plumage() {
if (this._voltage > 100) return "scorched";
else return this._plumage || "beautiful";
}
get airSpeedVelocity() {
return (this._isNailed) ? 0 : 10 + this._voltage / 10;
}
}
ในไม่ช้าระบบนี้จะแยกความแตกต่างครั้งใหญ่ระหว่างนกที่ถูกติดแท็กในธรรมชาติกับนกที่ถูกติดแท็กในกรงเลี้ยง ความแตกต่างนั้นสามารถจำลองเป็น subclass สองตัวของ Bird : WildBird และ CaptiveBird ได้ อย่างไรก็ตาม ผมใช้ inheritance ได้เพียงครั้งเดียว ดังนั้นถ้าผมอยากใช้ subclass สำหรับนกป่าเทียบกับนกในกรง ผมก็ต้องลบ subclass สำหรับสายพันธุ์ทิ้ง
เมื่อมี subclass หลายตัวเกี่ยวข้อง ผมจะจัดการทีละตัว โดยเริ่มจากตัวที่ง่าย—ในกรณีนี้คือ EuropeanSwallow . ผมสร้าง class delegate ที่ว่างเปล่าสำหรับ delegate
class EuropeanSwallowDelegate {
}
ผมยังไม่ใส่ data หรือ back-reference parameter ใด ๆ ตอนนี้ สำหรับตัวอย่างนี้ ผมจะค่อย ๆ แนะนำมันเมื่อจำเป็น
ผมต้องตัดสินใจว่าจะจัดการ initialization ของ field delegate ที่ไหน ตรงนี้ เนื่องจากผมมีข้อมูลทั้งหมดอยู่ใน data argument ตัวเดียวของ constructor ผมจึงตัดสินใจทำใน constructor และเนื่องจากมี delegate หลายตัวที่ผมอาจเพิ่มได้ ผมจึงสร้าง function เพื่อเลือกตัวที่ถูกต้องตาม type code ในเอกสาร
class Bird…
constructor(data) {
this._name = data.name;
this._plumage = data.plumage;
this._speciesDelegate = this.selectSpeciesDelegate(data);
}
selectSpeciesDelegate(data) {
switch(data.type) {
case 'EuropeanSwallow':
return new EuropeanSwallowDelegate();
default: return null;
}
}
ตอนนี้ผมมีโครงสร้างพร้อมแล้ว ผมก็ใช้ Move Function ( 198 ) กับ air speed velocity ของนกนางแอ่นยุโรป
class EuropeanSwallowDelegate…
get airSpeedVelocity() {return 35;}
class EuropeanSwallow…
get airSpeedVelocity() {return this._speciesDelegate.airSpeedVelocity;}
ผมเปลี่ยน airSpeedVelocity บน superclass ให้เรียก delegate ถ้ามันมีอยู่
class Bird…
get airSpeedVelocity() {
return this._speciesDelegate ? this._speciesDelegate.airSpeedVelocity : null;
}
ผมลบ subclass ทิ้ง
class EuropeanSwallow extends Bird {
get airSpeedVelocity() {return this._speciesDelegate.airSpeedVelocity;}
}
top level…
function createBird(data) {
switch (data.type) {
case 'EuropeanSwallow':
return new EuropeanSwallow(data);
case 'AfricanSwallow':
return new AfricanSwallow(data);
case 'NorweigianBlueParrot':
return new NorwegianBlueParrot(data);
default:
return new Bird(data);
}
}
ต่อไปผมจะจัดการกับนกนางแอ่นแอฟริกัน ผมสร้าง class ขึ้นมา ครั้งนี้ constructor ต้องรับ data document
class AfricanSwallowDelegate…
constructor(data) {
this._numberOfCoconuts = data.numberOfCoconuts;
}
class Bird…
selectSpeciesDelegate(data) {
switch(data.type) {
case 'EuropeanSwallow':
return new EuropeanSwallowDelegate();
case 'AfricanSwallow':
return new AfricanSwallowDelegate(data);
default: return null;
}
}
ผมใช้ Move Function ( 198 ) กับ airSpeedVelocity .
class AfricanSwallowDelegate…
get airSpeedVelocity() {
return 40 - 2 * this._numberOfCoconuts;
}
class AfricanSwallow…
get airSpeedVelocity() {
return this._speciesDelegate.airSpeedVelocity;
}
ตอนนี้ผมลบ subclass ของนกนางแอ่นแอฟริกันได้แล้ว
class AfricanSwallow extends Bird {
// all of the body ...
}
function createBird(data) {
switch (data.type) {
case 'AfricanSwallow':
return new AfricanSwallow(data);
case 'NorweigianBlueParrot':
return new NorwegianBlueParrot(data);
default:
return new Bird(data);
}
}
ต่อไปเป็นนกแก้วนอร์เวย์บลู (Norwegian blue) การสร้าง class และการย้าย air speed velocity ใช้ขั้นตอนเดียวกับก่อนหน้านี้ ผมจึงจะโชว์แค่ผลลัพธ์
class Bird…
selectSpeciesDelegate(data) {
switch(data.type) {
case 'EuropeanSwallow':
return new EuropeanSwallowDelegate();
case 'AfricanSwallow':
return new AfricanSwallowDelegate(data);
case 'NorweigianBlueParrot':
return new NorwegianBlueParrotDelegate(data);
default: return null;
}
}
class NorwegianBlueParrotDelegate…
constructor(data) {
this._voltage = data.voltage;
this._isNailed = data.isNailed;
}
get airSpeedVelocity() {
return (this._isNailed) ? 0 : 10 + this._voltage / 10;
}
ดีหมดทุกอย่าง แต่ Norwegian blue ยัง override property plumage ซึ่งเป็นสิ่งที่ผมไม่ต้องจัดการในกรณีอื่น ๆ การ Move Function ( 198 ) ครั้งแรกนั้นง่ายพอสมควร แม้จะต้องแก้ constructor เพื่อใส่ back-reference ไปยังตัวนก
class NorwegianBlueParrot…
get plumage() {
return this._speciesDelegate.plumage;
}
class NorwegianBlueParrotDelegate…
get plumage() {
if (this._voltage > 100) return "scorched";
else return this._bird._plumage || "beautiful";
}
constructor(data, bird) {
this._bird = bird;
this._voltage = data.voltage;
this._isNailed = data.isNailed;
}
class Bird…
selectSpeciesDelegate(data) {
switch(data.type) {
case 'EuropeanSwallow':
return new EuropeanSwallowDelegate();
case 'AfricanSwallow':
return new AfricanSwallowDelegate(data);
case 'NorweigianBlueParrot':
return new NorwegianBlueParrotDelegate(data, this);
default: return null;
}
}
ขั้นตอนที่ซับซ้อนคือวิธีลบ method plumage ใน subclass ทิ้ง ถ้าผมทำแบบนี้
class Bird…
get plumage() {
if (this._speciesDelegate)
return this._speciesDelegate.plumage;
else
return this._plumage || "average";
}
ผมก็จะเจอ error เต็มไปหมด เพราะไม่มี property plumage บน class delegate ของสายพันธุ์อื่น
ผมอาจใช้ conditional ที่เจาะจงกว่านี้:
class Bird…
get plumage() {
if (this._speciesDelegate instanceof NorwegianBlueParrotDelegate)
return this._speciesDelegate.plumage;
else
return this._plumage || "average";
}
แต่ผมหวังว่ามันจะส่งกลิ่นเหม็นของการย่อยสลายนกแก้วให้คุณได้พอ ๆ กับที่มันส่งกลิ่นให้ผม การใช้ class check แบบชัดเจนแบบนี้แทบจะไม่เคยเป็นความคิดที่ดีเลย
อีกทางเลือกหนึ่งคือ implement กรณี default บน delegate ตัวอื่น ๆ
class Bird…
get plumage() {
if (this._speciesDelegate)
return this._speciesDelegate.plumage;
else
return this._plumage || "average";
}
class EuropeanSwallowDelegate…
get plumage() {
return this._bird._plumage || "average";
}
class AfricanSwallowDelegate…
get plumage() {
return this._bird._plumage || "average";
}
แต่นี่ทำให้ method default ของ plumage ซ้ำซ้อนกัน และถ้านั่นยังแย่ไม่พอ ผมยังได้ duplication โบนัสใน constructor ต่าง ๆ สำหรับการกำหนด back-reference อีกด้วย
วิธีแก้ duplication ก็คือ inheritance โดยธรรมชาติ—ผมใช้ Extract Superclass ( 375 ) กับ species delegates:
class SpeciesDelegate {
constructor(data, bird) {
this._bird = bird;
}
get plumage() {
return this._bird._plumage || "average";
}
class EuropeanSwallowDelegate extends SpeciesDelegate {
class AfricanSwallowDelegate extends SpeciesDelegate {
constructor(data, bird) {
super(data,bird);
this._numberOfCoconuts = data.numberOfCoconuts;
}
class NorwegianBlueParrotDelegate extends SpeciesDelegate {
constructor(data, bird) {
super(data, bird);
this._voltage = data.voltage;
this._isNailed = data.isNailed;
}
จริง ๆ แล้ว เมื่อผมมี superclass แล้ว ผมก็ย้ายพฤติกรรม default ใด ๆ จาก Bird ไปยัง SpeciesDelegate ได้ โดยการการันตีว่า field speciesDelegate จะมีค่าอยู่เสมอ
class Bird…
selectSpeciesDelegate(data) {
switch(data.type) {
case 'EuropeanSwallow':
return new EuropeanSwallowDelegate(data, this);
case 'AfricanSwallow':
return new AfricanSwallowDelegate(data, this);
case 'NorweigianBlueParrot':
return new NorwegianBlueParrotDelegate(data, this);
default: return new SpeciesDelegate(data, this);
}
}
// rest of bird's code...
get plumage() {return this._speciesDelegate.plumage;}
get airSpeedVelocity() {return this._speciesDelegate.airSpeedVelocity;}
class SpeciesDelegate…
get airSpeedVelocity() {return null;}
ผมชอบแบบนี้ เพราะมันทำให้ method ที่ delegate บน Bird เรียบง่ายขึ้น ผมเห็นได้ชัดเจนว่าพฤติกรรมใดถูก delegate ไปยัง species delegate และพฤติกรรมใดที่อยู่กับตัว
นี่คือสถานะสุดท้ายของ class เหล่านี้:
function createBird(data) {
return new Bird(data);
}
class Bird {
constructor(data) {
this._name = data.name;
this._plumage = data.plumage;
this._speciesDelegate = this.selectSpeciesDelegate(data);
}
get name() {return this._name;}
get plumage() {return this._speciesDelegate.plumage;}
get airSpeedVelocity() {return this._speciesDelegate.airSpeedVelocity;}
selectSpeciesDelegate(data) {
switch(data.type) {
case 'EuropeanSwallow':
return new EuropeanSwallowDelegate(data, this);
case 'AfricanSwallow':
return new AfricanSwallowDelegate(data, this);
case 'NorweigianBlueParrot':
return new NorwegianBlueParrotDelegate(data, this);
default: return new SpeciesDelegate(data, this);
}
}
// rest of bird's code...
}
class SpeciesDelegate {
constructor(data, bird) {
this._bird = bird;
}
get plumage() {
return this._bird._plumage || "average";
}
get airSpeedVelocity() {return null;}
}
class EuropeanSwallowDelegate extends SpeciesDelegate {
get airSpeedVelocity() {return 35;}
}
class AfricanSwallowDelegate extends SpeciesDelegate {
constructor(data, bird) {
super(data,bird);
this._numberOfCoconuts = data.numberOfCoconuts;
}
get airSpeedVelocity() {
return 40 - 2 * this._numberOfCoconuts;
}
}
class NorwegianBlueParrotDelegate extends SpeciesDelegate {
constructor(data, bird) {
super(data, bird);
this._voltage = data.voltage;
this._isNailed = data.isNailed;
}
get airSpeedVelocity() {
return (this._isNailed) ? 0 : 10 + this._voltage / 10;
}
get plumage() {
if (this._voltage > 100) return "scorched";
else return this._bird._plumage || "beautiful";
}
}
ตัวอย่างนี้แทนที่ subclass ดั้งเดิมด้วย delegate แต่ก็ยังมีโครงสร้าง inheritance ที่คล้ายกันมากใน SpeciesDelegate . ผมได้อะไรจาก refactoring นี้บ้าง นอกจากการปลดปล่อย inheritance บน Bird ? การสืบทอดตามสายพันธุ์ตอนนี้ถูกจำกัดขอบเขตแคบลง ครอบคลุมแค่ข้อมูลและ function ที่แปรผันตามสายพันธุ์เท่านั้น code ใดก็ตามที่เหมือนกันทุกสายพันธุ์ยังคงอยู่บน Bird และ subclass ในอนาคตของมัน
ผมสามารถใช้แนวคิดเดียวกันในการสร้าง delegate superclass กับตัวอย่างการจองเมื่อกี้ได้ ซึ่งจะทำให้ผมแทนที่ method บน Booking ที่มี dispatch logic ด้วยการเรียก delegate ง่าย ๆ และปล่อยให้ inheritance ของมันจัดการเรื่อง dispatch อย่างไรก็ตาม ใกล้ถึงเวลาอาหารเย็นแล้ว ผมจึงจะฝากไว้เป็นแบบฝึกหัดให้ผู้อ่าน
ตัวอย่างเหล่านี้แสดงให้เห็นว่าวลี "Favor object composition over class inheritance" น่าจะพูดได้ดีกว่านี้ว่า "Favor a judicious mixture of composition and inheritance over either alone" —แต่ผมเกรงว่ามันจะไม่ catchy เท่า