Reducing the complexity of the method

I have a method that performs several tasks. It is part of the business logic of the application, but it is poorly read due to 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 tasks to special methods and have an archiveAll method that you can understand at a glance:

 public void archiveAll() { doCreateReport(); doSendReport(); doWarnIfErrors(); } 

But this raises two problems:

  • if all methods use a local variable, I will move it as a class field, but this is not a good design
  • I want to move the if (createReport) test to the doCreateReport method too, because part of the complexity stems from the tests that are executed. This makes helper methods poorly cohesive, though.
+4
source share
3 answers
  • Instead of creating the fields of a variable class, simply parameterize the function and pass the values ​​around. This has another big advantage in making your code more testable now. I always suggest that each method be as independent as possible, as it helps in UT.
  • If you had the name changed to checkAndCreateReport, then you will still think so :)
+1
source

If you have many local variables that are shared between them, it might make sense to make a private class to store them together, maybe even do something like:

 MyReport report = new MyReport(); // or MyReport.doCreateReport(); if it makes more sense report.send(); report.warnIfErrors(); 

Again, this really depends on whether the function is really large enough to guarantee something like this.

If you can just pass these common variables as parameters without huge parameter lists, do it.

+7
source
  • You can also pass the necessary data as arguments to the methods.
  • I would do a check before calling the method. If the method is called doCreateReport, it should actually do .
+2
source

All Articles