Why Java.NIO uses static methods?

Viewed 167

I wonder why java.nio is based in static methods, I mean in java.io you create a file and then use his methods, is something like:

File file = new File("myFile");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String readLine = bufferedReader.readLine();

Where each object has its own methods.

java.nio works in a different way, you use static methods and it forces you to always pass the file to work as a parameter.

Path file = Paths.get("myFile");
BufferedReader bufferedReader = Files.newBufferedReader(file);
String readLine = bufferedReader.readLine();

Path source = Paths.get("source");
Path target = Paths.get("target");
Files.copy(source, target);

There is less code to write since nio provides useful methods (like newBufferedReader) directly in the class. but it could have been done in instance methods as well so you wouldn't have to pass a path as parameter.

Why this change of paradigm? Whata are the hidden advantages?

1 Answers

In the examples you show, the pattern is to hide away the constructor call behind a factory method.

That is a very well established method to allow the implementation to be flexible in what kind of implementation it will actually return. This allows both complex logic to be encapsulated there as well as future evolution. Even though it does not apply for the examples you quoted, it is also possible to not create new instances at all, but return pooled or cached copies (like Integer.valueOf does as opposed to new Integer).

If you directly call a constructor, there is no way to achieve this flexibility.

There is less code to write since nio provides useful methods (like newBufferedReader) directly in the class. but it could have been done in instance methods as well so you wouldn't have to pass a path as parameter.

Something like path.newBufferedReader() is probably too much tight coupling between these classes. They want Path to be a class to represent a file system path. It does not need to know everything people may want to do with files. Focussed and independent classes help with modularity.

For an older API, where they went the other way, look at String#replaceAll. Here, the whole logic of understanding regular expressions has been integrated in the String class.

Related