I recently started using PMD to keep my code clean and it's been going well, but I've run into a few problems in the following function.
private final void readFile() throws Exception{
code.clear();
imports.clear();
//DD anomaly
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try{
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
String line;
//DU anomaly
boolean code_started = false;
//DU anomaly
while((line = bufferedReader.readLine()) != null){
if(code_started) code.add(line);
else{
if(lineIsImport(line))
imports.add(line);
else if(lineIsClassDeclaretion(line)){
code_started = true;
code.add(line);
}
}
}
}
catch(FileNotFoundException fn_ex){
throw new Exception("File not found!");
}
catch(IOException io_ex){
throw new Exception("Failed to read file: " + file.getName() + "!");
}
finally{
try{
if(bufferedReader != null)
bufferedReader.close();
if(fileReader != null)
fileReader.close();
}
catch(IOException io_ex){
throw new Exception("Failed to close reader");
}
}
}
The first DD anomaly:
FileReader fileReader = null;
BufferedReader bufferedReader = null;
If I don't set both to null the anomaly disappears, but I get an error in the finally block. I have no idea what the correct way of writing this should be.
Next is the DU anomaly:
boolean code_started = false;
If I don't set the variable the anomaly disappears, but again an error a few lines down.
The last is a DU anomaly:
while((line = bufferedReader.readLine()) != null)
This anomaly is probably the same as the one above, but again I have no idea how to fix it.
I would be grateful if somebody could explain or show how to write this function in a manner that won't cause PMD to show the anomaly.
If you are using Java 7 or higher you can try-with-resources. The try-with-resources statement ensures that each resource is closed at the end of the statement. Below is the example how you can use it.
Go Through: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html for more info.
File file = null;
//Automatically closes resources try-with-resources block
try( FileReader fileReader = new FileReader(file);BufferedReader bufferedReader = new BufferedReader(fileReader);){
String line;
boolean code_started = false;
while((line = bufferedReader.readLine()) != null){
//Code Goes Here
}
}catch(FileNotFoundException fn_ex){
throw new Exception("File not found!");
}
catch(IOException io_ex){
throw new Exception("Failed to read file: " + file.getName() + "!");
}