什么时候重构代码?

发布于 2024-09-28 20:01:07 字数 292 浏览 3 评论 0原文

现有:
1.你永远没有时间去做这件事。
2.“上下文切换”在精神上是昂贵的(很难将你正在做的事情留在中间)。
3. 这通常不是一件容易的事。
4. 总是担心你会破坏正在运行的东西。

另一方面:
1. 使用该代码很容易出错。
2. 随着时间的推移,您可能会意识到,如果您在第一次看到代码时就对其进行了重构,从长远来看,这会节省您的时间。

所以我的问题是 - 实际上 - 你什么时候决定重构你的代码?

谢谢。

On on hand:
1. You never get time to do it.
2. "Context switching" is mentally expensive (difficult to leave what you're doing in the middle of it).
3. It usually isn't an easy task.
4. There's always the fear you'll break something that's now working.

On the other:
1. Using that code is error-prone.
2. Over time you might realize that if you had refactored the code the first time you saw it, that would have saved you time on the long run.

So my question is - Practically - When do you decide it's time to refactor your code?

Thanks.

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

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

发布评论

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

评论(9

十秒萌定你 2024-10-05 20:01:07

一些观察结果:

现有:
1. 你从来没有时间去做这件事。

如果您将重构视为与编码分开的事情(而不是像样地编码的固有部分),并且如果您无法管理时间,那么是的,您将永远没有时间去做它。

  1. “上下文切换”在精神上是昂贵的(很难将你正在做的事情留在中间)。

请参阅上面的前一点。重构是良好编码实践的一个积极组成部分。如果您将两者分开,就好像它们是两个不同的任务一样,那么 1)您的编码实践需要改进/成熟,2)如果您的代码迫切需要重构(再次强调代码质量),您将进行严格的上下文切换。 )

  1. 这通常不是一件容易的事。

仅当您生成的代码不适合重构时。也就是说,难以重构的代码表现出以下一项或多项(列表并不普遍包含):

  1. 高圈复杂度
  2. 每个类(或过程)没有单一责任,
  3. 高耦合和/或较差的低内聚性(又名较差的LCOM 指标),
  4. 结构不佳
  5. 不遵循 SOLID 原则
  6. 在适当的情况下不遵守德米特法则
  7. 在不适当的情况下过度遵守德墨忒尔法则
  8. 针对实现而不是接口进行编程。
  1. 总是担心您会破坏正在运行的东西。

测试?确认?分析?在检查到源代码控制之前(当然还有在交付给用户之前),其中有任何一个吗?

另一方面:
1. 使用该代码很容易出错。

仅当它从未测试/验证和/或没有清楚地了解潜在易错代码可接受的运行条件和使用模式时。

  1. 随着时间的推移,您可能会意识到,如果您重构代码
    当您第一次看到它时 - 从长远来看,这会节省您的时间。

这种认识不应该随着时间的推移而发生。良好的工程和职业道德要求在制造工件(硬件或软件)时实现这一点。

所以我的问题是 - 实际上 - 你什么时候决定重构你的代码?

实际上,当我编码时;我发现需要改进的地方(或者在需求或期望发生变化后需要纠正的地方);我有机会在不牺牲最后期限的情况下改进它。如果我当时无法重构,我只需记录感知到的缺陷并创建一个可行的、现实的计划来重新审视重构的工件。

在现实生活中,有时我们会编写一些丑陋的代码,只是为了让事情正常运行,或者因为我们精疲力竭、疲倦或其他原因。这是现实。我们的工作是确保这些事件不会堆积起来并且无人处理。而做到这一点的关键是在编码时进行重构,保持代码简单并具有良好、简单和优雅的结构。我所说的“优雅”并不是指“自作聪明”或深奥,而是显示了通常被认为是可读的、简单的、可组合的属性(以及实际应用时的数学属性)

。它显示出良好的指标;它的结构类似于计算机科学函数组合数学函数组合;有明确的责任;它使其不变量、前置条件和后置条件变得明显;等等等等。

希望有帮助。

A couple of observations:

On on hand:
1. You never got time to do it.

If you treat re-factoring as something separate from coding (instead of an intrinsic part of coding decently), and if you can't manage time, then yeah, you'll never have time for it.

  1. "Context switching" is mentally expensive (difficult to leave what you're doing in the middle of it).

See previous point above. Refactoring is an active component of good coding practices. If you separate the two as if they were two different tasks, then 1) your coding practices need improvement/maturing, and 2) you will engage in severe context switching if your code is in a severe need of refactoring (again, code quality.)

  1. It's usually isn't an easy task.

Only if the code you produce is not amenable to refactoring. That is, code that is hard to refactor exhibits one or more of the following (list is not universally inclusive):

  1. High cyclomatic complexity,
  2. No single responsibility per class (or procedure),
  3. High coupling and/or poor low cohesion (aka poor LCOM metrics),
  4. poor structure
  5. Not following the SOLID principles.
  6. No adherence to the Law of Demeter when appropriate.
  7. Excessive adherence to the Law of Demeter when inappropriate.
  8. Programming against implementations instead of interfaces.
  1. There's always the fear you'll break something that's now working.

Testing? Verification? Analysis? Any of these before being checked into source control (and certainly before being delivered to the users)?

On the other:
1. Using that code is error-prone.

Only if it has never tested/verified and/or if there is no clear understanding of the conditions and usage patterns under which the potentially error-prone code operates acceptably.

  1. Over time you might realize that if you would have refactored the code the
    first time you saw it - That would have save you time on the long run.

That realization should not occur over time. Good engineering and work ethics calls for that realization to occur when the artifact (being hardware or software) is in the making.

So my question is - Practically - When do you decide it's time to refactor your code?

Practically, when I'm coding; I detect an area that needs improvement (or something that needs correction after a change on requirements or expectations); and I get an opportunity to improve it without sacrificing a deadline. If I cannot re-factor at that moment, I simply document the perceived defect and create a workable, realistic plan to revisit the artifact for refactoring.

In real life, there will be moments that we'll code some ugly kludge just to get things running, or because we are drained and tired or whatever. It's reality. Our job is to make sure that those incidents do not pile up and remain unattended. And the key to this is to refactor as you code, keep the code simple and with a good, simple and elegant structure. And by "elegant" I don't mean "smart-ass" or esoteric, but that displays what is typically considered readable, simple, composable attributes (and mathematical attributes when they apply practically.)

Good code lends itself to refactoring; it displays good metrics; its structure resembles both computer science function composition and mathematical function composition; it has a clear responsibility; it makes its invariants, pre and post-conditions evident; and so on and so on.

Hope it helps.

双马尾 2024-10-05 20:01:07

我看到的最常见的错误之一是人们将“重构”一词与“大改变”联系在一起。

重构代码并不总是很大。即使是很小的更改,例如将 bool 更改为适当的枚举,或者将方法重命名为更接近实际功能而不是意图,都会重构您的代码。除了里程碑的结束之外,我每次签入时都会尝试至少进行一次非常小的重构。您会惊讶地发现这在代码中产生了明显的差异。

不过,更大的改变确实需要更大的规划。在正常的开发周期中,我尝试每两周安排大约每天 1/2 次,以应对更大的重构变更。这足以对代码库进行实质性改进。如果每天重构失败 1/2,损失也不算太大。而且这很少会是彻底的损失,因为即使是失败的重构也会教会你一些关于代码的知识。

One of the most common mistakes i see is people associating the word "Refactor" with "Big Change".

Refactoring code does not always have to be big. Even small changes such as changing a bool to a proper enum, or renaming a method to be closer to the actual function vs. the intent is refactoring your code. With the exception of the end of a milestone, I try to make at least a very small refactoring every single time I check in. And you'd be amazed at how quickly this makes a visible difference in the code.

Bigger changes do take bigger planning though. I try and schedule about 1/2 a day every two weeks during a normal development cycle to tackle a bigger refactoring change. This is enough time to make a substantial improvement to the code base. If the refactoring fails 1/2 a day is not that much of a loss. And it's rarely a total loss because even the failed refactoring will teach you something about your code.

楠木可依 2024-10-05 20:01:07
  1. 只要有气味,我就会重构。我现在或许还不能做到完美,但至少可以向更好的状态迈出一小步。随着时间的推移,这些微小的变化确实会累积起来……
  2. 如果我正在做某事,当我注意到气味时,修复它并不是微不足道的(或者我就在发布之前),我可能会做一个(心理或纸质的) )注意一旦我完成主要任务就返回它。
  3. 实践使人变得更好:-)但是如果我没有看到问题的解决方案,我会把它放在一边并让它酝酿一段时间,与同事讨论,甚至将其发布在SO上;-)
  4. 如果我不这样做没有单元测试并且修复并不简单,我从测试开始。如果测试也很重要,我将应用第 2 点。
  1. Whenever it smells, I refactor. I may not make it perfect now, but I can at least make a small step towards a better state. And those small changes do add up over time...
  2. If I am in the middle of something when I notice the smell, and fixing it isn't trivial (or I am just before release), I may make a (mental or paper) note to return to it once I am finished with the primary task.
  3. Practice makes one better :-) But if I don't see a solution to a problem, I put it aside and let it brew for a while, discuss it with coworkers, or even post it on SO ;-)
  4. If I don't have unit tests and the fix isn't trivial, I start with the tests. If the tests aren't trivial either, I apply point 2.
停滞 2024-10-05 20:01:07

一旦我发现自己在重复自己,我就开始重构。 DRY 原则。

另外,如果方法/函数变得太长,以至于它们看起来很笨拙,或者它们的目的被函数的长度所掩盖,我会将其分解为私有子函数来解释真正发生的事情。

最后,如果一切都正常运行,并且代码非常慢,我会开始考虑重构以提高性能。

I start to refactor as soon as I find I am repeating my self. DRY principles ftw.

Also, if methods/functions get too long, to the point where they look unwieldy, or their purpose is being obscured by the length of the function, I break it into private subfunctions that explain what is really going on.

Lastly, if everything's up and running, and the code is dog-slow, I start to look at refactoring for the sake of performance.

静谧 2024-10-05 20:01:07

在实现新功能时,我经常注意到,如果我正在处理的代码以不同的方式构建,那么任务会简单得多。在这种情况下,我通常会退一步,尝试先进行重构,只有完成后我才会继续实现新功能。

我还有一个习惯,就是在笔记或错误跟踪器中跟踪我想到的所有潜在改进。这些想法在那里酝酿了一段时间,其中一些不再那么引人注目,而合理的想法是在我致力于较小任务的一天中实现的。

When implementing a new feature I often notice that the task would be much simpler if the code I'm working on was structured in a different way. In this case I usually step back, try to do the refactoring first, and only after this is done I continue implementing the new feature.

I also have a habit to track all potential improvements that come to my mind either in notes or the bug tracker. The ideas bake there for some time, some of them don't feel so compelling anymore, and the reasonable ones are implemented during a day which I dedicate to smaller tasks.

可爱暴击 2024-10-05 20:01:07

当需要重构时重构代码。我寻找的一些症状:

  • 相似对象中的重复代码。
  • 一个对象的方法内出现重复代码。
  • 每当需求发生两次或多次更改时。
  • 任何时候有人说“我们稍后会清理它”。
  • 任何时候我读完代码并摇头思考“哪个傻瓜做了这个”(即使有问题的傻瓜是我)

一般来说,较少的设计和/或不太明确的需求意味着更多的重构机会。

Refactor code when it needs to be refactored. Some symptoms I look for:

  • duplicate code in similar objects.
  • duplicate code in within methods of one object.
  • anytime the requirements have changed twice or more.
  • anytime somebody says "we will clean that up later".
  • any time I read through code and shake my head thinking "what goofball did this" (even when the goofball in question is me)

In general, less design and/or less clear requirements means more oppurtunities for refactoring.

独夜无伴 2024-10-05 20:01:07

这听起来可能像个笑话,但实际上,我只在事情“变得混乱”时才进行重构。当一个简单的任务开始花费更多的时间和平常一样时,当我必须扭转我的思维来记住哪个函数正在做什么等等时。另外,如果代码开始运行缓慢,并且不是因为我在开发环境中运行(有很多可变输出等),如果我无法优化它,我会重构代码。正如你所说,从长远来看,这是值得的。

尽管如此,我总是确保在开始之前有足够的时间来思考问题,这样我就不会陷入这种情况。

干杯!

This might sound like a joke, but really, I only refactor when things "get messy". When a simple task starts taking more time and usual, when I have to twist my mind around to remember what function is doing what and such. Also, if the code starts running slow and it's not because I'm running in a development enviroment (a lot of variable outputs and such) if I can't optimise it, I refactor the code. As you said, it's worthed on the long run.

Still, I allways make sure I have enough time to think things through before I start so I don't get in this sittuation.

Cheers!

时光清浅 2024-10-05 20:01:07

当出现以下情况之一时,我通常会进行重构:

  • 我没有更好的事情可做,正在等待下一个项目进入我的收件箱
  • 我对代码所做的添加/更改无法工作,除非,或者如果我重构
  • 我对代码的布局方式在审美上不满意

I usually refactor when one of the following is true:

  • I have nothing better to do and waiting for the next project to come to my inbox
  • The additions/changes I'm making to the code cannot work unless, or would be better if, I refactor
  • I am aesthetically displeased with the way the code is laid out
一梦等七年七年为一梦 2024-10-05 20:01:07

Martin Fowler 在他的中,如果同名建议您第三次这样做您正在代码块中进行另一项更改。第一次进入该块时,您碰巧注意到应该重构,但没有时间。第二次回来……同样的事情。第三次回溯重构。
另外,我读到当前版本的smalltalk(我想是squeak.org)的开发人员说他们经历了几周的紧张编码……然后他们退后一步看看可以重构什么。
就我个人而言,我必须在编码时抵制重构的冲动,否则我就会“瘫痪”。

Martin Fowler in his book if the same name suggests you do it the third time you're in a block of code to make another change. First time in the block, you happen to notice you should refactor, but don't have time. Second time back...same thing. Third time back-now refactor.
Also, I read the developers of a current release of smalltalk (squeak.org, I think) say they go through a couple weeks of intense coding...then they step back and look at what can be refactored.
Personally I have to resist the impulse to refactor as I code or I get 'paralyzed'.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文