Assertion (การยืนยัน) คืออะไร?
Assert เป็นคำสั่งที่ใช้ตรวจสอบเงื่อนไข (boolean expression) ระหว่างรันโปรแกรม (runtime) หากเงื่อนไขเป็น false โปรแกรมจะหยุดทำงานและแสดงข้อความแจ้งเตือน ช่วยจับข้อผิดพลาดตรรกะ (logic errors) ได้อย่างรวดเร็ว
รูปแบบการใช้งาน
Debug.Assert(condition, message);
- condition - นิพจน์บูลีนที่คาดหวังให้เป็น true
- message - (optional) ข้อความแสดงเมื่อเงื่อนไขเป็น false
ตัวอย่างการใช้งาน
using System.Diagnostics;
public class Calculator
{
public int Divide(int a, int b)
{
// ตรวจสอบว่า b ไม่ใช่ 0
Debug.Assert(b != 0, "ตัวหารไม่สามารถเป็นศูนย์ได้");
return a / b;
}
public int Factorial(int n)
{
// ตรวจสอบ precondition
Debug.Assert(n >= 0, "แฟกทอเรียลต้องเป็นจำนวนไม่ติดลบ");
if (n <= 1) return 1;
return n * Factorial(n - 1);
}
}
Debug.Assert vs Release Build
สำคัญมาก: Debug.Assert ทำงานเฉพาะใน Debug build** เท่านั้น ใน **Release build** โค้ด Assert จะถูกตัดออกโดย compiler อัตโนมัติ
ปัญหาที่อาจเกิดขึ้น
// ❠ อันตราย! หาก DecCounter มี side effect
Debug.Assert(DecCounter(d) != 0);
// ใน Release build: DecCounter() จะไม่ถูกเรียกเลย!
// ทำให้ logic ของโปรแกรมผิดพลาด
วิธีแก้ไขที่ถูกต้อง
// ✅ ใช้ตัวแปรชั่วคราว (temp variable)
int temp = DecCounter(d);
Debug.Assert(temp != 0); // ใน Release: temp ยังถูก assign แต่ Assert ถูกลบ
เมื่อไหร่ควรใช้ Assert?
- ตรวจสอบ Preconditions (เงื่อนไขก่อนเข้าฟังก์ชัน)
- ตรวจสอบ Postconditions (เงื่อนไขหลังจบฟังก์ชัน)
- ตรวจสอบ Invariants (เงื่อนไขที่ควรเป็นจริงตลอดเวลา)
- ในโปรแกรมขนาดใหญ่ซับซ้อน เพื่อจับ bug ระหว่างพัฒนา
เมื่อไหร่ไม่ควรใช้ Assert?
- ตรวจสอบ input จากผู้ใช้ (ควรใช้ validation + exception)
- ตรวจสอบ error ที่คาดการณ์ได้ (เช่น file not found, network error)
- ใน production code ที่ต้อง handle error อย่างเหมาะสม
- โค้ดที่มี side effect ภายใน Assert
Debug.Assert vs Trace.Assert
| คุณสมบัติ | Debug.Assert | Trace.Assert |
|---|---|---|
| ทำงานใน Debug build | ✅ ใช่ | ✅ ใช่ |
| ทำงานใน Release build | ❌ ไม่ (ถูกลบออก) | ✅ ใช่ (ต้อง define TRACE) |
| เหมาะสำหรับ | Development/Testing | Production monitoring |
Best Practices
- ใช้ Assert สำหรับ programming errors (bugs) ไม่ใช่ runtime errors
- อย่าใส่โค้ดที่มี side effect ภายใน Assert
- เขียนข้อความแจ้งเตือนที่ชัดเจน ช่วย debug ได้ง่าย
- ใช้
Debug.Failสำหรับจุดที่ไม่ควรถึง (unreachable code)