首頁  >  文章  >  web前端  >  關注點分離和墨菲定律

關注點分離和墨菲定律

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-07 06:17:02511瀏覽

Separation of concern & Murphy

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');
});



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;



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


  • 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!');        });



以上是關注點分離和墨菲定律的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn