哪个更好 - 使用字符串或文件作为参数类型的方法,采取文件名 [英] Which is better - using String or File as parameter type for methods that take filenames

查看:121
本文介绍了哪个更好 - 使用字符串或文件作为参数类型的方法,采取文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个方法把文件名作为参数。我怀疑是什么是更好的方法来声明这些方法的参数。


  • 如果参数是字符串

      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屋!

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