preface

Last month a colleague left and handed over a project to me. Because the project involves different opcodes to do different business processing, it writes all the opcode business block logic of the code into a method, and uses if/else to determine the difference between them.

When I looked at the code, the business logic was not clear. Because there are too many judgments, you have to be careful to distinguish which opcodes go into which judgments. This kind of code is confusing.

Learn to disassemble

The problem

After looking at the whole project, several typical problems were summarized:

  • This main module logic has nearly 2000 lines of code, no problem in a large category. Another method may exceed 200 lines.
  • Piece together functionality that writes all the business logic together. The code is too long and hard to understand and difficult to troubleshoot later.
  • The code is too coupled and has poor reusability.

The solution

How to avoid the problems mentioned above?

Don’t try to make a class or method cover a lot of content, but rather break it down into smaller functional blocks.

In fact, it is disassembled to ensure that the functional modules are clear and independent.

  • Classes are separated into functional modules: caching, calling various external interfaces, MQ operations and other related methods are separated into a single class and method to ensure that each module has a single function.
  • Split different business opcodes into separate methods/classes: Each opcode has a different operation, so split a separate module for it.
  • The same part of the code is split into a common template method: the opcode methods are split into the same part, which is extracted as a template method.
  • The DAO layer, which deals with databases, breaks down the table dimension: each class-related operation is a class.
  • Introduce design patterns: Different opcodes have different operations, which can be handled by introducing policy pattern + factory pattern.
  • Each method of disassembly is named by its name: see the method name to know what the method does.

Aim achieved

The ultimate goal:

  • Each module is an independent combat unit and is stable externally. That is: an unstable method depends on a stable one, which does not change with different calls from outside.
  • The function of the business logic is clear, and subsequent operations, even if the opcode is deleted, affect only one method/class, not the whole, and regression testing is not required.

After disassembly, the original 30 classes were disassembled into the present 60 classes. Although there are more classes, the functional modules become clearer, the coupling of the code is very low, even if the subsequent addition and deletion of functions, the overall business logic has a very small impact.