Is it worth using
java.io.Console at all?
class in Java 6 has the following constraints:
- It is
final, so you can't provide your own implementation directly
- There is no service provider interface (SPI), so it is difficult to provide your own implementation indirectly
People managed to get data to and from the console before Java 6
came along. So, should your application just use
Console implementation offers a couple of
advantages over the standard I/O streams:
- Methods for reading passwords without echoing the data to the terminal
- Better character encoding integration (on Windows, it will
emit data using the set console encoding in
System.outuses the default ANSI encoding)
An alternative might be a third party framework designed for interacting with terminals. This post sticks to the standard library.
The best way to handle
null is to not let your application interact with the
type directly. Instead, your code should rely on an abstraction layer of
your own devising. Here's an example:
By using such a type, it is possible to return a working implementation supported by your environment:
Testing and the console
Defining your own abstraction layer doesn't just mean you can run your code from Eclipse/NetBeans/whatever. It lets you mock/fake/stub code for automated testing. Consider this simple number-guessing game:
Because the code doesn't rely on the console directly, we can write automated tests to make sure it works:
All the sources are available in a public Subversion repository.