Vibe Coding
Best Practices
AI
Programming
Tips

Best Practices สำหรับ Vibe Coding

รวมแนวทางปฏิบัติที่ดีที่สุดสำหรับ Vibe Coding ตั้งแต่การเขียน prompts ไปจนถึงการ review โค้ด เพื่อใช้ AI ได้อย่างมีประสิทธิภาพและปลอดภัย

AI Unlocked Team
25/01/2568
Best Practices สำหรับ Vibe Coding

Best Practices สำหรับ Vibe Coding

Vibe Coding กำลังเปลี่ยนวิธีที่เราพัฒนาซอฟต์แวร์ แต่การใช้ AI อย่างมีประสิทธิภาพต้องอาศัยทักษะและแนวปฏิบัติที่ถูกต้อง บทความนี้รวบรวม best practices ที่จะช่วยให้คุณใช้ AI coding assistants ได้อย่างเต็มศักยภาพ

หลักการพื้นฐาน

The Vibe Coding Mindset

Traditional: "ฉันต้องเขียนทุกบรรทัดเอง"
↓
Vibe Coding: "ฉันเป็นผู้กำกับ AI เป็นผู้ช่วย"

หลักการสำคัญ:

  1. AI เป็นผู้ช่วย ไม่ใช่ผู้แทนที่ - คุณยังต้องเข้าใจโค้ด
  2. Quality over Speed - เร็วขึ้นแต่ต้องไม่ลดคุณภาพ
  3. Trust but Verify - เชื่อถือแต่ต้องตรวจสอบ
  4. Continuous Learning - เรียนรู้จาก AI และพัฒนาตัวเอง

Best Practice #1: เขียน Prompts ที่ดี

โครงสร้าง Prompt ที่มีประสิทธิภาพ

[Context] - บริบทของงาน
[Task] - สิ่งที่ต้องการ
[Constraints] - ข้อจำกัด
[Format] - รูปแบบผลลัพธ์
[Examples] - ตัวอย่าง (ถ้ามี)

ตัวอย่างการใช้งาน

❌ ไม่ดี:
"สร้าง API"

✅ ดี:
"Context: Next.js 14 app with Supabase backend

Task: สร้าง API route สำหรับ user registration

Constraints:
- ใช้ Zod สำหรับ validation
- Hash password ด้วย bcrypt
- Return appropriate HTTP status codes
- ต้องมี rate limiting

Format:
- TypeScript
- มี comments อธิบาย
- มี error types

Example response structure:
{ success: true, user: { id, email, name } }
หรือ
{ success: false, error: { code, message } }"

เทคนิคเพิ่มเติม

1. ใช้ Role Setting

"คุณเป็น Senior TypeScript Developer ที่เชี่ยวชาญ Next.js และ Supabase
ช่วย review โค้ดนี้และเสนอแนะการปรับปรุง..."

2. ให้ Context จากโปรเจค

"@file:package.json @file:tsconfig.json
ช่วย setup path aliases ให้ใช้ @/ แทน relative imports"

3. ขอให้ Think Step-by-Step

"คิดทีละขั้นตอน:
1. วิเคราะห์ requirements
2. ออกแบบ solution
3. เขียนโค้ด
4. ตรวจสอบ edge cases"

Best Practice #2: Review โค้ดอย่างละเอียด

Checklist สำหรับ Review AI-Generated Code

## Logic Review
- [ ] Logic ถูกต้องตาม requirements หรือไม่?
- [ ] มี edge cases ที่ไม่ได้จัดการหรือไม่?
- [ ] Algorithm มีประสิทธิภาพหรือไม่?

## Security Review
- [ ] มี SQL injection vulnerabilities หรือไม่?
- [ ] มี XSS vulnerabilities หรือไม่?
- [ ] Sensitive data ถูก handle อย่างถูกต้องหรือไม่?
- [ ] Authentication/Authorization ถูกต้องหรือไม่?

## Code Quality
- [ ] ตรงตาม coding standards ของ project หรือไม่?
- [ ] มี unnecessary dependencies หรือไม่?
- [ ] Error handling ครบถ้วนหรือไม่?
- [ ] มี hardcoded values ที่ควรเป็น config หรือไม่?

## Performance
- [ ] มี N+1 queries หรือไม่?
- [ ] มี memory leaks หรือไม่?
- [ ] มี unnecessary re-renders (React) หรือไม่?

ตัวอย่างการ Review

// AI Generated Code
async function getUsers() {
  const users = await db.query('SELECT * FROM users');
  return users;
}

// Review Notes:
// ❌ SELECT * - ควรเลือกเฉพาะ columns ที่ต้องการ
// ❌ ไม่มี pagination - อาจทำให้ memory เต็ม
// ❌ ไม่มี error handling
// ❌ ไม่มี type safety

// Improved Version
async function getUsers(options: GetUsersOptions): Promise<PaginatedResult<User>> {
  try {
    const { page = 1, limit = 20, status } = options;
    const offset = (page - 1) * limit;

    const query = db
      .select(['id', 'email', 'name', 'created_at'])
      .from('users')
      .where(status ? { status } : {})
      .limit(limit)
      .offset(offset);

    const [users, total] = await Promise.all([
      query,
      db.count('users').where(status ? { status } : {})
    ]);

    return {
      data: users,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit)
      }
    };
  } catch (error) {
    logger.error('Failed to get users', { error, options });
    throw new DatabaseError('Failed to fetch users');
  }
}

Best Practice #3: Security First

สิ่งที่ต้องระวังเสมอ

1. ไม่ส่ง Sensitive Data ไปยัง AI

// ❌ อย่าทำ
"ช่วย debug function นี้:
const apiKey = 'sk-live-abc123...'
const dbPassword = 'production_password'"

// ✅ ใช้ placeholders
"ช่วย debug function นี้:
const apiKey = process.env.API_KEY
const dbPassword = process.env.DB_PASSWORD"

2. ตรวจสอบ AI-Generated Security Code

// AI อาจ generate code ที่มี vulnerabilities

// ❌ Vulnerable to SQL Injection
const query = `SELECT * FROM users WHERE id = ${userId}`;

// ✅ Use parameterized queries
const query = 'SELECT * FROM users WHERE id = $1';
const result = await db.query(query, [userId]);

3. Validate All Input

// AI อาจลืม validation

// ❌ ไม่มี validation
app.post('/api/users', async (req, res) => {
  const user = await createUser(req.body);
  res.json(user);
});

// ✅ มี validation
import { z } from 'zod';

const createUserSchema = z.object({
  email: z.string().email(),
  password: z.string().min(8),
  name: z.string().min(2).max(100)
});

app.post('/api/users', async (req, res) => {
  const result = createUserSchema.safeParse(req.body);
  if (!result.success) {
    return res.status(400).json({ error: result.error });
  }
  const user = await createUser(result.data);
  res.json(user);
});

Best Practice #4: Version Control Strategy

Commit Strategy

# ก่อนใช้ AI generate code ที่ใหญ่
git add .
git commit -m "WIP: before AI refactoring"

# หลังจาก AI generate และ review แล้ว
git add .
git commit -m "feat: add user authentication

- Add login/register endpoints
- Add JWT token management
- Add session middleware

AI-assisted with manual review"

Branch Strategy

# สำหรับ AI-heavy changes
git checkout -b feature/ai-refactor

# ทำ AI changes
# Review
# Test

# Merge เมื่อมั่นใจ
git checkout main
git merge feature/ai-refactor

Best Practice #5: Testing AI-Generated Code

ทำ Tests ก่อนใช้ Production

// AI Generate: function
function calculateTax(amount, rate) {
  return amount * rate;
}

// คุณต้องเขียน tests
describe('calculateTax', () => {
  // Happy path
  it('should calculate tax correctly', () => {
    expect(calculateTax(100, 0.07)).toBe(7);
  });

  // Edge cases
  it('should handle zero amount', () => {
    expect(calculateTax(0, 0.07)).toBe(0);
  });

  it('should handle zero rate', () => {
    expect(calculateTax(100, 0)).toBe(0);
  });

  // Error cases
  it('should handle negative amounts', () => {
    // ถาม: ควร throw error หรือ return negative?
    expect(() => calculateTax(-100, 0.07)).toThrow();
  });

  it('should handle invalid rate', () => {
    expect(() => calculateTax(100, 1.5)).toThrow();
  });
});

ให้ AI ช่วยสร้าง Tests

Prompt:
"สร้าง comprehensive unit tests สำหรับ function นี้:
[paste function]

ต้องครอบคลุม:
1. Happy path cases
2. Edge cases (empty, null, undefined)
3. Error cases
4. Boundary conditions
5. Type validation"

Best Practice #6: Documentation

Document AI Decisions

/**
 * Calculates shipping cost based on weight and destination.
 *
 * @ai-note This algorithm was generated by Claude and reviewed for:
 * - Weight bracket accuracy
 * - International shipping rates
 * - Edge case handling
 *
 * @reviewed 2025-01-25 by @developer
 */
function calculateShipping(weight, destination) {
  // ...
}

Maintain Context Files

สร้างไฟล์ .cursorrules หรือ CLAUDE.md:

# AI Context for This Project

## Tech Stack
- Next.js 14 with App Router
- Supabase for backend
- TypeScript strict mode
- Tailwind CSS + shadcn/ui

## Coding Standards
- Use async/await, not callbacks
- Prefer const over let
- Use early returns
- Error messages in Thai

## File Structure
- API routes: app/api/[resource]/route.ts
- Components: components/[category]/[name].tsx
- Hooks: lib/hooks/use-[name].ts

## Testing
- Use Vitest for unit tests
- Use Playwright for E2E
- Minimum 80% coverage for new code

Best Practice #7: Continuous Improvement

เรียนรู้จาก AI

// เมื่อ AI suggest โค้ดที่ดี
// ถามว่าทำไมถึงทำแบบนั้น

Prompt: "อธิบายว่าทำไมคุณถึงใช้ useMemo ตรงนี้
และเมื่อไหร่ควร/ไม่ควรใช้ useMemo"

Track AI Performance

## AI Usage Log

### 2025-01-25
- Task: Refactor auth system
- Tool: Cursor + Claude
- Time saved: ~2 hours
- Issues found: 1 security issue (fixed)
- Learnings: Claude ดีสำหรับ complex logic

### 2025-01-24
- Task: Generate CRUD endpoints
- Tool: GitHub Copilot
- Time saved: ~1 hour
- Issues found: None
- Learnings: Copilot เร็วสำหรับ boilerplate

Best Practice #8: Know When NOT to Use AI

งานที่ควรทำเอง

  1. Security-critical code - Authentication, encryption
  2. Business logic core - ที่ต้องเข้าใจลึกซึ้ง
  3. Performance-critical - ที่ต้อง optimize ละเอียด
  4. Legal/Compliance - ที่มีข้อกำหนดเฉพาะ

Warning Signs

❌ ไม่ควรใช้ AI เมื่อ:
- ไม่เข้าใจว่าโค้ดทำอะไร
- ไม่มีเวลา review
- งานที่ต้องการ 100% accuracy
- เกี่ยวกับ sensitive data จริงๆ

Checklist สรุป

ก่อนใช้ AI

  • กำหนด scope และ requirements ชัดเจน
  • เตรียม context ที่จำเป็น
  • ตรวจสอบว่าไม่มี sensitive data

ระหว่างใช้ AI

  • เขียน prompt ที่ชัดเจนและละเอียด
  • Iterate ถ้าผลลัพธ์ไม่ตรงใจ
  • ถามคำถามถ้าไม่เข้าใจ

หลังใช้ AI

  • Review โค้ดอย่างละเอียด
  • ตรวจสอบ security
  • เขียน tests
  • Document การเปลี่ยนแปลง
  • Commit ด้วย message ที่ชัดเจน

สรุป

Vibe Coding จะมีประสิทธิภาพสูงสุดเมื่อคุณ:

  1. เขียน prompts ที่ดี - ชัดเจน ละเอียด มี context
  2. Review ทุกครั้ง - ไม่ trust 100%
  3. Security first - ระวัง vulnerabilities
  4. Test thoroughly - มี coverage ที่ดี
  5. Document decisions - เพื่อ maintenance
  6. Keep learning - พัฒนาตัวเองไปพร้อมกับ AI

พร้อมเริ่ม Vibe Coding อย่างมืออาชีพแล้วหรือยัง?

เริ่มต้นด้วยการอ่าน:


เขียนโดย

AI Unlocked Team