Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Precondition Check: ตรวจสอบ List ว่างหรือ null ใน Java

รูปแบบมาตรฐานของ Precondition

public void myFunction(List myList) {
    // 1. ตรวจสอบ null
    if (myList == null) {
        throw new IllegalArgumentException("List is null");
    }
    
    // 2. ตรวจสอบว่าง
    if (myList.isEmpty()) {
        throw new IllegalArgumentException("List is empty");
    }
    
    // 3. ทำงานต่อ...
    // process(myList);
}


แนวทางปฏิบัติที่ดี (Best Practices)

  • Fail-fast: ตรวจสอบ precondition ทันทีที่เข้ามethod
  • ข้อความชัดเจน: บอกว่าผิดที่ไหน (null? empty? size ไม่ตรง?)
  • Exception ให้ถูกต้อง: IllegalArgumentException สำหรับ argument ผิด, NullPointerException ถ้าต้องการระบุชัดเจนว่า null
  • Java 7+: ใช้ Objects.requireNonNull(list, "List must not be null")
  • Java 9+: ใช้ Objects.requireNonNull(list).isEmpty() แบบ chaining

ตัวอย่าง Java 9+

public void process(List items) {
    Objects.requireNonNull(items, "Items list cannot be null");
    if (items.isEmpty()) {
        throw new IllegalArgumentException("Items list cannot be empty");
    }
    // ปลอดภัยแล้ว
}

Design by Contract

Precondition เป็นส่วนของ "Design by Contract" - กำหนดเงื่อนไขที่ caller ต้องปฏิบัติ ก่อนเรียก method ช่วยลด bug และทำให้ code อ่านง่าย