# สัปดาห์ที่ 6: รีวิว (Static Testing - Reviews) และ การวิเคราะห์แบบสแตติก (Static Analysis)

## 📑 สารบัญ (Table of Contents)

1. [จุดประสงค์การเรียนรู้](#จุดประสงค์การเรียนรู้)
2. [Static Testing vs Dynamic Testing](#1-static-testing-vs-dynamic-testing)
3. [เทคนิคการทบทวนโค้ด](#2-code-review-techniques)
4. [เครื่องมือวิเคราะห์แบบสแตติก](#3-static-analysis-tools)
5. [การจัด ห้องปฏิบัติการการทบทวนโค้ด](#4-code-review-meeting)
6. [สรุป & ประเด็นสำคัญ](#สรุป--ประเด็นสำคัญ)

---

## จุดประสงค์การเรียนรู้ (Learning Objectives) {#จุดประสงค์การเรียนรู้}

เมื่อจบบทเรียนนี้ นิสิตจะสามารถ:

1. อธิบายความแตกต่างระหว่าง การทดสอบแบบสแตติก (Static Testing) และ การทดสอบแบบไดนามิก (Dynamic Testing)
2. เลือกใช้เทคนิค การทบทวนโค้ด (Code Review) ที่เหมาะสม
3. ใช้ เครื่องมือวิเคราะห์แบบสแตติก (Static Analysis Tools) เช่น ESLint, Prettier วิเคราะห์คุณภาพโค้ด
4. วางแผนและดำเนินการ การประชุมตรวจสอบโค้ด (Code Inspection Meeting)
5. วิเคราะห์และรายงาน เมตริกซ์ (metrics) จาก Static Analysis

---

## 1: Static Testing vs Dynamic Testing (15 นาที)

### Static Testing คืออะไร?

**การทดสอบซอฟต์แวร์โดยไม่ต้องรันโปรแกรม** - ตรวจสอบผ่าน เอกสาร (documents), รหัสต้นฉบับ (source code), การออกแบบ (design)

### Dynamic Testing คืออะไร?

**การทดสอบซอฟต์แวร์โดยการรันโปรแกรม** - execute code และตรวจสอบผลลัพธ์

### เปรียบเทียบ Static vs Dynamic Testing

| Aspect          | Static Testing                           | Dynamic Testing                      |
| --------------- | ---------------------------------------- | ------------------------------------ |
| **Execution**   | ไม่ต้องรันโค้ด                           | ต้องรันโค้ด                          |
| **เมื่อไหร่ทำ** | ตั้งแต่เริ่มต้นโปรเจกต์                  | หลังมี executable code               |
| **ค้นหาอะไร**   | Defects ในเอกสาร, design, code structure | Functional defects, bugs ตอน runtime |
| **ตัวอย่าง**    | Code review, Inspection, ESLint          | Unit tests, Integration tests        |
| **Cost**        | ต่ำกว่า (find bugs เร็ว)                 | สูงกว่า (find bugs ช้า)              |
| **Coverage**    | Design, architecture, standards          | Functionality, performance           |

### ข้อดีด้านต้นทุน (The Cost Advantage)

```
ต้นทุนในการแก้ข้อบกพร่อง (Cost to Fix Bug (Industry Average)):

Requirements Phase:   $100
Design Phase:         $1,000
Coding Phase:         $10,000
Testing Phase:        $100,000
Production:           $1,000,000+
```

**Static Testing ช่วยจับ bugs ในช่วงแรกๆ = ประหยัดเงินได้มาก**

### ข้อดีหลักของ Static Testing Key Benefits of Static Testing ()

1. **การตรวจหาข้อบกพร่องเร็ว (Early Defect Detection)** - หา bugs ก่อนที่จะมีค่าใช้จ่ายสูง
2. **ป้องกันข้อบกพร่อง (Prevent Defects)** - หยุดปัญหาก่อนที่จะเกิด
3. **ปรับปรุงคุณภาพ (Improve Quality)** - code ที่สะอาด, บำรุงรักษาได้ง่าย (maintainable)
4. **การแบ่งปันความรู้ (Knowledge Sharing)** - ทีมเรียนรู้จากกัน
5. **การปฏิบัติตามมาตรฐาน (Standards Compliance)** - ตรวจสอบว่าทำตามมาตรฐาน

---

## 2: เทคนิคการทบทวนโค้ด (Code Review Techniques) (45 นาที) {#2-code-review-techniques}

### 1. การสำรวจ (Walkthrough)

**คืออะไร:** ผู้เขียนโค้ดนำเสนอผลงานของตนเองให้ทีมฟัง

**กระบวนการ:**

- ผู้เขียน (Author) นำเสนอ code/document
- ผู้เข้าร่วมฟังและถามคำถาม
- ไม่เป็นทางการ (Informal), เน้นด้านการศึกษา (educational focus)
- ไม่มี การบันทึกข้อบกพร่องอย่างเป็นทางการ (formal defect logging)

**ข้อดี:**

- Educational - ทีมเรียนรู้จากกัน
- Flexible - ไม่เป็นทางการมาก
- Good for new team members - ดีสำหรับสมาชิกใหม่

**ข้อเสีย:**

- อาจไม่ค่อยหา defects ได้ดี
- ไม่มี structure มาก

**เมื่อไหร่ใช้:**

- การทบทวนการออกแบบแบบแรก (Early design reviews)
- การโอนความรู้ (knowledge transfer)
- การฝึกอบรม (training)

---

### 2. การทบทวนทางเทคนิค (Technical Review)

**คืออะไร:** การประเมินทางเทคนิคโดยผู้เชี่ยวชาญ

**กระบวนการ:**

- นำโดยผู้ประสานงาน (Led by moderator) (not author)
- เพื่อนทางเทคนิค (Technical peers review)
- เน้นความถูกต้องทางเทคนิค (Focus on technical correctness)
- การตัดสินใจเกี่ยวกับทางเลือก (Decision-making about alternatives)

**ข้อดี:**

- ความลึกทางเทคนิค (Technical depth)
- ความเห็นจากผู้เชี่ยวชาญ (Expert opinions)
- สามารถเสนอทางเลือก (Can propose alternatives)

**ข้อเสีย:**

- ต้องการความเชี่ยวชาญทางเทคนิค (Requires technical expertise)
- ใช้เวลามาก (Time-consuming)

**เมื่อไหร่ใช้:**

- การทบทวนสถาปัตยกรรม (Architecture reviews)
- อัลกอริทึมที่ซับซ้อน (complex algorithms)
- การตัดสินใจทางเทคนิค (technical decisions)

---

### 3. การตรวจสอบตามวิธี Fagan (Fagan Inspection)

**คืออะไร:** Structured review process อย่างเป็นระบบ พัฒนาโดย Michael Fagan (IBM)

**กระบวนการ 6 ขั้นตอน:**

#### 1. **การวางแผน (Planning)**

- Moderator เลือก reviewers
- กำหนดวันเวลา meeting
- แจกจ่าย สื่อการสอน (materials)

#### 2. **ภาพรวม (Overview)** (ถ้าจำเป็น)

- Author อธิบาย บริบท (context)
- ให้ ข้อมูลพื้นฐาน (background information)

#### 3. **การเตรียมการ (Preparation)** (Individual Review)

- แต่ละคน review ล่วงหน้า
- ใช้ รายการตรวจสอบ (checklist)
- บันทึก defects
- **Optimal rate: 150-200 เส้นต่อชั่วโมง (lines/hour)**

#### 4. **การประชุมตรวจสอบ (Inspection Meeting)**

- Reader อ่าน code ทีละส่วน
- Reviewers ชี้ defects
- ผู้จดบันทึก (Scribe) บันทึก defects
- **Meeting: 1-2 ชั่วโมงสูงสุด (hours max)**

#### 5. **การปรับปรุง (Rework)**

- Author แก้ไข defects
- อัปเดตเอกสาร (Update documentation)

#### 6. **ติดตามผล (Follow-up)**

- ยืนยันการแก้ไข (Moderator verify fixes)
- ตรวจสอบว่าแก้ครบถ้วน

### บทบาทในการตรวจสอบ (Inspection Roles)

| Role          | Responsibilities                  |
| ------------- | --------------------------------- |
| **Moderator** | จัดการ process, เป็นกลาง          |
| **Author**    | เจ้าของ work product, ตอบคำถาม    |
| **Reader**    | อ่าน/ถ้อยคำใหม่ (paraphrase) code |
| **Reviewer**  | หา defects ตาม checklist          |
| **Scribe**    | บันทึก defects, issues            |

### 📊 เมตริกซ์ของการตรวจสอบ (Inspection Metrics)

Track ตัวเลขเหล่านี้:

- **เวลาเตรียมการ (Preparation time)** (hours per person)
- **Inspection rate** (lines/hour)
- **Defect density** (defects per KLOC)
- **ประสิทธิภาพการตรวจหาข้อบกพร่อง (Defect detection efficiency)** (% found vs total)

---

### แนวปฏิบัติที่ดีที่สุด (Code Review Best Practices)

#### DO's

1. **ทบทวนส่วนเล็ก ๆ (Review Small Chunks)**
   - 200-400 lines ต่อครั้ง
   - มากเกินไป = พลาดง่าย

2. **ใช้เวลาอย่างเพียงพอ (Take Your Time)**
   - 300-500 lines/hour สำหรับ preparation
   - อย่ารีบร้อน! (Don't rush!)

3. **ใช้รายการตรวจสอบ (Use Checklist)**
   - ครอบคลุมทุก ด้าน (aspect)
   - ทบทวนอย่างสอดคล้อง (consistent review)

4. **เน้นที่โค้ด ไม่ใช่ผู้เขียน (Focus on Code, Not Coder)**
   - ฟังก์ชันนี้สามารถทำให้ง่ายขึ้นได้ ("This function could be simplified")
   - ไม่ใช่ "คุณเขียนโค้ดแย่" (NOT "You wrote bad code")

5. **กำหนดข้อจำกัดเวลา (Set Time Limits)**
   - Meeting: 60-90 minutes max
   - สมองเหนื่อย! (Brain gets tired!)

6. **ยืนยันการแก้ไข (Verify Fixes)**
   - ตรวจสอบว่าแก้ไขถูกต้อง

#### DON'Ts

1. **อย่าเป็นเรื่องส่วนตัว (Don't Make it Personal)**
   - โจมตีโค้ด ไม่ใช่คน (Attack code, not people)

2. **อย่าทบทวนมากเกินไป (Don't Review Too Much)**
   - ไม่มีประสิทธิผล (> 500 lines = ineffective)

3. **อย่าข้ามขั้นตอนเตรียมการ (Don't Skip Preparation)**
   - ประชุมโดยไม่เตรียม = เสียเวลา (Meeting without prep = waste time)

4. **อย่ารีบร้อน (Don't Rush)**
   - คุณภาพสำคัญกว่าความเร็ว (Quality over speed)

5. **อย่าออกแบบในการประชุม (Don't Design in Meeting)**
   - ทำเครื่องหมายปัญหา พูดคุยภายหลัง (Mark issue, discuss later)

---

## 3: เครื่องมือวิเคราะห์แบบสแตติก (Static Analysis Tools) (40 นาที) {#3-static-analysis-tools}

### ทำไมต้องใช้ Automated Static Analysis?

**Manual Review:**

- หาบาง issues ได้ดี (logic, design)
- ช้า, เบื่อ
- พลาด simple issues ง่าย
- ไม่สอดคล้องกัน (inconsistent)

**Automated Tools:**

- เร็ว, consistent
- หา common issues ได้ดี
- พลาด complex logic issues

**Best Approach: ผสมกัน!**

- Tools หา ผลไม้ที่เก็บง่าย (low-hanging fruits)
- มนุษย์เน้นที่ปัญหาที่ซับซ้อน (Humans focus on complex issues)

---

### 🛠️ ESLint - JavaScript Code Analysis

**ESLint คืออะไร:**
Pluggable linting utility สำหรับ JavaScript/TypeScript

**ตรวจสอบอะไรได้:**

- ปัญหาคุณภาพโค้ด (Code quality issues)
- ข้อบกพร่องที่อาจเกิด (Potential bugs)
- การละเมิดรูปแบบ (Style violations)
- ช่องโหว่ความปลอดภัย (Security vulnerabilities)
- การละเมิดแนวปฏิบัติที่ดี (Best practice violations)

#### การติดตั้งและ Config

```bash
# Installation
npm install --save-dev eslint

# Initialize config
npx eslint --init

# หรือใช้ config สำเร็จรูป
npm install --save-dev eslint-config-airbnb-base
```

#### ตัวอย่าง .eslintrc.json

```json
{
  "env": {
    "node": true,
    "es2021": true,
    "jest": true
  },
  "extends": ["eslint:recommended"],
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "rules": {
    "no-console": "warn",
    "no-unused-vars": "error",
    "no-undef": "error",
    "prefer-const": "warn",
    "no-var": "error",
    "eqeqeq": ["error", "always"],
    "curly": ["error", "all"],
    "no-eval": "error",
    "no-implied-eval": "error"
  }
}
```

#### ระดับความรุนแรง (Rule Severity Levels)

- **"off" หรือ 0** - ปิด rule
- **"warn" หรือ 1** - แสดงเตือน (ไม่ fail build)
- **"error" หรือ 2** - แสดง error (fail build)

#### ตัวอย่าง Issues ที่ ESLint หาได้

```javascript
// BAD: Using var
var name = "John";

// GOOD: Use const/let
const name = "John";

// BAD: Unused variable
const unusedVar = "hello";
console.log("something else");

// GOOD: Remove unused
console.log("something else");

// BAD: == instead of ===
if (value == "5") {
}

// GOOD: Use strict equality
if (value === 5) {
}

// BAD: No curly braces
if (condition) return;

// GOOD: Always use braces
if (condition) {
  return;
}

// BAD: eval is dangerous
eval(userInput);

// GOOD: Never use eval
// Find alternative approach
```

---

### 🎨 Prettier - การจัดรูปแบบโค้ด (Code Formatting)

**Prettier คืออะไร:**
Opinionated code formatter - จัด format code ให้สวยงามและ consistent

**ทำไมต้องใช้:**

- รูปแบบที่สอดคล้องในทั้งทีม (Consistent style across team)
- ไม่ต้องถกเรื่อง style
- จัดรูปแบบอัตโนมัติเมื่อบันทึก (Auto-format on save)
- ทำงานกับหลาย ภาษา (languages)

#### การติดตั้ง

```bash
npm install --save-dev prettier
```

#### ตัวอย่าง .prettierrc.json

```json
{
  "semi": true,
  "trailingComma": "es5",
  "singleQuote": true,
  "printWidth": 80,
  "tabWidth": 2,
  "useTabs": false,
  "arrowParens": "always",
  "bracketSpacing": true
}
```

#### การใช้งาน

```bash
# Format specific files
npx prettier --write src/**/*.js

# Check formatting (for CI)
npx prettier --check src/**/*.js

# Format all supported files
npx prettier --write .
```

#### ตัวอย่าง Before/After

```javascript
// BEFORE
function calculateTotal(items) {
  const total = items.reduce((sum, item) => {
    return sum + item.price;
  }, 0);
  return total;
}

// AFTER (Prettier)
function calculateTotal(items) {
  const total = items.reduce((sum, item) => {
    return sum + item.price;
  }, 0);
  return total;
}
```

---

### 🔗 การรวมเข้าด้วยกัน (ESLint + Prettier Integration)

ใช้ร่วมกันได้โดย:

```bash
npm install --save-dev eslint-config-prettier eslint-plugin-prettier
```

**eslint-config-prettier:** ปิด ESLint rules ที่ conflict กับ Prettier  
**eslint-plugin-prettier:** รัน Prettier เป็น ESLint rule

```json
// .eslintrc.json
{
  "extends": ["eslint:recommended", "plugin:prettier/recommended"]
}
```

---

### 📊 Metrics จาก Static Analysis

#### 1. โค๊ดน่าสงสัย (Code Smells)

**เมธอดยาว (Long Method)**

```javascript
// BAD: Method too long (>50 lines)
function processOrder(order) {
  // 100 lines of code...
}

// GOOD: Break into smaller functions
function processOrder(order) {
  validateOrder(order);
  calculateTotal(order);
  applyDiscount(order);
  processPayment(order);
}
```

**โค้ดซ้ำ (Duplicated Code)**

```javascript
// BAD: Copy-paste code
function calculateTotalForBooks() {
  let total = 0;
  books.forEach((book) => {
    total += book.price;
  });
  return total;
}

function calculateTotalForMovies() {
  let total = 0;
  movies.forEach((movie) => {
    total += movie.price;
  });
  return total;
}

// GOOD: DRY principle
function calculateTotal(items) {
  return items.reduce((sum, item) => sum + item.price, 0);
}
```

**คลาส/ไฟล์ใหญ่ (Large Class/File)**

- File >500 lines = ควรแยกออก
- Class มี responsibilities มากเกินไป

#### 2. เมตริกซ์ความซับซ้อน (Complexity Metrics)

**ความซับซ้อนแบบวนรอบ (Cyclomatic Complexity)**

- จำนวน decision paths ในโค้ด
- สูง = ยากต่อการ test และ maintain

```javascript
// Complexity = 4 (3 if statements + 1)
function getDiscount(customer) {
  if (customer.isVIP) {
    // +1
    if (customer.totalSpent > 10000) {
      // +1
      return 0.2;
    }
    return 0.1;
  }
  if (customer.totalSpent > 5000) {
    // +1
    return 0.05;
  }
  return 0;
}
```

**Guidelines:**

- 1-10: Simple, easy to test
- 11-20: ความซับซ้อนปานกลาง (Moderate complexity)
- 21+: ความเสี่ยงสูง ลองปรับโครงสร้างใหม่ (High risk, consider refactoring)

#### 3. หนี้ทางเทคนิค (Technical Debt)

**Definition:** Code ที่ "ทำงานได้" แต่ไม่ดีพอ - จะมีค่าใช้จ่ายในอนาคต

**ตัวอย่าง Technical Debt:**

- ค่าที่เขียนตายตัว (Hardcoded values)
- ไม่มีการจัดการข้อผิดพลาด (No error handling)
- ชื่อที่ไม่ดี (Poor naming)
- ขาดการทดสอบ (Missing tests)
- การพึ่งพาที่เก่าไป (Outdated dependencies)

**Measuring:**

```
Technical Debt Ratio = Remediation Cost / Development Cost × 100%

ถ้า > 5% = ควรจัดการ
```

---

## 4: การประชุมทบทวนโค้ด (Code Review Meeting) (20 นาที) {#4-code-review-meeting}

### การวางแผนการประชุม (Planning the Meeting)

**Before Meeting:**

1. **เลือก Code ที่จะ Review**
   - 200-400 lines
   - มี บริบท (context) ครบ

2. **แจกจ่าย สื่อการสอน (Materials)**
   - Source code
   - เอกสารการออกแบบ (Design documents)
   - Checklist
   - ให้เวลาอ่านล่วงหน้า 24-48 ชม.

3. **เลือก Reviewers (3-6 คน)**
   - ระดับประสบการณ์ที่หลากหลาย (Mixed experience levels)
   - มุมมองที่แตกต่าง (Different perspectives)

### ระหว่างการประชุม (During Meeting)

**Meeting Structure (60-90 minutes):**

1. **บทนำ (Introduction)** (5 min)
   - วัตถุประสงค์ (Objectives)
   - ขอบเขตการทบทวน (Review scope)
   - การเตือนกระบวนการ (Process reminder)

2. **การอ่านโค้ด (Code Reading)** (40-60 min)
   - Reader อ่าน code ทีละส่วน
   - Reviewers ชี้ issues
   - Scribe บันทึก
   - **DON'T design solutions in meeting!**

3. **สรุป (Summary)** (10-15 min)
   - Count defects
   - การจำแนกความร้ายแรง (Severity classification)
   - Action items
   - Follow-up plan

**กฎของการประชุม (Meeting Rules):**

- Focus on finding defects
- เคารพซึ่งกันและกัน (Be respectful)
- ยึดตามข้อจำกัดเวลา (Stick to time limit)
- No solution design
- ไม่โจมตีส่วนตัว (No personal attacks)
- No debugging in meeting

### การจำแนกความร้ายแรงของข้อบกพร่อง (Defect Severity Classification)

| Severity       | Description             | Example                     |
| -------------- | ----------------------- | --------------------------- |
| **Critical**   | System crash, data loss | Null pointer, SQL injection |
| **Major**      | Feature not working     | Login fails, search broken  |
| **Minor**      | Cosmetic, slight impact | Wrong error message         |
| **Suggestion** | Improvement idea        | Better variable name        |

### หลังการประชุม (After Meeting)

**งานของผู้เขียน (Author's Tasks):**

1. Fix defects
2. อัปเดตเอกสาร (Update documentation)
3. Self-review fixes
4. แจ้งให้ผู้ประสานงาน (Notify moderator)

**งานของผู้ประสานงาน (Moderator's Tasks):**

1. ยืนยันการแก้ไข (Verify fixes)
2. มั่นใจว่าแก้ไขทั้งหมด (Ensure all issues addressed)
3. Close review
4. Update metrics

---

## สรุป & ประเด็นสำคัญ (Summary & Key Takeaways) {#สรุป--ประเด็นสำคัญ}

### ประเด็นสำคัญของ Static Testing (Static Testing Key Points)

- ตรวจหาข้อบกพร่องเร็วและราคาต่ำ (Find defects **early** and **cheap**)
- **เสริม (Complement)** dynamic testing
- ใช้ทั้งวิธีคู่มือและอัตโนมัติ (Use **both manual and automated** approaches)

### เทคนิคการทบทวนโค้ด (Code Review Techniques)

- **Walkthrough**: ไม่เป็นทางการ สำเร็จการศึกษา (Informal, educational)
- **Technical Review**: การประเมินของผู้เชี่ยวชาญ (Expert evaluation)
- **Inspection**: อย่างเป็นทางการ มีประสิทธิภาพมากที่สุด (Formal, most effective)

### Tools

- **ESLint**: หา bugs บังคับมาตรฐาน (Find bugs, enforce standards)
- **Prettier**: การจัดรูปแบบที่สอดคล้อง (Consistent formatting)
- **Together**: ดีที่สุดของทั้งสองโลก (Best of both worlds)

### แนวปฏิบัติที่ดีที่สุด (Best Practices)

1. ทบทวนส่วนเล็ก (Review small chunks) (200-400 lines)
2. ใช้เวลาเตรียมการ (Take time to prepare)
3. ใช้รายการตรวจสอบ (Use checklists)
4. เน้นที่โค้ด ไม่ใช่คน (Focus on code, not person)
5. วัด และปรับปรุง (Measure and improve)
