ได้เลย 😎 เรามาเรียนเรื่อง Guard (Guard Clauses) ใน C# แบบละเอียดและเข้าใจง่าย
1️⃣ Guard คืออะไร?
-
Guard Clause คือ การตรวจสอบเงื่อนไขตั้งแต่ต้นของ Method หรือ Constructor
-
ถ้าเงื่อนไขไม่ถูกต้อง → โยน Exception หรือหยุดทำงานทันที
-
จุดประสงค์: ป้องกัน Invalid State หรือ Null Reference
-
ทำให้โค้ด อ่านง่ายและปลอดภัย
2️⃣ ตัวอย่าง Guard แบบพื้นฐาน
public void SetUserName(string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("Name cannot be empty");
Console.WriteLine($"User name set to: {name}");
}
// การใช้งาน
SetUserName(""); // Exception: Name cannot be empty
3️⃣ ใช้ Guard กับ Constructor
public class User
{
public string Name { get; }
public int Age { get; }
public User(string name, int age)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("Name cannot be empty");
if (age < 0 || age > 120)
throw new ArgumentOutOfRangeException(nameof(age), "Age must be between 0 and 120");
Name = name;
Age = age;
}
}
4️⃣ ทำให้ Guard Cleaner ด้วย Helper Method
public static class Guard
{
public static void AgainstNull(object obj, string name)
{
if (obj == null)
throw new ArgumentNullException(name);
}
public static void AgainstInvalidAge(int age)
{
if (age < 0 || age > 120)
throw new ArgumentOutOfRangeException(nameof(age), "Age must be between 0 and 120");
}
}
// ใช้งาน
public class User
{
public string Name { get; }
public int Age { get; }
public User(string name, int age)
{
Guard.AgainstNull(name, nameof(name));
Guard.AgainstInvalidAge(age);
Name = name;
Age = age;
}
}
5️⃣ ใช้ Guard Clauses กับ C# 11 ArgumentNullException.ThrowIfNull
public void SetUser(User user)
{
ArgumentNullException.ThrowIfNull(user, nameof(user));
Console.WriteLine(user.Name);
}
-
ข้อดี: โค้ดสั้นลง ไม่ต้องเขียน
if
แบบยาว ๆ -
รองรับ C# 11+
✅ สรุป
-
Guard Clause → ป้องกันข้อมูลไม่ถูกต้องตั้งแต่ต้น
-
โค้ดอ่านง่าย → ไม่มี nested
if
เยอะ -
สามารถทำเป็น Helper Class หรือใช้ built-in methods เช่น
ArgumentNullException.ThrowIfNull
ถ้าคุณอยาก ฉันสามารถทำ ตัวอย่าง Guard Clauses แบบ Advanced + Integration กับ CQRS / CommandHandler ให้ดูวิธีป้องกัน Invalid Command ก่อนถึง Handler ด้วย
คุณอยากให้ทำไหม?