首頁 > web前端 > js教程 > 主體

關注點分離和墨菲定律

Mary-Kate Olsen
發布: 2024-10-07 06:17:02
原創
460 人瀏覽過

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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!