Logic Belongs to Entities


We have a Cart in the online store system, the Cart is responsible for handling items (add, remove) but not prices. Once we want to show the total price of the Cart, we have to use fresh prices from the database because product prices are changed often.

Logic in Service

Let’s start with a service implementation that can be usually found in large applications (usually and sadly). The benefit of this implementation is that it works

Think About Use-Case Only

The theme of this article is logic in entities, but let’s think about the use-case Calculate Cart Total Price without programming first. To be able to finish the use-case we need

  • a Price of each Product
  • Amount of each of Products

Moving Logic to Cart Entity

Our goal is to implement calculating the total price in the Cart entity itself.

  • The logic sits together with data in the Cart entity, this leads to a rich model
  • The Cart doesn’t expose data (Items), Items are therefore properly encapsulated
  • This code is testable as we can mock the interface in tests to produce predictable prices
  • By the way, this was our goal — to have the logic in the entity

Interface Implementation

The interface has to be implemented anyway, but that’s not a problem at all

Only One Implementation

We will usually have only one implementation for such an interface, that is strange, isn’t it wrong?

Moving Logic … even further

Do you think the logic is moved well? I have an advanced proposal.


Moving logic to entities is possible, use an interface that provides the necessary information and passes it to the method. Logic in entities is easy to understand, leads to better testability, better layer separation, and better encapsulation.


If you struggle with moving logic to entities, contact me, I’ll help You. Business logic is my passion… svatasimara.cz



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store