Do you always need to separate services and controllers?
Tags: node, javascript
Published: 2020-02-19 13:57:56

---
title: Do you always need to separate services and controllers?
published: true
canonical_url: https://www.coreycleary.me/do-you-always-need-to-separate-services-and-controllers/
tags: node,javascript
---

<em><strong>Originally published at <a href="https://www.coreycleary.me/do-you-always-need-to-separate-services-and-controllers/">coreycleary.me</a></strong>. This is a cross-post from my content blog. I publish new content every week or two, and you can <a href="https://www.coreycleary.me/about/">sign up to my newsletter</a> if you'd like to receive my articles directly to your inbox! I also regularly send cheatsheets and other freebies.</em>

You might have heard that you should separate your web logic (HTTP routes, middleware, and <strong>controllers</strong>) from your business logic (<strong>services</strong>). <a href="https://www.coreycleary.me/why-should-you-separate-controllers-from-services-in-node-rest-apis/" target="_blank" rel="noopener noreferrer">I've written about this before</a>, and I highly recommend giving it a read if you haven't yet, as it will form the basis of the rest of this post.

But as a recap, you want to pull out business logic code into services because:
<ul>
 	<li>Controllers can end up doing lots of things - AKA "fat controllers".</li>
 	<li>Closely related to the previous one, your code looks cluttered. With controllers making 4 or 5 or more database/model calls, handling the errors that could come with that, etc., that code probably looks pretty ugly.</li>
 	<li>All your logic in your controllers makes it really difficult to writes tests.</li>
 	<li>Requirements change, or you need to add a new feature and it becomes really difficult to refactor.</li>
 	<li>Code re-use becomes pretty much <em>non-existent</em>.</li>
</ul>
But what if your route <em>isn't</em> doing that much? What if all it needs to do is fetch an item from the database and return it?

Something like this:
```javascript
// route
router.post('/search', itemController.search)
```
```javascript
// item controller
const search = async (req, res, next) =&gt; {
  const { term } = req.body
  const items = await itemService.searchItems(term)
  res.send(items)
}
```
```javascript
// item service
const searchItems = async (term) =&gt; {
  return itemQuery.search(term)
}
```
```javascript
// item database query
const search = async (term) =&gt; {
  return db.select('*').from('item').where('name', 'like', '%${term}%')
}
```
Do you <em>really</em> need to create that service if all it's doing is calling the database and nothing else? Or can you just put that database code in the controller itself?

Let's dive into the <strong>pros</strong> and <strong>cons</strong> so you are better equipped to make a choice.
<h3>Approach 1 - Going with a service no matter what</h3>
Even if all you need to do is make a database call and return that result from your route, let's imagine you put that database call logic in a separate service and not just a controller. What would the effects of this be?

<strong>PROS:</strong>
<ul>
 	<li>(Avoid all the issues described above)</li>
 	<li>You get "thin" controllers, right from the start</li>
 	<li>Can write tests much more easily, right from the start</li>
 	<li>Easier to refactor when requirements change... your code is already separated into a service rather than it all bunching up in the controller, right from the start</li>
</ul>
These are all pretty big advantages, but let's look at a disadvantage I see with this approach.

<strong>CONS:</strong>
<ul>
 	<li>You have an extra file (`item.service.js`), which results in more wiring up (importing/exporting) you have to do</li>
</ul>
Now, in my opinion, this is not that big a deal... the advantages far outweigh this minor inconvenience, and as your app grows with code and features, you're likely going to have to pull the business logic out into a service if you haven't already done so anyways.
<h3>Approach 2 - Skipping the service, just putting business logic in controller</h3>
Now let's take a look at the advantages and disadvantages of the opposite approach.

<strong>PROS:</strong>
<ul>
 	<li>There is less wiring up you have to do - you can put all the code in your controller and not have to add separate service and/or database/models files.</li>
 	<li>If the route is simple, it can be easier to see all your logic in one file.</li>
</ul>
<strong>CONS:</strong>
<ul>
 	<li>Off the bat, you pretty much have to test your app <strong>only through the route</strong>, <a href="https://www.coreycleary.me/faking-errors-to-test-error-scenarios-in-express-apis/" target="_blank" rel="noopener noreferrer">using something like supertest</a>.</li>
 	<li>You can't <em>unit</em> test your code, with all that logic in one place, right now it's all an integration test.</li>
 	<li>When the app gets more complex, future refactoring has the potential to more difficult. The more logic you need to pull out and isolate into a service, the more potential for breaking things and introducing new bugs.</li>
</ul>
Let's imagine that the <code>search</code> controller we described at the beginning of this post now needs to do check against a separate service for how those search results should be ranked and check a different service for promotional deals on those items we are returning from the search. It just got much more complex, and shoving all that logic in the controller is going to get messy. Quickly.
<h3>Conclusion</h3>
If you can live with the extra wiring up work, my recommendation is to include the service, even if it's simple. If you've worked in software development for even a short amount of time, you know how quickly and how often requirements can be changed, added, or removed. With those requirements changes comes changes to the business logic, which means the controller will get more complex and you're going to have to pull that logic out into a service anyways. So might as well start off with having the service.

If this is a small side project and you're writing throwaway code, or if you're at a hackathon and working against the clock to ship something fast, putting that business logic / database access code in the controller is probably fine. But if this is going to be a project that will be in production and worked on by several developers, start off with the service.

As always, each app is unique and has unique requirements and design. But use the above comparison the next time you are faced with making this decision and it will help guide you in your design choices.

Love JavaScript but still getting tripped up by architecture stuff and how you should structure your service? I publish articles on JavaScript and Node every 1-2 weeks, so if you want to receive all new articles directly to your inbox, <a href="https://www.coreycleary.me/about/">here's that link again</a> to subscribe to my newsletter!