การรัน Experiment ด้วย SDK
การรัน experiment โดยตรงในโค้ด
หัวข้อที่มีชื่อว่า “การรัน experiment โดยตรงในโค้ด”GrowthBook มีสองวิธีในการรัน A/B experiment:
- Feature-flag experiment — คุณสร้าง Feature ใน GrowthBook UI, ผูก Experiment rule เข้าไป แล้วอ่าน variation ด้วย
gb.getFeatureValue()โดย logic การ assign จะอยู่ใน GrowthBook - Inline experiment ด้วย
gb.run()— คุณนิยาม experiment ทั้งหมดในโค้ด แล้วส่งให้ SDK โดยไม่จำเป็นต้องมี feature rule ใน UI
gb.run() มีประโยชน์เมื่อคุณต้องการทดลองกับสิ่งที่ไม่ได้แมปกับ feature flag โดยตรง หรือเมื่อคุณต้องการ prototype อย่างรวดเร็วโดยไม่ต้องตั้งค่าใน GrowthBook UI ทั้งหมด
result object
หัวข้อที่มีชื่อว่า “result object”gb.run() คืนค่า result object ที่มีสามคุณสมบัติหลัก:
| คุณสมบัติ | ชนิด | คำอธิบาย |
|---|---|---|
result.value | string / number / boolean | ค่า variation ที่ assign ให้ผู้ใช้คนนี้ |
result.inExperiment | boolean | true ถ้าผู้ใช้ถูก assign เข้า variation bucket สำเร็จ |
result.variationId | number | index ของ variation ที่ถูก assign (เริ่มที่ 0) |
เมื่อ result.inExperiment เป็น false แสดงว่าผู้ใช้อยู่นอก experiment (เช่น traffic coverage น้อยกว่า 100% หรือ experiment หยุดแล้ว) ในกรณีนั้น result.value จะเป็นองค์ประกอบแรกใน array variations เสมอ — ที่เป็น default ที่ปลอดภัย
ตัวอย่าง inline experiment
หัวข้อที่มีชื่อว่า “ตัวอย่าง inline experiment”snippet ด้านล่างนี้ initialise SDK แล้วเรียก gb.run() เพื่อ assign ผู้ใช้ไปยัง variation ของสีปุ่ม:
import { GrowthBook } from '@growthbook/growthbook';
const gb = new GrowthBook({
apiHost: 'https://cdn.growthbook.io',
clientKey: 'sdk-YOUR_KEY',
});
await gb.init({ timeout: 2000 });
const result = gb.run({
key: 'button-color-test',
variations: ['blue', 'green'],
});
if (result.inExperiment) {
console.log('Variation:', result.value);
// result.value is 'blue' or 'green'
} else {
// User is not in the experiment — use default
console.log('Not in experiment');
}ข้อแลกเปลี่ยน
หัวข้อที่มีชื่อว่า “ข้อแลกเปลี่ยน”| ตัวเลือก | Benefit | Cost |
|---|---|---|
| Feature-flag experiment | เชื่อม logic เข้ากับโค้ดที่มีอยู่ ยืดหยุ่นกว่า | ต้องแก้โค้ดเพื่อเชื่อม experiment |
| Visual editor experiment | ไม่ต้องแก้โค้ด | จำกัดกับการเปลี่ยน UI เท่านั้น |
ข้อผิดพลาดที่พบบ่อย
หัวข้อที่มีชื่อว่า “ข้อผิดพลาดที่พบบ่อย”- เรียก
getFeatureValueโดยไม่ระบุ stable user attribute ทำให้ assignment ไม่เสถียรข้าม session - ไม่ track exposure event ทำให้ analysis ไม่มีข้อมูล
- mix การ implement หลาย SDK version ในโค้ดเดียวกันทำให้ behavior ไม่ตรงกัน
💡 ตัวอย่างจากของจริง
ทีม engineering ที่ Spotify เชื่อม experiment เข้ากับ feature flag ที่มีอยู่แล้วเสมอ แทนสร้าง experiment แยกต่างหาก เพื่อลด code path ที่ต้อง maintain