任何有效的代码重复的原因? [英] Any valid reason for code duplication?

查看:175
本文介绍了任何有效的代码重复的原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在审查一个非常古老的C ++项目,并看到很多代码重复。

I'm currently reviewing a very old C++ project and see lots of code duplication there.

例如,有一个类有5个MFC消息处理程序10个相同的代码行。或者有一个5行代码片段,用于非常特定的字符串变换。减少代码重复在这些情况下根本不是一个问题。

For example, there is a class with 5 MFC message handlers each holding 10 identical lines of code. Or there is a 5-line snippet for a very specific string transformation every here and there. Reducing code duplication is not a problem in these cases at all.

但我有一个奇怪的感觉,我可能会误会一些东西,并且最初有一个原因这种重复。

But I have a strange feeling that I might be misunderstanding something and that there was originally a reason for this duplication.

重复代码的有效理由是什么?

What could be a valid reason for duplicating code?

推荐答案

当我第一次开始编程时,我写了一个应用程序,我有一堆类似的功能,我包装在一个整洁的小20-30行功能...我为自己感到非常自豪,写这样优雅的代码。

When I first started programming, I wrote an app where I had a bunch of similar functionality which I wrapped up in a neat little 20-30 line function ... I was very proud of myself for writing such an elegant piece of code.

不久之后,客户端在非常特定的情况下,然后再次,然后又一次,然后又一次又一次...更改了过程(许多更多次)我的优雅的代码变成一个非常困难,黑客,越野车,高维护混乱。

Shortly after, the client changed the process in very specific cases, then again, then again, then again , and again, and again .... (many many more times) My elegant code turned into a very difficult, hackish, buggy, & high maintenance mess.

一年后,当我被要求做一个非常相似的事情时,我故意决定忽略DRY。我把基本过程放在一起,并生成了所有重复的代码。重复的代码被记录,我保存了用于生成代码的模板。当客户端请求特定的条件更改(像,如果x == y ^ z + b然后1 + 2 == 3.42),这是一块蛋糕。这是令人难以置信的容易维护&改变。

A year later, when I was asked to do something very similar, I deliberately decided to ignore DRY. I put together the basic process, and generated all duplicate code. The duplicate code was documented and I saved the template used to generate the code. When the client asked for specific conditional change (like, if x == y^z + b then 1+2 == 3.42) it was a piece of cake. It was unbelievably easy to maintain & change.

回想起来,我可能可以用函数指针和谓词解决很多这些问题,但是使用当时的知识,我仍然相信这个具体情况下,这是最好的决定。

In retrospect, I probably could have solved many of these problems with function pointers and predicates, but using the knowledge I had at the time, I still believe in this specific case, this was the best decision.

这篇关于任何有效的代码重复的原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆