Introduction of the author: New Minant Financial · Data Experience Technology team

preface

As I mentioned earlier, our team’s front-end project went through an 8-month iteration of 100,000 lines of business code (only 20% of the product’s long-term planning requirements) from scratch and is still iterating.

In addition to designing the architecture to manage this extremely complex front-end application, the team members began to supplement their knowledge of design patterns and refactoring in order to optimize the project code over time and keep it fresh, robust, and maintainable… So that the new team members can also quickly join our product development

PS: Refactoring is an integral part of the software development process in any language. If you already know the basics of refactoring, you can skip to the refactoring case section later in the article.

Refactoring background

“If the diaper stinks, change it.”

  • As business requirements continue to be added, the code gets worse and worse over time.
  • These may include the following bad smells (to name only):
    • Duplicate code
    • Overlong function
      • One rule to follow: Whenever you feel you need a comment to explain something, try writing it into a function
    • Lazy class
      • Consider inlining classes when subclasses are not doing enough work, or when there is no visible expectation that something new will happen.
    • Long class
      • This situation is prone to redundant code. For example, if multiple variables in a class have the same prefix or suffix, this means that you can consider refining them into a component, or consider whether the component can be subclassed and refactoring using a refining class approach.

What is refactoring

Let’s go back and look at what refactoring is.

  • Improve the internal structure of the software without changing its observable behavior

  • To improve understanding and reduce modification costs

    Excerpt from Refactoring - Improving the design of existing CodeCopy the code

When to refactor?

Let’s be clear: Refactoring is not something that should be set aside for a specific period of time. Refactoring is not the goal, but refactoring can help you get things done.

Three things, three reconstruction

  1. Repetitive work, when existing code doesn’t help you easily add new features
  2. Troubleshoot logic difficulties when fixing bugs
  3. Code review allows others to review code to see if it is readable and understandable
  4. Too much code is uncommented, and you can’t figure out the logic quickly enough

Refactoring metrics

  • Number: number of lines of code
  • Quality: code complexity, coupling, readability, architecture dependency complexity, etc
  • Cost: Time spent
  • Reward (achievement): support the fast superposition of subsequent functions, solve the existing contradictions that cannot be optimized due to code design problems, etc

Get to the point. Get to the point

Having said so much nonsense, in fact, we all know that theory without the combination of practice is empty.

But refactoring, like design patterns, is a learning-comprehension-breakthrough process. Step 1 gives you a basic understanding of refactoring techniques, step 2 reminds you of refactoring techniques and reuses them, and step 3 encourages you to think, understand and summarize refactoring practices so that you can use them flexibly.

But all people, always constantly learning, constantly review, in order to achieve a specific scene specific application, flexible. Refactoring is a big topic, and the author of Refactoring has developed his refactoring skills through many projects and years of experience.

Refactoring technique

The author of Refactoring summarized so many refactorings that I can only show the list of refactorings summarized by the author in pictures. For more details, see refactoring.

Refactoring practices

One approach the authors recommend:

  1. Pick a target at randomPick a goal for yourself (” get rid of a bunch of unnecessary subclasses, “for example) and work toward that goal in small, firm steps
  2. Stop when in doubtWhen you can’t prove that you’ve done anything to maintain the logic and semantics of the original program, stop and think about whether the existing refactoring is an improvement or a complete failure that needs to be undone.
  3. Ensure that every refactoring test runs normally

As a developer, you should refactor as part of your development, as you go along. On the basis of quickly stacking the code and realizing the basic function requirements, write good test cases to ensure the same function and gradually reconstruct. That’s why our team requires everyone to master refactoring as an essential skill. A good programmer should avoid low-quality code.

Refactoring case

stories

  1. There are three types of movies that customers can rent
  2. Lease rules
    1. New film — 3 yuan per children’s film per day — The starting price is 2¥, 0.8 yuan per film per day for film over 3 days
    2. Bonus points: 1 for each film borrowed, 2 for each new film

The original code

  • CODEPEN

Program result :(please ensure that the result remains unchanged after reconstruction ~)

  • The class diagram

  • Divide responsibilities and follow themSingle responsibility principle
    • The statement print bill function performs many functions, including charge calculation, credit calculation, and result display
      • Extract Method — The most commonly used refactoring technique
      • Decompose Conditional expression
    • The user class assumes responsibilities that do not belong to it, including charging rules and integral rules. These duties should be in the movie genre.
  • Clarify the business logic, such as charging rules and points rules – see story scenario
  • Do not directly access the object’s data. It is easy for other objects to change the object’s data without the object owning the data knowing it.
    • 8.10 Encapsulate Field — To make data and behavior separate
  • Refactoring should not be perceived by the outside world to ensure that TestCases remain viable

Part of the refactoring

Here, in order to better display the method of reconstruction, we use TS to partially reconstruct according to the above discussion. In fact, the way of reconstruction depends on the future expansion direction of the business, and there is no optimal solution. If you are interested, please join us and offer your opinion ~

  • CODEPEN result:

  • Class diagram relationship after reconstruction

Basic skills

  • Take small steps and test frequently (make sure you have enough tests to support your refactoring efforts)
  • Use smart development tools (such as VSCode right click to disassemble long function code)

Recommended books

  • The Code Clean Way
  • Refactoring – Improving the Design of Existing Code
  • The Art of Fixing Code
  • Code Book

Refactoring is a long-term investment with a high input/output ratio. Those interested in refactoring can follow the column or send your resume to ‘tao.qit####alibaba-inc.com’.replace(‘####’, ‘@’)

Original address: github.com/ProtoTeam/b…