逐行迭代文本文件的内容 - 是否有最佳实践?(相对于 PMD 的 AssignmentInOperand) [英] Iterating over the content of a text file line by line - is there a best practice? (vs. PMD's AssignmentInOperand)

查看:9
本文介绍了逐行迭代文本文件的内容 - 是否有最佳实践?(相对于 PMD 的 AssignmentInOperand)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个 Java 应用程序,其中有几个模块可以读取文本文件.他们用这样的代码很简单地做到了:

We have a Java Application that has a few modules that know to read text files. They do it quite simply with a code like this:

BufferedReader br = new BufferedReader(new FileReader(file));  
String line = null;  
while ((line = br.readLine()) != null)  
{  
   ... // do stuff to file here  
} 

我在我的项目上运行了 PMD 并在 while (...) 行上发现了AssignmentInOperand"违规.

I ran PMD on my project and got the 'AssignmentInOperand' violation on the while (...) line.

除了显而易见的循环之外,还有没有更简单的方法来做这个循环:

Is there a simpler way of doing this loop other than the obvious:

String line = br.readLine();  
while (line != null)  
{  
   ... // do stuff to file here  
   line = br.readLine();  
} 

这被认为是更好的做法吗?(虽然我们复制"了 line = br.readLine() 代码?)

Is this considered a better practice? (although we "duplicate" the line = br.readLine() code?)

推荐答案

我通常更喜欢前者.我一般不喜欢比较中的副作用,但这个特殊的例子是一个习语,它是如此常见和方便,以至于我不反对它.

I generally prefer the former. I don't generally like side-effects within a comparison, but this particular example is an idiom which is so common and so handy that I don't object to it.

(在 C# 中有一个更好的选择:一种返回 IEnumerable 的方法,您可以使用 foreach 对其进行迭代;这在 Java 中没有那么好,因为在增强的 for 循环的结束...还因为您不能从迭代器中抛出 IOException,这意味着您不能只是将一个替换为另一个.)

(In C# there's a nicer option: a method to return an IEnumerable<string> which you can iterate over with foreach; that isn't as nice in Java because there's no auto-dispose at the end of an enhanced for loop... and also because you can't throw IOException from the iterator, which means you can't just make one a drop-in replacement for the other.)

换句话说:重复行问题比操作数内赋值问题更困扰我.我习惯于一目了然地接受这种模式 - 对于重复的行版本,我需要停下来检查一切是否都在正确的位置.这可能和其他任何事情一样都是习惯,但我认为这不是问题.

To put it another way: the duplicate line issue bothers me more than the assignment-within-operand issue. I'm used to taking in this pattern at a glance - with the duplicate line version I need to stop and check that everything's in the right place. That's probably habit as much as anything else, but I don't think it's a problem.

这篇关于逐行迭代文本文件的内容 - 是否有最佳实践?(相对于 PMD 的 AssignmentInOperand)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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