public field?初學者常覺得 obj.field = value; 比 obj.setField(value); 簡單。但直接暴露欄位會導致:
Map、計算屬性、延遲載入) 無法在不改動呼叫端的情況下變更。public class User {
private String email;
private int age;
public String getEmail() { return email; }
public void setEmail(String email) {
if (email == null || !email.contains("@")) {
throw new IllegalArgumentException("Invalid email format");
}
this.email = email.toLowerCase(); // 正規化
}
public int getAge() { return age; }
public void setAge(int age) {
if (age < 0 || age > 150) {
throw new IllegalArgumentException("Age out of range");
}
this.age = age;
}
}
@Data / @Getter / @Setter: 編譯期自動生成,原始碼極度精簡。public record User(String email, int age) {} 自動提供 email(), age()、建構子、equals/hashCode/toString,預設不可變,適合資料傳輸物件 (DTO)。java.awt.Point)。結論:Getter/Setter 不是為了當下的「驗證代碼」,而是為了未來的「可維護擴充性」。現代開發配合 Lombok 或 Record 可兼顧簡潔與封裝。