Wrapping Things Inside a Service

Learn how to create a cart service and move all the heavy cart functionality codes from the controller to the service.

Right now, the addToCart functionality is part of the controller, which doesn’t reflect good design.

This is why the code for addToCart() is so dense, because we don’t have all those temporary variables and intermediate bits of state. By cutting that out, what’s left are operations that do the real lifting. Each line moves things forward. Hence, we’ll simply move it to a different service.

A consequence of this is that our web controllers can quickly get too heavy. It’s recommended that we keep controllers light and focused on handling web requests, not business logic.

All that code involved with retrieving the cart and adding items should probably be pushed down into a service.

Create a cart service

Let’s take a look at the code for our CartService below:

Get hands-on with 1400+ tech skills courses.