I had very errorsome Exception handling with if-clauses. An exception occurs if not found path. An exception returns the function again. The function is recursive. Safe?
$ javac SubDirs.java $ java SubDirs Give me an path. . Dir1 Dir2 Give me an path. IT WON'T FIND ME, SO IT RETURNS ITSELF due to Exception caught Give me an path.
The code of Subdirs.java looks like this:
import java.io.*;
import java.util.*;
public class SubDirs {
private List<File> getSubdirs(File file) throws IOException {
List<File> subdirs = Arrays.asList(file.listFiles(new FileFilter() {
public boolean accept(File f) {
return f.isDirectory();
}
}));
subdirs = new ArrayList<File>(subdirs);
List<File> deepSubdirs = new ArrayList<File>();
for(File subdir : subdirs) {
deepSubdirs.addAll(getSubdirs(subdir));
}
subdirs.addAll(deepSubdirs);
return subdirs;
}
public static void search() {
try{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s;
System.out.println("Give me an path.");
while ((s = in.readLine()) != null && s.length() != 0){
SubDirs dirs = new SubDirs();
List<File> subDirs = dirs.getSubdirs(new File(s));
for ( File f : subDirs ) {
System.out.println(f.getName());
}
System.out.println("Give me an path.");
}
}catch(Exception e){
// Simple but is it safe?
search();
}
}
public static void main(String[] args) throws IOException {
search();
}
}
Debatable. I would think this leaves a mess of useless stack frames – maybe not a concern unless you try to reuse this code on a mobile device. Regardless, I wouldn’t let it pass a code review without more convincing that there’s no better way.
For better understandability and maintainability, get in the habit of coding what you mean: if you intend the code to loop to retry on error, then code a loop. Recursion feels slicker, but, since its not a common practice in exception handlers, it increases the surprise factor. if I were a future maintainer of this code, I’d wonder if the recursion is intentional or a bug – please leave me a comment to explain the recursion is intentional.
I would gladly exchange a few more lines of mundane code now for better maintainability and easier troubleshooting later.