So I was trying to refactor this SomeClass
that has lots of different responsibilities. The shown above method seemed like a good place to start trimming down this class, so I thought about putting it in a IO specific class (and to easily allowing mocking, when needed).
class SomeClass{
...
public void m() {
...
emptyDirectory(something);
...
}
private void emptyDirectory(File dir) {
File[] dirContent = dir.listFiles();
if (dirContent != null)
for (File f : dirContent) {
if (f.isDirectory())
emptyDirectory(f);
try {
if (!f.delete())开发者_开发百科 {
IOError problem = new IOError(symbolTable.getRefinement().getFileName(),
f.toString(), f.isDirectory());
problemManager.add(problem);
}
} catch (SecurityException e) {
IOError problem = new IOError(symbolTable.getRefinement().getFileName(),
f.toString(), f.isDirectory());
problemManager.add(problem);
}
}
}
}
}
The problem is that our system has a error logging mechanism that works just like a compiler's one (it will report the error but everything should continue its work. when you try to compile a program, it won't stop the compilation process on the first time it encounters an error).
I'd like to have my IO class agnostic about this error reporting thing, so my idea was to throw exception from the IO method and then have m()
catching it and doing the rest of the error handling. The problem is that both the IOException
and SecurityException
won't tell me what the name of the file is.
I know I could create an exception of my own, but if I start creating exceptions of my own for such simple things, I'll have to create hundreds of exceptions for the rest of my code, also!
I'd like to keep the refactor as simple as possible.
How would you deal with refactoring?
Clearly the first thing to do is design and implement error handling that will allow for non-fatal error logging.
I would suggest creating a class that has a list of encountered errors (just like the compiler). When the I/O encounters a problem it passes to the error class which pops it in the error list and returns for further processing.
In this way you won't have recover from throwing the error at any given point -- each place that can generate an error is responsible for handling it or giving to the error logger to store and process later.
With this error logger in hand, your refactoring should be a breeze.
I will check for following points.
Single responsibility
Don't return null from method; return empty object/collection
keep methods simple and small
Don't pass more than 2-3 arguments in method signatures
throw exception only to the caller; if its meaningful to it. Otherwise handle it here only.
Refactoring doesn;t mean only creating smaller methods from bigger one, we need to check such things. And still many more depending on our design structure.
精彩评论