Code Review: คุณภาพโค้ด, Clean Code, Best Practice

Code Review คือกระบวนการตรวจโค้ดเพื่อหาความเสี่ยง ปรับคุณภาพ และสร้างมาตรฐานร่วมกันในทีม โดยเน้นทั้งความถูกต้อง อ่านง่าย ทดสอบได้ และดูแลต่อได้

Timeline/ประวัติศาสตร์

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#fabd2f", "primaryTextColor": "#282828", "primaryBorderColor": "#b57614", "lineColor": "#7c6f64", "secondaryColor": "#83a598", "tertiaryColor": "#b8bb26", "background": "#fbf1c7", "mainBkg": "#ebdbb2", "fontFamily": "Tahoma, sans-serif"}}}%%
flowchart LR
  subgraph Era1["ยุค Review หลังงานเสร็จ / Late Review"]
    A["พบ bug ตอนท้าย
แก้แพง"] end subgraph Era2["ยุค Pull Request / Collaborative Review"] B["PR Review
ตรวจเป็นรอบ"] C["Clean Code
อ่านง่าย"] end subgraph Era3["ยุค Automated Quality / Tooling"] D["ESLint
ตรวจ rule"] E["Prettier
format อัตโนมัติ"] end A --> B --> C --> D --> E

แนวคิดสำคัญ

ตาราง Code Review Checklist

หัวข้อ คำถามตรวจ ตัวอย่างปัญหา
Naming ชื่อสื่อความหมายไหม x, data2
DRY มี logic ซ้ำไหม copy function หลายที่
Responsibility component หนักเกินไหม API logic อยู่ใน component
Error Handling จัดการ error ไหม ไม่มี fallback
Testability test ง่ายไหม dependency ผูกแน่น

Mermaid Diagram: Code Review Loop

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#fabd2f", "primaryTextColor": "#282828", "primaryBorderColor": "#b57614", "lineColor": "#7c6f64", "secondaryColor": "#83a598", "tertiaryColor": "#b8bb26", "background": "#fbf1c7", "mainBkg": "#ebdbb2", "fontFamily": "Tahoma, sans-serif"}}}%%
flowchart TD
  A["Open Pull Request
เปิด PR"] --> B["Automated Checks
lint/test"] B --> C["Reviewer Reads Code
อ่านโค้ด"] C --> D["Feedback
ข้อเสนอแนะ"] D --> E["Author Updates
แก้ไข"] E --> B B --> F["Approve & Merge
ผ่านและรวม"]

Code Example

// bad-example.ts
// ตัวอย่างที่อ่านยากและทำหลายหน้าที่ใน function เดียว
function doIt(x: any[]) {
  return x.filter(i => i.active).map(i => i.name);
}
// good-example.ts
// แยกชื่อให้สื่อความหมาย และกำหนด type ชัดเจน
interface User {
  name: string;
  active: boolean;
}

function getActiveUserNames(users: User[]): string[] {
  return users
    .filter(user => user.active)
    .map(user => user.name);
}

// ตัวอย่างการใช้งาน:
const names = getActiveUserNames([
  { name: 'Ana', active: true },
  { name: 'Bob', active: false }
]);
console.log(names); // ['Ana']
{
  "scripts": {
    "lint": "ng lint",
    "format": "prettier --write \"src/**/*.{ts,html,css}\""
  }
}

วิดีโอแนะนำ

กิจกรรมท้ายบท

กลับสัปดาห์ที่ 15