可怕的 While (True) 循环的最佳重构 [英] Best refactoring for the dreaded While (True) loop

查看:14
本文介绍了可怕的 While (True) 循环的最佳重构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果像我一样,你在 While (True) 循环的地方发抖,那么你一定也深思熟虑了将它重构掉的最佳方法.我见过几种不同的实现,没有一个比任何其他实现更好,例如计时器和;委托组合.

If, like me, you shiver at the site of a While (True) loop, then you too must have thought long and hard about the best way to refactor it away. I've seen several different implementations, none really better than any other, such as the timer & delegate combination.

那么您想出或看到的重构可怕的 While (True) 循环的最佳方法是什么?

So what's the best way you've come up with or seen to refactor the dreaded While (True) loop?

编辑:正如一些评论所提到的,我的意图是让这个问题成为一个无限循环"重构,例如运行 Windows 风格的服务,其中唯一的停止条件是 OnStop 或致命的例外.

Edit: As some comments mentioned, my intent was for this question to be an "infinite loop" refactoring, such as running a Windows style service where the only stop conditions would be OnStop or a fatal exception.

推荐答案

我们真的需要重构 while(true) 循环吗?有时它是一种编码标准,大多数开发人员已经习惯了这种结构.如果你必须认真思考如何重构这段代码,你确定重构它是个好主意吗?

Do we really need to refactor while(true) loops? Sometimes it's a coding standard and most of the developers has got used to this structure. If you have to think hard on how to refactor this code, are you sure it's a good idea to refactor it?

Goto 曾经是编码标准中的害群之马.我遇到过goto 使代码更具可读性和更短的算法.有时不值得重构(或者使用 goto 更好).

Goto used to be a black sheep in coding standards. I've met algorithms where goto made the code much more readable and shorter. Sometimes it doesn't worth to refactor (or better to use goto).

另一方面,您可以在大多数情况下避免while(true).

On the other hand you can avoid while(true) most of the time.

这篇关于可怕的 While (True) 循环的最佳重构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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