I've asked a previous question last month, about whether an Entity should access a Repository, and although it looks like most people think they shouldn't, I have to admit it's hard for me to get convinced.
I have a use case for which I really can't think of any (reasonable) way to do the logic without injecting the Repository in my Entity:
We have a Store
, which is assigned a Zone
(city, district, ... - user defined).
To reduce the workload of the employee in charge of adding Stores to the database, and to ensure consistency, we don't ask him to select the Zone in which he wants to add the Store. He just zooms on a map, clicks to pinpoint the Store location, and saves. The application then has to find the most relevant Zone for this location.
What I currently have is something like:
class Store
{
protected Zone zone;
protected Point location;
protected ZoneRepository zoneRepository;
public void setLocation(Point location)
{
Zone matchingZone = this.zoneRepository.findByLocation(location);
if (matchingZone == null) {
throw new ApplicationException(
"The store location must be within a zone boundary");
}
this.location = location;
this.zone = matchingZone;
}
}
Do you have any solid alternative which would support the commonly accepted opinion that this design is inherently bad?