Separation of Concerns The Simple Way
Tags: computerscience, beginners, soc
Published: 2020-12-20 01:44:33

It's tough hearing the truth.

That your 2000+ line program that is all written in one file.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/hu8hj841zcp7p8jgr8xc.gif)

but you already know that, or I hope you do.

I know you already tried making it more compact, but things just aren't making sense.

This is where the principle that transcends time and space comes, which helps us in all aspects of our life comes, it's called Separation of concerns or SoC.

I know it may sound intimidating but don't worry Uncle T is here and I will make stuff as simple as possible for your pleasure.

So today we are gonna go over these points:

1. What is separation of concerns?
2. Cohesion and Coupling
3. Why does it work?
4. Examples
5. Conclusion

So before further ado, get comfy, grab your favorite beverage, and wear your smart glasses, let's get started.

## What is separation of concerns?

Now in every blog post, you gotta add a quote so here's something I copied from [wikipedia](https://en.wikipedia.org/wiki/Separation_of_concerns)

> In computer science, separation of concerns is a design principle for separating a computer program into distinct sections such that each section addresses a separate concern.

Okay, now that formalities are over let me explain.

Separation of concerns is a universal principle that pretty much all people do, I'm not only talking about software development but it also applies to many other fields. Let's imagine we have a hospital called Uncle T Clinics, in our hospital, we have many employees with different roles to provide care to our patients: nurses, doctors, medical assistants, techs, clerical staff, cafeteria, etc.

Is there any one person that knows how *all* of those people get their jobs done?  No, because it would be overwhelming.  They have to separate out the different responsibilities into distinct roles and the touchpoints between those roles are very specific.

You might want to hear a more code-related example, so here's one for all you folks.

Lets take simple webpage as an example:

```html
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
h1   {color: blue;}
p    {color: red;}
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
<script>
console.log("hello world")
</script>
</html>
```

This is a perfectly working page, but the issue is that if we ever want to add more stuff to our webpage then things would get messy, mainly because our structure, style, and logic layers are close together. A better approach would look something like this:

```html
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
<script src="logic.js"></script>
	</html>
```

```jsx
// logic.js
console.log("hello world")
```

```css
/* styles.css */
body {background-color: powderblue;}
h1   {color: blue;}
p    {color: red;}
```

Right now our code is much more cleaner as we separated them into three different files that handle different layers. I know this is a super simple example but it can be applied on a bigger scale which will be shown in the examples section at the bottom half of the post.

## Cohesion and Coupling

Why are we talking about this? 

Well, because Separation of Concerns involves two processes: reduction of coupling and increasing cohesion.

### What is cohesion?

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/xikbg4cgydydtn3zzf1r.png)

Cohesion is the measure of how related a group of things is, for example in your kitchen you usually put the knives in the knife block, the spoons with spoons, the forks with forks, you get it. In computer science, it's how strong the relationship is between the methods and data of a class.

For example, you may have two functions like this:

```php
function drawCirle(){
   // draw a cirlce code
}

function drawRectangle(){
   // draw a rectangle code
}
```

These two functions are essentially very cohesive or similar enough to be in the same module/class which is responsible for drawing, and to be fair it feels very natural to put them together. It will look something like this:

```php
class Draw {

   public function drawCircle(){
	// draw a circle
   }

   public function drawRectangle(){
	// draw a rectangle
   }
}
```

### What is coupling?

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/rge7mdyrhixh81vjmjin.png)

Coupling is basically a measure of dependence between two or more classes, modules, or components. Tight coupling is bad, and loose coupling is good.

You should always try to write code that is highly cohesive and has low coupling. 

There are many benefits in this approach:

1. Better code clarity, it's much easier to understand what's going on when everything is neatly organized.
2. Better code reusability. When you reuse code, it's costs less to maintain it, it's also a lot easier to extend or to fix bugs because the code is only found in one place.
3. Better testability. When everything is neatly isolated, testing becomes a breeze. You don't have to set up a whole testing environment, you can simply mock neighboring modules with dummy data. This way you can test your module as a black box by verifying just the output, or as a white box by verifying which methods are being run.
4. Faster Development. Isolating modules helps in creating/updating new features.
5. Organizational. When everything is neatly separated engineers can have a better development experience, by agreeing on which modules to work on and not to interfere with each other.

## Why does it work so well?

Short answer: it's easier for our brains to process information when it's neatly separated.

Long answer: having your code organized in this manner makes it easy to read, maintain, and extend, but this is not only good for you but for your colleagues in multiple ways:

- The first is that these elements are often changed independently, in the example above you can change the styles without changing the structure. Or you may want to keep the logic but change the structure. Keeping them separate makes it easy to swap out one without keeping affecting the other.
- Another reason is that there are often different people responsible for different roles. For example, if you're creating a website, you might be responsible for the content and another person might be responsible for styles. Separating the concerns makes it easier for both individuals to work freely.
- A third reason is that it's just easier to find things. Let's say you wanna change the styles of the page, you go to the CSS file, you wanna change the content it's in the HTML file.

## Examples

I would never finish this post, if I had to list all the different kinds of domains that use this principle so here are the most common ones.

### Internet protocol stack

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/y9ipg8icjqvpx9a58myg.png)

Separation of concern is used when designing the internet. In the [internet protocol suite](https://en.wikipedia.org/wiki/Internet_protocol_suite), great efforts have been made to separate concerns into layers. This allows protocol designers to focus on the concerns of a single layer. For example, the application layer protocol [SMTP](https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol) is concerned about conducting an email session over a transport service which is usually TCP. But we don't care how TCP works when working with SMTP. Similarly, TCP does not care how the routing of data packets happens which gets handled at the internet layer.

### Model, View, Controller (MVC)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ky82e1erunz4rfwtie8a.png)

MVC is an architectural pattern that separates an application into three components:

1. Model - business layer
2. View - presentational layer
3. Controller - presentational layer

Each of these is built to handle a specific concern of the application.

MVC is the most popular architecture used in web development frameworks such as Laravel, Spring, and many others.

### Microservices

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/tfvy6pmasnglci6k4pqy.png)

Everyone and their mother is talking about microservices. What it basically is, it's a project that is made up of other small independent standalone projects. In essence, this is a form of separation of concerns. 

## Conclusion

I hope by the end of this, you got a better idea of what separation of concerns is about. Don't forget that this principle does not only apply to code, but to real life as well for example setting up goals and such. With this knowledge in hand, you can finally write code that your senior peers would be proud of.

Uncle T, out.

PS. I would really appreciate some criticism, I'm still new to this blogging thing.

## References

- [https://nalexn.github.io/separation-of-concerns/](https://nalexn.github.io/separation-of-concerns/)
- [https://www.sumologic.com/blog/5-patterns-better-microservices-architecture/](https://www.sumologic.com/blog/5-patterns-better-microservices-architecture/)
- [https://www.oreilly.com/library/view/programming-javascript-applications/9781491950289/ch05.html](https://www.oreilly.com/library/view/programming-javascript-applications/9781491950289/ch05.html)
- [https://en.wikipedia.org/wiki/Separation_of_concerns](https://en.wikipedia.org/wiki/Separation_of_concerns)
- [https://en.wikipedia.org/wiki/Coupling_(computer_programming)](https://en.wikipedia.org/wiki/Coupling_(computer_programming))
- [https://en.wikipedia.org/wiki/Cohesion_(computer_science)](https://en.wikipedia.org/wiki/Cohesion_(computer_science))
- [https://softwareengineering.stackexchange.com/questions/32581/how-do-you-explain-separation-of-concerns-to-others](https://softwareengineering.stackexchange.com/questions/32581/how-do-you-explain-separation-of-concerns-to-others)