is this bad programming ? scanner as global variable [closed]

被刻印的时光 ゝ 提交于 2019-12-10 13:19:04

问题


Is it considered bad programming practice to have an input scanner (such as a keyboard ) declared as a global var for a class? such like:

private static Scanner input  = new Scanner(System.in);

Im working with alot of input from various methods, and just seems alot easier then having to send the keyboard to each method


回答1:


It seems a lot easier to use a global variable, but in the long run, it can make the code very hard to maintain, have you thought about creating a class to handle the keyboard input? By having a good separation of concerns, you end up with cleaner code.

https://en.wikipedia.org/wiki/Separation_of_concerns




回答2:


It's best if you created a special class for getting Inputs and/or produce Outputs for example

class IO{
Scanner scanner ;
public Scanner getScanner(){

return new Scanner();
}
public Scanner getScanner(File file){
return new Scanner(new FileReader(file));
}
... // other types of scanners
}



回答3:


Depending on how the object should be used would define where to put it.

If the Scanner is something that there MUST be only one instance of, then consider making it a singleton instead of creating it using the constructor. The following link describes singletons:

http://www.javaworld.com/article/2073352/core-java/simply-singleton.html

Then, rather than having it as a static global, the Scanner class can have a public static method called 'getInstance'. Therefore, you aren't tieing the instance of a scanner to any particular location and whenever you need to use it, call Scanner.getInstance from anywhere to access the underlying instance of the class.




回答4:


Overall it's ok since it's a very commonly used object in your application. However there are 2 problems you can face as far as I can see:

  • Concurrent access and mutable state of Scanner can be a problem. You might want to synchronize that.
  • Unit testing might be a problem since you can't override static members. It might still be ok if in classes that use it it can be overridden.

So it depends on the size of your app and how it's used in terms of multithreading. I would do it at home but not at work.



来源:https://stackoverflow.com/questions/21198652/is-this-bad-programming-scanner-as-global-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!