开发者

Reducing complexity of a method

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.


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.


  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.


  1. Instead of making variables class fields, just parameterize the function and pass the values around. This has another big advantage that your code will now become more unit-testable. I always promote to have each method to be as independent as possible as it helps in UT.
  2. If you had the name changed to checkAndCreateReport then, will you still think that way:)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜