DEV Community

Fullstack Dev
Fullstack Dev

Posted on

Separation of concern & Murphy's law

Anything that can go wrong will go wrong is what Murphy's law tells us. This comes as a principle in software engineering known as separation of concern.

Separation of concern is a design principle in programming used to break an application into sections or modules.

SoC ensures that each section is responsible for a specific aspect of functionality or behavior. this ensures that the applications is easy to maintain and easy to scale.

This principle allows us to create reusable components that can be used across the entire application.

Murphy's Law in Separation of Concerns

When multiple aspects or functionalities are mixed or are in one file in your code something will eventually break.

By separating concerns for example by separating the express application and the web server the chances that everything will break Is reduced.

if there's an issue in your express app it won't affect the logic of your application. The more you compartmentalized the behavior or responsibility of your application the chances of a one failure affecting your entire application becomes slimmer.

example where no SoC was applied:



const express = require('express');
const app = express();

// Application logic (handling routes)
app.get('/hello', (req, res) => {
  res.send('Hello, World!');
});

// Server logic (listening on a port)
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});



Enter fullscreen mode Exit fullscreen mode

Here's how murphy's law works

  • if the server failure happens (port is already in use), you won't be able to test your routes and the entire app tops working.

Example where SoC was applied



//app.js
const express = require('express');
const app = express();

// Application logic (handling routes)
app.get('/hello', (req, res) => {
  res.send('Hello, World!');
});

module.exports = app;


Enter fullscreen mode Exit fullscreen mode


//server.js
const app = require('./app'); 
// Server logic (listening on a port)
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});


Enter fullscreen mode Exit fullscreen mode
  • if the server fails to start the application will still be able to work since your application logic is safe.

  • You can still test your application logic without directly running the server by using testing frameworks like jest and supertest



const request = require('supertest');  
const app = require('./app');          

// Test case for GET /hello
test('GET /hello should return "Hello, World!"', async () => {
  const response = await request(app).get('/hello');  
  expect(response.text).toBe('Hello, World!');        });



Enter fullscreen mode Exit fullscreen mode

Top comments (0)