I would like to know how to perform a clean code to organize validation in my service layer.
So, I have this service:
public interface PersonService {
public Person getPerson(int idperson);
public List getPeopleWithFather( int idFather);
}
For the validation of the service layer I use Spring AOP (Aspectj), so for validate the first method :
public Person getPerson(int idperson){
return personRepository.getPerson(idperson);
}
@AfterReturning(
pointcut="execution(* business.PersonService.getPerson(..))",
returning = "result")
public void afterRunning(JoinPoint joinPoint, Object result){
Person person = (Person) result;
if(person == null){
throw new PersonNotFound();
}
}
So in my service, I dont need to write try/catch or maybe conditions of validate. But, I don't know how I can organize my code for the second method, because :
- First, I need to validate that the father exists with his id.
- get list of children.
One way is to do so:
public List getPeopleWithFather( int idFather){
Person father = getPerson(idFather);
if(father != null){ return personRepository.getPeopleWithFather(father); }
return null;
}
Other way is :
public List getPeopleWithFather( int idFather){
Person father = ((PersonService) AopContext.currentProxy() ).getPerson(idFather);
return personRepository.getPeopleWithFather(father);
}
@AfterThrowing(pointcut="execution(* business.PersonService.getPeopleWithFather(..))",
throwing = "throwable")
public void afterThrowing(JoinPoint joinPoint, Exception throwable){
if( throwable instanceof PersonNotFound){
throw new PersonNotFound("whatever");
}
}
There a more elegant way to perform these validations?. Thanks in advance.