节点需要全部或仅特定

node require all or only specific

本文关键字:全部 节点      更新时间:2023-09-26

我想知道只要求我们想要的特定属性还是整个对象更好。

示例:

这是我的助手文件

'use strict';
/**
 * getCallback
 * return a function used to make callback
 * @param {callback} callback - the callback function
 * @returns {Function}
 */
function getCallback(callback) {
    let cb = (typeof callback === 'function')
        ? callback
        : function() {};
    return cb;
}
/**
 * Random Number function
 * This function give a random number min and max
 * @param {number} [min=0] - min number you can get
 * @param {number} [max=1] - max number you can get
 * @returns {Number}
 */
function randomNumber(min, max) {
    let _min = (min) ? parseInt(min) : 0;
    let _max = (max) ? parseInt(max) : 1;
    return Math.floor((Math.random() * _max) + _min);
}
/**
 * Random String function
 * This function give a random string with the specified length
 * @param {number} length - length of the string
 * @param {string} chars - char you want to put in your random string
 * @returns {String}
 */
function randomString(length, chars) {
    let text = '';
    chars = (chars) ? chars : 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    for (let i = 0; i < length; i++) {
        text += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return text;
}
exports.getCallback = getCallback;
exports.randomNumber = randomNumber;
exports.randomString = randomString;

这里还有一个需要两个这个辅助函数的文件

这样做更好吗

'use strict';
const util = require('./helpers/util.helper');
console.log(util.randomNumber(0, 10));
console.log(util.randomString(10));

或者这个

'use strict';
const randomNumber = require('./helpers/util.helper').randomNumber;
const randomString = require('./helpers/util.helper').randomString;
console.log(randomNumber(0, 10));
console.log(randomString(10));

您可能希望需要整个文件。如果您最终更改了 util 文件中的名称或功能,将所有内容拆分会使事情变得更加困难。我想这有点个人喜好,但在后一个选项中,您更依赖于实用程序的内部。这些代码片段将非常紧密地耦合在一起。这也遵循具有单个对象的 OOP 方式,该方式公开了多个方法以供根据需要使用。

例如,在

后一个选项中,您必须在三个位置更改方法名称,而不是第一个选项中的方法名称。

在此处查看有关耦合的更多信息: https://en.wikipedia.org/wiki/Coupling_(computer_programming)