java-test-tutorial/src at main · Woomin-Wang/java-test-tutorial
public record Student(String id, String name) {
}
💡 StudentResult가 필요할까?
Student
만을 사용하여 성공 시에는 객체를 반환하고, 실패 시나리오(유효하지 않은 입력, 중복 ID 등)에서는 각각의 의미에 맞는 예외(IllegalArgumentException
,IllegalStateException
)를 던지도록StudentServiceImpl
을 설계하는 것이 좋다.
public class StudentServiceImpl implements StudentService {
private final Map<String, Student> studentMap;
public StudentServiceImpl(Map<String, Student> studentMap) {
this.studentMap = studentMap;
}
@Override
public Student create(String id, String name) {
validateInput(id, name);
Student newStudent = new Student(id, name);
Student existingStudent = studentMap.putIfAbsent(id, newStudent);
if (existingStudent != null) {
throw new IllegalStateException("ID already exists: " + id);
}
return newStudent;
}
@Override
public void remove(String id) {
validateInput(id);
Student removedStudent = studentMap.remove(id);
if (removedStudent == null) {
throw new IllegalStateException("ID does not exist: " + id);
}
}
private void validateInput(String id, String name) {
if (StringUtils.isBlank(id) || StringUtils.isBlank(name)) {
throw new IllegalArgumentException("Student ID and name cannot be blank.");
}
}
private void validateInput(String id) {
if (StringUtils.isBlank(id)) {
throw new IllegalArgumentException("Student ID cannot be blank.");
}
}
}