Reading Java 8 Code
This piece of Java code is hard to understand. How is this DirExplorer created? DirExplorer class link https://github.com/ftomassetti/analyze-java-code-examples/blob/master/src/main/java/me/tomassetti/support/DirExplorer.java Cheers, Code below:
new DirExplorer((level, path, file) -> path.endsWith(".java"), (level, path, file) -> {
System.out.println(path);
System.out.println(Strings.repeat("=", path.length()));
try {
new VoidVisitorAdapter<Object>() {
@Override
public void visit(ClassOrInterfaceDeclaration n, Object arg) {
super.visit(n, arg);
System.out.println(" * " + n.getName());
}
}.visit(JavaParser.parse(file), null);
System.out.println(); // empty line
} catch (ParseException | IOException e) {
new RuntimeException(e);
}
}).explore(projectDir);
source to share
Let's refactor the old-style code for easier understanding:
Filter filter = new Filter() {
@Override
public boolean interested(int level, String path, File file) {
return path.endsWith(".java");
}
};
FileHandler fileHandler = new FileHandler() {
@Override
public void handle(int level, String path, File file) {
// Your long implementation for FileHandler
}
};
new DirExplorer(filter, fileHandler).explore(projectDir);
A variable filter
is an instance of an anonymous class implementation interface filter
, the interface filter
has only one method, so in Java 8 it is a functional interface , and the initialization code above can be abbreviated as lambda expression in Java 8 to:
Filter filter = (level, path, file) -> path.endsWith(".java");
FileHandler fileHandler = (level, path, file) -> {
// Your implementation for FileHandler
};
new DirExplorer(filter, fileHandler).explore(projectDir);
And besides that, you can inline both variables, which results in the code looking like this:
new DirExplorer((level, path, file) -> path.endsWith(".java"), (level1, path1, file1) -> {
// Your implementation for FileHandler
}).explore(projectDir);
source to share
When it's hard to read, I break it down into smaller, more readable chunks. Is it easier to understand?
Filter filter = (level, path, file) -> path.endsWith(".java");
FileHandler fileHandler = (level, path, file) -> {
System.out.println(path);
System.out.println(Strings.repeat("=", path.length()));
try {
new VoidVisitorAdapter<Object>() {
@Override
public void visit(ClassOrInterfaceDeclaration n, Object arg) {
super.visit(n, arg);
System.out.println(" * " + n.getName());
}
}.visit(JavaParser.parse(file), null);
System.out.println(); // empty line
} catch (ParseException | IOException e) {
new RuntimeException(e);
}
};
new DirExplorer(filter, fileHandler).explore(projectDir);
source to share