I have a method that does several tasks. It is part of the business logic of the application, but it is poorly readable because of the many if-then
and try-catch
blocks and the many log
calls.
public class MyClass {
boolean createReport, sendReport, warnIfErrors;
public void archiveAll() {
if (createReport) {
//... ...
}
if (sendReport) {
//... ...
}
if (warnIfErrors) {
//... ...
}
}
The idea is to move the tasks into ad hoc methods and have an "archiveAll" method that may be understood at a glance:
public void archiveAll() {
doCreateReport();
doSendReport();
doWarnIfErrors();
}
But as doing this, two problems arise:
if (createReport)
into the method doCreateReport
too, because part of the complexity derives from the tests that are done. This makes the sub methods poorly cohesive though.If you have a lot of local variables that are shared between them it might make sense to make a private class to store them together, perhaps even do something like:
MyReport report = new MyReport(); // or MyReport.doCreateReport(); if it makes more sense
report.send();
report.warnIfErrors();
Again, it really depends on whether the function is currently big enough to warrant something like this.
If you can get away with just passing those common variables as parameters without having huge lists of parameters, do that.
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