is this bad programming ? scanner as global variab

2019-06-17 02:52发布

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

4条回答
倾城 Initia
2楼-- · 2019-06-17 03:09

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
}
查看更多
倾城 Initia
3楼-- · 2019-06-17 03:19

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.

查看更多
走好不送
4楼-- · 2019-06-17 03:21

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.

查看更多
虎瘦雄心在
5楼-- · 2019-06-17 03:22

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

查看更多
登录 后发表回答