Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reducing complexity of a method

Tags:

java

algorithm

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:

  1. if all methods use a local variable, I'll move it as a class field, but this is not good design
  2. I want to move the test 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.
like image 246
AgostinoX Avatar asked Dec 27 '22 19:12

AgostinoX


2 Answers

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.

like image 67
trutheality Avatar answered Dec 30 '22 10:12

trutheality


  1. You can also pass the required data as arguments to the methods.
  2. I would do the check before calling a method. If a method is called doCreateReport it should actually do that.
like image 30
Adam Byrtek Avatar answered Dec 30 '22 08:12

Adam Byrtek