将 DRY 原则应用到 JavaScript 中,帮我优化这段代码吗?

发布于 2024-12-03 16:39:19 字数 2370 浏览 1 评论 0原文

在寻找优化代码质量的方法时,我最终遇到了 DRY(不要重复自己)的概念。我尽力遵循这一点,但有时我不得不编写两个几乎相同的函数,除了 2 或 3 行代码之外,我在尝试找出最佳方法时耗尽了时间。组织它。

这就是我的“问题”。我在下面添加了几周前写的两个函数,除了最后的 3 行之外,它们基本上是相同的,并且一个通过加法制作动画,另一个通过减法制作动画。我很想从其他开发人员那里获得一些意见,了解他们如何优化下面的代码或者有解决类似问题的不相关代码的示例。

/**
 * Go to the previous notification
 *
 * @private
 * @param {object} cl Click event details (ex. {id: 'linkId', ss: '_', index: '1', e: event})
 * @memberOf APP.devices
 */
function slideNext (cl) {
    var button = $('#' + cl.id + cl.ss + cl.index),
        index = cl.index - 1,
        slider = devices[index].container.find('.slideContainer'),
        // In order to get the value of the 'right' position we must take the (container width - slider width - left position - right-margin)
        slidePos = (slider.parent().width() - slider.width()) + (slider.position().left * -1) + (parseFloat(slider.css('margin-right')) * -1);
    if (button.hasClass('disabled')) {
        return false;
    }
    slider.find('.active').removeClass('active').prev().addClass('active');
    disableButtons(index);
    slider.animate({'right': slidePos + notificationOffset}, 200, function () {
        determineButtonState(index);
    });
    updatePositionContext(index);
}


/**
 * Advance to the next notification
 *
 * @private
 * @param {object} cl Click event details
 * @memberOf APP.devices
 */
function slidePrev (cl) {
    var button = $('#' + cl.id + cl.ss + cl.index),
        index = cl.index - 1,
        slider = devices[index].container.find('.slideContainer');
        // In order to get the value of the 'right' position we must take the (container width - slider width - left position - right-margin)
        slidePos = (slider.parent().width() - slider.width()) + (slider.position().left * -1) + (parseFloat(slider.css('margin-right')) * -1);
    if (button.hasClass('disabled')) {
        return false;
    }
    slider.find('.active').removeClass('active').next().addClass('active');
    disableButtons(index);
    slider.animate({'right': slidePos - notificationOffset}, 200, function () {
        determineButtonState(index);
    });
    updatePositionContext(index);
    // Load more notifications once user get's close to the end of the current set of notifications
    if (slider.find('.active').nextAll().length == 3) {
        getMoreNotifications(index);
    }
}

While on the search for ways to optimize the quality of my code, I eventually came across the concept of DRY (Don't repeat yourself). I try to follow this as best I can but sometimes I get into positions where I have to write two functions that are practically identical, save for 2 or 3 lines of code and I run out of time while trying to figure out the best way to organize it.

So here's my "question." I've included two functions below that I wrote a couple weeks ago that are basically identical except for 3 lines at the end, as well as one does an animation by addition and the other with subtraction. I would love to get some input from other developers as to how they would optimize the code below OR have examples of unrelated code where you solved a similar problem.

/**
 * Go to the previous notification
 *
 * @private
 * @param {object} cl Click event details (ex. {id: 'linkId', ss: '_', index: '1', e: event})
 * @memberOf APP.devices
 */
function slideNext (cl) {
    var button = $('#' + cl.id + cl.ss + cl.index),
        index = cl.index - 1,
        slider = devices[index].container.find('.slideContainer'),
        // In order to get the value of the 'right' position we must take the (container width - slider width - left position - right-margin)
        slidePos = (slider.parent().width() - slider.width()) + (slider.position().left * -1) + (parseFloat(slider.css('margin-right')) * -1);
    if (button.hasClass('disabled')) {
        return false;
    }
    slider.find('.active').removeClass('active').prev().addClass('active');
    disableButtons(index);
    slider.animate({'right': slidePos + notificationOffset}, 200, function () {
        determineButtonState(index);
    });
    updatePositionContext(index);
}


/**
 * Advance to the next notification
 *
 * @private
 * @param {object} cl Click event details
 * @memberOf APP.devices
 */
function slidePrev (cl) {
    var button = $('#' + cl.id + cl.ss + cl.index),
        index = cl.index - 1,
        slider = devices[index].container.find('.slideContainer');
        // In order to get the value of the 'right' position we must take the (container width - slider width - left position - right-margin)
        slidePos = (slider.parent().width() - slider.width()) + (slider.position().left * -1) + (parseFloat(slider.css('margin-right')) * -1);
    if (button.hasClass('disabled')) {
        return false;
    }
    slider.find('.active').removeClass('active').next().addClass('active');
    disableButtons(index);
    slider.animate({'right': slidePos - notificationOffset}, 200, function () {
        determineButtonState(index);
    });
    updatePositionContext(index);
    // Load more notifications once user get's close to the end of the current set of notifications
    if (slider.find('.active').nextAll().length == 3) {
        getMoreNotifications(index);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

扮仙女 2024-12-10 16:39:19

使用基本标志,您几乎可以将其全部删除。我确信我缺少一个很好的理由来解释为什么你没有这样做,但我从来没有对 DRY 非常重视。请随时启发我:)

/**
 * Move to another notification
 *
 * @private
 * @param {object} cl Click event details (ex. {id: 'linkId', ss: '_', index: '1', e: event})
 * @param fw Whether to go forwards or backwards. Defaults to true (forwards)
 * @memberOf APP.devices
 */
function slideNext (cl, fw) {
    var button = $('#' + cl.id + cl.ss + cl.index),
        index = cl.index - 1,
        slider = devices[index].container.find('.slideContainer'),
        // In order to get the value of the 'right' position we must take the (container width - slider width - left position - right-margin)
        slidePos = (slider.parent().width() - slider.width()) + (slider.position().left * -1) + (parseFloat(slider.css('margin-right')) * -1);
        var distance = ((fw) ? slidePos + notificationOffset : slidePos - notificationOffset;
    if (button.hasClass('disabled')) {
        return false;
    }
    if (fw)
        slider.find('.active').removeClass('active').prev().addClass('active');
    else
        slider.find('.active').removeClass('active').next().addClass('active');
    disableButtons(index);
    slider.animate({'right': distance}, 200, function () {
        determineButtonState(index);
    });
    updatePositionContext(index);
    // Load more notifications once user get's close to the end of the current set of notifications
    if (!fw && slider.find('.active').nextAll().length == 3) {
        getMoreNotifications(index);
    }
}

Using a basic flag you can pretty much cut it all out. I'm sure there's a good reason I'm missing for why you haven't done that though, I've never been super-massively big on DRY. Feel free to enlighten me :)

/**
 * Move to another notification
 *
 * @private
 * @param {object} cl Click event details (ex. {id: 'linkId', ss: '_', index: '1', e: event})
 * @param fw Whether to go forwards or backwards. Defaults to true (forwards)
 * @memberOf APP.devices
 */
function slideNext (cl, fw) {
    var button = $('#' + cl.id + cl.ss + cl.index),
        index = cl.index - 1,
        slider = devices[index].container.find('.slideContainer'),
        // In order to get the value of the 'right' position we must take the (container width - slider width - left position - right-margin)
        slidePos = (slider.parent().width() - slider.width()) + (slider.position().left * -1) + (parseFloat(slider.css('margin-right')) * -1);
        var distance = ((fw) ? slidePos + notificationOffset : slidePos - notificationOffset;
    if (button.hasClass('disabled')) {
        return false;
    }
    if (fw)
        slider.find('.active').removeClass('active').prev().addClass('active');
    else
        slider.find('.active').removeClass('active').next().addClass('active');
    disableButtons(index);
    slider.animate({'right': distance}, 200, function () {
        determineButtonState(index);
    });
    updatePositionContext(index);
    // Load more notifications once user get's close to the end of the current set of notifications
    if (!fw && slider.find('.active').nextAll().length == 3) {
        getMoreNotifications(index);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文