重新审视DRY原则

DRY Principle Reexamined

大多数程序员都是自学成才或受过大学教育,一次就接触了DRY原则。 它通常是作为方法和OOP的赛格威引入的。 例如,如果跨代码库多次计算购物清单的价格:

    void method1(){
        ...
        for(Item item: items){
            price += item.cost;
        }
        price *= 1.13;
        price -= customer.discount();
        ...
    }

    void method2(){
        ...
        for(Item item: items){
            price += item.cost;
        }
        price *= 1.13;
        price -= customer.discount();
        ...
    }

您会被教导将这种逻辑封装到一个方法中。 这有助于使您的代码库更小,更干净并且更易于维护。

    int calculateCost(Item[] items, Customer customer){
        int cost = 0;
        for(Item item: items){
            cost += item.cost;
        }
        price *= 1.13;
        price -= customer.discount();
        return cost;
    }

这一切都很好,很花哨,大多数程序员对此都感到满意。 但是,DRY原理不仅适用于您的代码,还适用于标准库和您正在使用的库。

让我们从一个示例开始,我们要创建一个返回区别在。。之间最大值和分元素数组。

int maxmin_difference(int[] array){
    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;

    for(int i: array){
        min = Math.min(min, i);
        max = Math.max(max, i);
    }

    return max - min; // not worrying about integer overflow
}

如果大多数开发人员在代码审查中看到了这一点,他们会很高兴,因为它相对简单直观。 但是我认为这违反了DRY原则,Java标准库已经附带了Collections.max()和Collections.min()功能。

int maxmin_difference(List<Integer> array){
    return Collections.max(array) - Collections.min(array); // not worrying about integer overflow
}

Utilizing those methods will clean up our code and remove the nuances around initializing min/max correctly.

PS: Much of the inspiration of this post, including this example, comes from a fantastic talk given by Conor Hoekstra.

依靠经过严格测试和广泛测试的代码是防止bug并违反DRYOTCAY(不要重复自己或周围的代码)的最佳方法。

想象一下您正在构建的构建为Lego Block的软件,每当您选择一件作品时,都可以使用官方的Lego Block™或自制的Lego Block。

Lego blocks

使用正式的Lego积木时,您会知道其结构合理且能胜任工作(例如语言附带的标准库),这些积木是首选的材料选择。 但是,有时需要添加一些魔术/胶水才能使最终修饰恰到好处。 添加的自制块越多,未知的结构完整性就越大。

理想情况下,您的程序只需一行即可调用标准库。

public static void main(String[] args){
    Library.doMyCoolStuff(args);
}

Unfortunately this is unlikely to be the case and custom code will need to be written. This is perfectly fine, but attempting to reinvent the wheel for everything when a function/library already exists is a BAD DECISION. Instead really learn your languages standard library and the ecosystem of libraries available to you. As well when Googling for help, don't fall into the XY Problem, your problem is likely not as unique as you think it is.

Copied over from http://kwojcicki.github.io/

from: https://dev.to//kwojcicki/the-dry-principle-reexamined-4bjk

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值