开发者

Should the updating of an entity be handled by the entity itself or by a service class?

开发者 https://www.devze.com 2023-03-25 05:31 出处:网络
Forgive the title, it\'s simpler than it sounds. I\'ve got a class, StickerBook. It contains some stickers, List<Sticker>.

Forgive the title, it's simpler than it sounds.

I've got a class, StickerBook. It contains some stickers, List<Sticker>.

When it's time to see if there any stickers waiting to be added, should StickerBook.CheckForNewStickers() handle the logic of looking for them and then adding them, or should a new class, NewStickerChecker check for and开发者_如何转开发 then add them to the StickerBook?

A pretty basic concept I know, I just can't wrap my head around it.


Pretty sure there's no right or wrong answer to this. Either way you seem to be encapsulating the logic rather than making the internals of the class (List) open to all which is generally a good thing.

Putting logic into a separate service class (and having this class implement an interface) could make unit testing easier if you then pass this interface to other pieces of code as a dependency. I think it's conceptually easier to mock up a service class and pass around the actual simple entities during testing rather than mock up entities with complex logic on them.


Well, it depends on what's your general approach to structuring the code and modelling of objects. That said, the Single Responsibility Principle states that object should have only one reason of existence, so I would favor the NewStickerChecker as a class.


there is no black and white and this could be subjective, in my experience if there is an entity which contains a collection of sub-entities, like in your case the book contains a list of stickers, you could load them inside the entity.

After all OOP defines that classes contain data and logic required to manipulate that data ;-)

P.S. just as disclaimer, you are talking of entities in the spirit of Business Entities and not in the Entity Framework light (... not that it would change too much anyway but just for the question's tagging ).

0

精彩评论

暂无评论...
验证码 换一张
取 消