So I have a code snippet similar to this. I feel like the if statements should be in a common function. I am not sure how to handle that because school and student should be passed to this function but they are of different types.
Teacher teacher = school.getTeachers();
if(ObjectUtils.isEmpty(teachers) {
log.error(”cannot find teachers in school” + school.getSchoolName());
throw new Exception(”xyz”);
}
Student student = teacher.getStudents();
if(ObjectUtils.isEmpty(student)) {
log.error(”cannot find students in school” + school.getSchoolName());
throw new Exception(”xyz”);
One way is to consider this case (and similar ones) in your class design. You could use inheritance. Let's say Teacher and Student inherit from Person. This way the code will be easier to extend in case you need to consider some more common logics for both classes of Teacher/Student. Create your own exception handler taking the Person class. You could use Optional in Java to throw your exception. For your log message, you can use the class name