Avoiding the Anaemic Domain - How to decide what single responsibility a class has
Posted
by
thecapsaicinkid
on Programmers
See other posts from Programmers
or by thecapsaicinkid
Published on 2013-06-26T09:26:22Z
Indexed on
2013/06/26
10:27 UTC
Read the original article
Hit count: 348
Even after reading a bunch I'm still falling into the same trap. I have a class, usually an enity. I need to implement more than one, similar operations on this type. It feels wrong to (seemingly arbitrarily) choose one of these operations to belong inside the entity and push the others out to a separate class; I end up pushing all operations to service classes and am left with an anaemic domain.
As a crude example, imagine the typical Employee class with numeric properties to hold how many paid days the employee is entitled to for both sickness and holiday and a collection of days taken for each.
public class Employee
{
public int PaidHolidayAllowance { get; set; }
public int PaidSicknessAllowance { get; set; }
public IEnumerable<Holiday> Holidays { get; set; }
public IEnumerable<SickDays> SickDays { get; set; }
}
I want two operations, one to calculate remaining holiday, another for remaining paid sick days. It seems strange to include say, CalculateRemaingHoliday() in the Employee class and bump CalculateRemainingPaidSick() to some PaidSicknessCalculator class. I would end up with a PaidSicknessCalculator and a RemainingHolidayCalculator and the anaemic Employee entity as seen above. The other alternative would be to put both operations in the Employee class and kick Single Responsibility to the curb. That doesn't make for particularly maintainable code.
I suppose the Employee class should have some initialisation/validation logic (not accepting negative alowances etc.) So maybe I just stick to basic initialisation and validation in the entities themselves and be happy with my separate calculator classes. Or maybe I should be asking myself if Anaemic Domain is actually causing me some tangible problems with my code.
© Programmers or respective owner