I like implementing service classes as stateless. However, I also like to decompose my logic into more, simple methods or functions. In some scenarios it seems like the two are somewhat against each other. Consider the following two examples.
I have an entity object called House
, implemented something like this.
public class House {
public string Address { get; set; }
public List<Room> Rooms { get; set; }
...
public IEnumerable<Furniture> GetAllFurnitures() {
return Rooms.SelectMany(e => e.Furnitures);
}
...
}
1. Stateful implementation
Pros: cleaner code, no parameter hell
Cons: one service per one House
, makes Dependency injection harder because of constructor parameter
public class HouseCleaner {
private readonly House _house;
public HouseCleaner(House house) {
_house = house;
}
public void Clean() {
vacuumClean();
cleanBathroom();
cleanToilettes();
cleanKitchen();
wipeFloor();
}
}
2. Stateless implementation
Pros: the service instance can be shared, makes Dependency injection easier
Cons: need to pass probably many parameters to all simple methods and functions to share the current state
public class HouseCleaner {
public void Clean(House house) {
vacuumClean(house);
cleanBathroom(house);
cleanToilettes(house);
cleanKitchen(house);
wipeFloor(house);
}
}
Which one do you feel more appropriate considering that this is a simplified example. In reality there could be several service dependencies, and other parameters too.