Is this bad programming? scanner as a global variable

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

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

Im working with a lot of input from various methods and just seems a lot easier than sending a keyboard to each method

+6
source share
4 answers

It seems much easier to use a global variable, but in the end it can make the code very difficult to maintain, have you thought about creating a class to handle keyboard input? Having a good separation of problems, you get cleaner code.

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

+5
source

Best of all, if you created a special class for getting Inputs and / or creating 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 } 
+4
source

Depending on how the object should be used, determine where to place it.

If a scanner is something that SHOULD be just one instance, then consider making it single and not creating it with a constructor. The following link describes singletones:

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

Then, instead of having it as a static global one, the Scanner class can have an open static method called "getInstance". Therefore, you do not bind the scanner instance to any specific location, and whenever you need to use it, call Scanner.getInstance from anywhere to access the base instance of the class.

+1
source

In general, this is normal, as it is a very frequently used object in your application. However, there are two problems that you may encounter, as far as I see:

  • Concurrent access and changing scanner status can be a problem. You can sync this.
  • Testing modules can be a problem since you cannot override static members. This may still be fine if in classes that use it, it can be overridden.

So it depends on the size of your application and how it is used in terms of multithreading. I would do it at home, but not at work.

+1
source

All Articles