Pregunta

Example : ShoppingCart entity has a rule that no more than 10 items can be added . The shoppingCart will have a method addItemToCart(item) that will check if it the limit was not exceeded. If the cart limit is exceeded the cart should somehow inform somehow the upper layer calling that method that a specific business rule was broken.

One thing that comes in mind is to use exceptions but these seem an unproper use of exceptions. How should the messaging be done? What patterns could help for this problem , keeping the domain unrelated to the other layers and properly encapsulated ?

¿Fue útil?

Solución

If the rule is max 10 items in the cart, then ShoppingCart should expose isFull() so upper layers can check before calling addItem(). Or disable Add button, or whatever - ShoppingCart doesn't know how the rule information is used and shouldn't assume it will only be required when addItem is called. As a safety check addItem can throw an exception but this shouldn't be the primary mechanism to communicate to upper layer.

Otros consejos

There isn't a recipe for that, it really depends on your app. For your specific example I believe things are quite simple: ShoppingCart is pretty much a container and even that it's a domain concept it's still a container. Also the UI should be aware of this rule too, so it shouldn't allow for a greater number of items than it suppose to accept.

But let's say the shopping cart POST model get to the controller. It's easy to have a service or use directly the ShopppingCart object to validate the input. The point is, you expect this kind of situation so you deal with it as fast as possible. but if you decide that the UI shouldn't allow this to happen in the first place, then the ShoppingCart should throw an exception, because it's a bug (UI permitted an invalid operation).

Personally, I wouldn't have a ShoppingCart domain concept modeled. The ShoppingCart would be an input model used to create an Order from it.

As a thumb rule, if I expect some situations (which require to give feedback to the user) then I'd have some validation before I'm using the data to update the domain. The domain objects should throw everytime a business rule is violated. Once again, there isn't a recipe, I'd probably do different things in different apps.

The same way as in any other program: choose a method that works well with your team and with your implementation environment. Exceptions work fine.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top