
Java Record compact constructor: ตรวจค่าตอนสร้างโดยไม่เขียนฟิลด์ซ้ำ
น้องกายEngineering
อยากได้ DTO สั้นๆ แต่ยังต้องเช็กว่าชื่อไม่ว่างหรือตัวเลขไม่ติดลบ ผมใช้ compact constructor ของ record ครับ
Record มีตั้งแต่ Java 16 คอนสตรัคเตอร์แบบย่อเขียนเป็น record Point(int x, int y) { public Point { ... } } โดยไม่ต้องประกาศพารามิเตอร์ซ้ำ ภายในบล็อกนี้จะรันก่อนที่ฟิลด์จะถูก assign จริง และใช้ตรวจ/ปรับค่าจากพารามิเตอร์ได้
public class Main {
record Money(int cents, String currency) {
public Money {
if (cents < 0) {
throw new IllegalArgumentException("cents must be >= 0");
}
if (currency == null || currency.isBlank()) {
throw new IllegalArgumentException("currency required");
}
currency = currency.trim().toUpperCase();
}
}
public static void main(String[] args) {
Money thb = new Money(100, " thb ");
if (!"THB".equals(thb.currency()) || thb.cents() != 100) {
throw new AssertionError("normalize failed");
}
try {
new Money(-1, "THB");
throw new AssertionError("expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {
// ok
}
System.out.println("ok");
}
}
Recap
- ใช้ compact constructor สำหรับ validation/normalize ของ record
- จำว่า assign ฟิลด์เกิดหลังบล็อก — ในบล็อกให้แตะพารามิเตอร์
- โยน IllegalArgumentException เมื่ออินพุตผิดแทนการสร้างออบเจ็กต์เพี้ยน