DEV Community

Cover image for Separation of Concerns The Simple Way
Tamerlan Gudabayev
Tamerlan Gudabayev

Posted on • Updated on

Separation of Concerns The Simple Way

It's tough hearing the truth.

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

Alt Text

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

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:

<!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>
Enter fullscreen mode Exit fullscreen mode

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:

<!-- 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>
Enter fullscreen mode Exit fullscreen mode
// logic.js
console.log("hello world")
Enter fullscreen mode Exit fullscreen mode
/* styles.css */
body {background-color: powderblue;}
h1   {color: blue;}
p    {color: red;}
Enter fullscreen mode Exit fullscreen mode

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

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:

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

function drawRectangle(){
   // draw a rectangle code
}
Enter fullscreen mode Exit fullscreen mode

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:

class Draw {

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

   public function drawRectangle(){
    // draw a rectangle
   }
}
Enter fullscreen mode Exit fullscreen mode

What is coupling?

Alt Text

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

Separation of concern is used when designing the internet. In the 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 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

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

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

Top comments (2)

Collapse
 
konung profile image
konung

Good post .

A couple of personal gripes I have with MVC that apply. I think MVC often breaks separation of concerns, when people follow it blindly.

  1. I don’t think it’s correct to call controller layer a presentation layer. I believe it causes people to use it inappropriately. It should be called a routining layer, because it should be responsible for routing requests and nothing more . Instead it often end up housing business rules, as well as bits of presentation - such as converting view data to JSON or XML
  2. Model layer should not be responsible for business logic except in most simple apps . It should be responsible only for data layer - ie ORM. Business logic normally benefits from being separated into ServiceObjects that are loosely coupled with the Model layer.
Collapse
 
otumianempire profile image
Michael Otu

superb..