I'm working on designing a shopping cart system that respects the single responsibility principle. However, I'm facing a challenge when it comes to handling cart creation and updating separately.
Scenario:
When a user logs into the website and adds products to the cart. Currently, the "add to cart" operation also implicitly creates a cart, which violates the single responsibility principle. I want to find a solution that respects the single responsibility of creating and updating the cart separately, without requiring the user to explicitly create the cart.
I'm considering a few approaches and would appreciate insights or alternative suggestions:
Approach 1: Domain Logic inside "Add to Cart" Service
If I, as the domain owner, decide to embed the cart creation logic within the "add to cart" service, allowing it to create the cart if it doesn't exist. it seems like a practical solution, but maybe not a good design.
Approach 2: Two Separate Services
Creating two services, one for cart creation and another for cart update seems like a clean separation of concerns. The create cart service would be invoked asynchronously via an event triggered by account creation. However, I'm concerned about potential overengineering, and the asynchronous event might fail and/or take some time to be processed, affecting the user experience.
Approach 3: Two services with Observer pattern
I'm considering using the observer pattern. After the user creates an account, a synchronous trigger would invoke the create cart service. Would this be a more straightforward solution in terms of implementation and user experience?
the "add to cart" operation also implicitly creates a cart, which violates the single responsibility principle.
-- That's not true at all. The SRP is informed by variations in your functional requirements; all you have here is one requirement (The requirement being that a cart must always exist before you can add something to it). Such a requirement cannot vary in any way; i.e. it is not possible to add something to a cart that doesn't exist, therefore you have no variations, therefore the creation of the cart and add/remove operations all fall under the same responsibility.