This piece of Java code is hard to understand. How does this DirExplorer get created? Class DirExplorer link is https://github.com/ftomassetti/analyze-java-code-examples/blob/master/src/main/java/me/tomassetti/support/DirExplorer.java Cheers, Code is 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);
Let's refactor the code to the old-style 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);
The variable filter is an instance of an anonymous class implementing interface Filter, the interface Filter has only one method so in Java 8 it's a functional interface, and the initialisation code above can be shortened by 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 further more, you could inline both variables, which leads the code to be:
new DirExplorer((level, path, file) -> path.endsWith(".java"), (level1, path1, file1) -> {
// Your implementation for FileHandler
}).explore(projectDir);
When it's hard to read I break it into smaller, more readable pieces. Is this 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With