Hardcoding
The path to the file with words is a hardcoded. That's not so good. It would be better to use a command line argument and the String[] args
parameter of the main
method.
If you must hardcode something, make it a constant, for example:
private static final String PATH = "src/app/wordlist.txt";
fileName
was not a good name for a path anyway. A "file name" usually refers to the last path segment without parent directories.
Single responsibility principle
The class violates the single responsibility principle: it picks a random word, and it reads a file. I would do something like this instead:
class RandomStringPicker {
private final List<String> list;
public RandomStringPicker(List<String> list) {
this.list = list;
}
public String pick() {
return list.get(pickRandomNumber(list.size()));
}
private int pickRandomNumber(int max) {
return (int) (Math.random() * max);
}
}
This class only does one thing. You could read the file somewhere else and create a RandomStringPicker
class from the lines you read. But now you can reuse this class for other purposes too, for example in unit tests.
This implementation also improves the weakness of your init
method. If you forget to call init
, your program will compile, but not work. In the example above there is no such uncertainty: if the class is not constructed with a list, it will not compile.
Printing, validating and logging
It's not good practice to print things on the console. If you want to verify your code works, write unit tests. If you want to log messages during runtime, use a logger.