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