if语句或for循环中的长代码块 [英] Long code blocks inside if statements or for loops

查看:218
本文介绍了if语句或for循环中的长代码块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个关于编码风格的跨语言问题。

This is a cross language question on coding style.

我必须使用很多代码,它们具有很长的代码块, if语句或for循环。代码是程序性的。

I have to work with a lot of code that has very long code blocks, sometimes hundreds of lines, inside if statements or for loops. The code is procedural.

代码如下

if(condition){
    //hundreds of lines of code
}else if{
    //hundreds of lines of code
} else {
    //hundreds of lines of code
}



如果我没有在而因为我不断地来回滚动来检查我所在语句的哪个分支,或者我是在一个循环中,还是循环迭代器被调用。

I have trouble navigating this code if I haven't seen it in a while because I constantly have to scroll back and forth to check which branch of the statement I'm in or whether I'm in a loop, or what the loop iterator is called.

我的希望是将一长串代码放在函数中,并从语句的分支或循环内部调用它们,因此循环和if树更短,因此更易读。我会创建一些明智的代码仓库函数,而不仅仅是简单地剪掉当前的代码。

My hunch is to put pieces of the long lines of code inside functions and call them from within the branches of the statements or inside the loops, so the loops and if trees are shorter and therefore more readable. I'd create functions that are sensible code-silos ofcourse, not just cut up the current code haphazardly.

但是,这里是我的问题:这是个好主意吗?或者是不是一种坏的编码风格,在if语句或for循环中有几百行代码?我不是一个真正有经验的程序员,但我很喜欢干净的代码:)

But, and here's my question: is that a good idea? Or is it not a bad coding style to have hundreds of lines of code inside an if statement or a for loop? I'm not a really experienced programmer but I do appreciate clean code :)

谢谢!


几百行代码不重复,大多数时间。我理解并尝试坚持DRY原则。

Added: The hundreds of lines of code are not repetitive, most of the time. I understand and try to adhere to the DRY principle of course.

推荐答案

通常是一个好主意,的方法在一个屏幕上。如果你必须向上和向下滚动太多(有些人会争论),那么你会有丢失信息的风险。

It's generally a good idea to be able to see the whole of a method on one screen. If you have to scroll up and down too much (some would argue at all) then you run the risk of missing information.

因此,一般来说你提出的是一个好主意。虽然你不需要把一个分支中的所有代码放到一个方法中。可能会有重复的代码段,因此您可以按如下方式分解它:

So in general what you're proposing is a good idea. Though you needn't go as far as putting all the code in one branch into one method. There might be repeated sections of code so you could break it up as follows:

if(condition){
    CommonMethod();
    SpecificMethodA();
}else if{
    CommonMethod();
    SpecificMethodB();
} else {
    CommonMethod();
    SpecificMethodC();
}

虽然重构的确切性质完全取决于您的代码。

as an example. Though the exact nature of the refactoring will depend totally on your code.

这篇关于if语句或for循环中的长代码块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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