A very simple use case implemented using DDD and java.
I have a FooEntity and a FooRepository. The Entity has a delete method which validates certain state to check whether it is safe to be deleted, and in case this evaluates to true invoke the delete in the repository, which is injected in the entity.
So far so good, but, what happens if somebody invokes the delete method directly in the repository? Then the validation wouldn't be performed.
Placing the validation in the repository would solve the problem, but this would be clearly wrong since it would make necessary to expose the internal state of the entity.
What am I missing?
public class FooEntity {
@inject
FooRepository fooRepository;
private Boolean canBeDeleted;
public void delete(){
if (canBeDeleted){
fooRepository.delete(this);
}
throw new CannotBeDeletedException();
}
}
public class FooRepository {
@inject
FooDAO fooDAO;
public void delete(FooEntity fooEntity){
fooDAO.delete(fooEntity.getId());
}
}