【问题标题】:node require all or only specific节点需要全部或仅特定的
【发布时间】:2016-03-02 12:49:22
【问题描述】:

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

示例:

这是我的帮助文件

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

【问题讨论】:

    标签: javascript node.js require


    【解决方案1】:

    您可能想要要求整个文件。如果您最终更改了 util 文件中的名称或功能,那么将所有内容拆分会变得更加困难。我想这有点个人偏好,但在后一种选择中,您更依赖于 util.代码片段将非常紧密地耦合。这也遵循了具有单个对象的 OOP 方式,它根据需要公开了几种使用方法。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 2021-09-14
      • 2016-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      相关资源
      最近更新 更多