哪个更好 - 使用字符串或文件作为参数类型的方法,采取文件名 [英] Which is better - using String or File as parameter type for methods that take filenames
问题描述
我有几个方法把文件名作为参数。我怀疑是什么是更好的方法来声明这些方法的参数。
-
如果参数是
字符串
void normalizeData(String inFile)
-
还是应该显式声明参数为
File
。b
$ >就我个人而言,我发现File
更直观,但是想知道什么是这种事情的最佳实践。解决方案我会传递
java.io.InputStream
- 这使得代码更容易测试,将它绑定到文件系统。
这样你的代码就会变成:
public void normalizeData(InputStream in)
{
...
}
并调用它:
myObject.normalizeData(new FileInputStream(myFile));
或
myObject.normalizeData(new FileInputStream(c:/myfile.txt));
或者在测试中
myObject.normalizeData(new ByteArrayInputStream(some test data.getBytes()));
I have a couple of methods which take filenames as parameters. My doubt is that what is better way to declare the parameters of these methods.
Should the parameter be of type
String
void normalizeData(String inFile)
Or should I explicitly declare the parameter as
File
.void normalizeData(File inFile)
Personally I find
File
more intuitive but want to know about what is the best practice for such things.解决方案I would pass an
java.io.InputStream
- this makes the code easier to test and doesn't bind it to the file system.This way your code ends up like:
public void normalizeData(InputStream in) { ... }
And calling it:
myObject.normalizeData(new FileInputStream(myFile));
Or
myObject.normalizeData(new FileInputStream("c:/myfile.txt"));
Or in a test
myObject.normalizeData(new ByteArrayInputStream("some test data".getBytes()));
这篇关于哪个更好 - 使用字符串或文件作为参数类型的方法,采取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!