I have a Code Like this:
Insurance Dto:
private String accidentNo;
private String birthDate;
private String mobileNo;
private String ssn;
public InsuranceDto(String accidentNo, String birthDate, String mobileNo, String ssn) {
this.accidentNo = accidentNo;
this.birthDate = birthDate;
this.mobileNo = mobileNo;
this.ssn = ssn;
}
public InsuranceDto() {}
public String getAccidentNo() {
return accidentNo;
}
public void setAccidentNo(String accidentNo) {
this.accidentNo = accidentNo;
}
public String getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
Main Method:
InsuranceDto insuranceDto = new InsuranceDto();
if (insuranceDto.getAccidentNo() == null)
throw new RuntimeException("Enter AccidentNo.");
if (insuranceDto.getBirthDate() == null)
throw new RuntimeException("Enter BirthDate.");
if (insuranceDto.getMobileNo() == null)
throw new RuntimeException("Enter MobileNo");
if (insuranceDto.getSsn() == null)
throw new RuntimeException("Enter SSN");
So the Code Works but its Kind of Garbage and if I Add 3 Other Fields to InsuranceDTO, I Have to Edit the Entire Code to Validate them. Imagen if the Validation Policy Gets more Complicated and you Need to Validate two and/or more Fields in one If statement At Once.
So How Can I avoid this? Is There a Design Pattern or Something else to Make it Better?