The author | Zhu Tianfu (sea culture)

Edit | orange

New retail product | alibaba tao technology

A lot of words come to mind when it comes to code quality: naming conventions, formatting conventions, logging conventions, unit test coverage…

But I think code quality boils down to two things: good looking and easy to use.

Good-looking code is readable, easy to understand, easy to maintain, others take over do not scold you; Easy to use means that the code is robust, error-free, and the machine runs without scolding you. Even when mistakes are made, they are easy to locate, stop and recover.

Why do you need to improve code quality?

Here’s what I think:

  • Improve the maintainability of the code and reduce the cost of new recruits

  • Promote communication, promote knowledge sharing, and do backup well

  • Promote consistency of style and ease application flow between teams

  • Build a good code and design team atmosphere

However, I think that writing code is a creative process that people can enjoy. If there are too many rules and regulations, it takes away the fun of writing code. So here are some rules for code quality:

  • Advice is provided, not mandatory

  • Encourage creative coding

  • Encourage artistic coding

How do YOU have high-quality code

There are two approaches:

  • The first way is to have good design and then implement it with good coding and then continue the good coding style

  • The second way is to start with bad code -> refactor towards good design and code style -> and continue

How do you start building code quality?

** You have to know what good code is, and ** you have to have standards, and that’s all the different specifications that we see all the time, but I think there are a few simple rules, too many to remember, a few simple rules that you can use from time to time to see if you’re doing it right.

Then there is the practice of the specification, which requires some techniques, some tools, to help us follow the specification better.

** Then comes the measurement, ** to see the effect of our Code practice. This is what we often say and do, but Code Review also needs to follow certain norms and apply certain skills.

Measurement is followed by improvement, and the most important part is to follow up on CR results, otherwise CR is meaningless.

Review is a useful tool. CR also needs to review, summarize the good and bad aspects of CR processes and processes, and update specifications and checklists.

Let’s talk about each step.

Specification: What is good code first

We can see from the birth of high quality code above, design is also a very important part, so our specification includes design specification and coding specification, combined with our production reality, here plus the safety production specification, so the specification has three parts: design, coding, safe production.

Design: Start with a good plan

It is recommended to use pictures to express, because pictures have more intuitive communication ability than words:

** First is the business flow chart, ** it can quickly build our understanding of the business, with the understanding of the business to look at the code, twice the result with half the effort.

** Then comes the use case diagram, which clearly expresses the responsibilities, boundaries and service objects of our system. Combined with the business flow chart, we can quickly build up our cognition of the system responsibilities.

** Next comes the architecture diagram, which is required from our daily design requirements. A good architecture diagram provides a quick framework for understanding, and when you look at the details of the system, it’s easy to understand. The architecture diagram recommends the C4 specification, which is by far the most articulate architecture diagram specification I have worked with.

Then use sequence diagram, state diagram, ER diagram and so on to express the design of key and complex parts.

However, our daily needs are large and small, and the scheme does not need to follow a unified model. To design for the sake of design, it only increases the workload. On demand as the first principle, can do what to do, how to do it clearly. Here, the usage scenario of each graph is recommended according to the scenario:

New application/major modification of existing application/complex project

  • Business flow chart (explain business background)

  • The system context, container and component of C4

  • Use case diagram: There are multiple external actors

  • Class diagram: More than 5 key models

  • State diagram: More than three object states

  • Sequence diagram: More than 3 objects are involved in critical processes or complex links

  • ER diagram: Involving database changes (including data table structure documents)

General project/major daily

  • Business flow chart

  • Sequence diagram (complex function, critical flow)

daily

  • On demand

Coding: Good solutions require good coding

The most important thing about coding is to be readable, to control complexity, to be self-explanatory, to be able to read your code as if it were a natural language, which is the highest level, and the realm of the gods. Then there’s maintainability and changeability, where quickly and safely modifying code is the goal. Finally, there’s the need for elegant implementation. It’s not uncommon for great code to be slapped in the lap, and we have the occasional flash in our messy code.

Coding principles:

readability

  • Control complexity

  • self-document

maintainability

elegant

Constrast specification

Reasonable code layering can control the complexity of each layer and improve the reusability of the code. As for layerization, I believe that what is familiar is good, and it is good if it can meet most situations in work. Here, I do not talk about concepts such as hexagonal architecture, clear architecture and DODAF, which cannot be mastered by myself. I recommend the basic 4-tier DDD architecture as follows:

User interface/interface layer ⇩ application layer ⇩ Domain layer ⇩ Infrastructure layerCopy the code

Here’s an example I used in my actual project:

-- bootstrap -- BeanConfig -- application -- pv -- ChannelPvApplicationService -- sns -- domain -- abtest -- AbtestService -- address -- coupon -- entity -- Coupon -- CouponStatus -- CategoryCouponTemplate -- category -- user -- UserRepository -- service -- OneIdService -- UserService -- item -- ItemRepostory -- live -- LiveStatus -- infrastructure -- concurrent -- ThreadPoolExecutorFactory -- MonitorableCallerRunsPolicy -- dal -- IGraphDal -- TuringDal -- DefaultUserRepository -- dao -- MybatisItemDao -- util -- DateUtil -- MoneyUtil -- UriUtil -- monitor -- Event -- Timing -- TimingAspect -- TimingEvent -- Monitors -- view -- atomicwidget -- BannerWidget -- CrazySubsidyWidget  -- FeedItemsWidget -- NavigateBarWidget -- LiveWidget -- page -- HomeScreenPage -- CategoryFeedsPage -- SearchCardPage -- widget -- Widget -- DispatchableWidget -- Debuggable -- AbstractWidget -- AbstractDispatchableWidget -- WidgetDispatcher -- WidgetResult -- WidgetContextIncompatibleExceptionCopy the code

In the above project structure, because it is a shopping guide project, VIEW is equivalent to the user interface layer, application is the application layer, Domain is the domain layer, and infrastructure is the infrastructure layer.

The division of the package is explained again:

  • The definition of domain object, value object, DTO, Service and so on should be put under the package of subdomain, and there should be no large and complete entity, Service, impL and so on. (The subdomain here is a cohesive logical concept, corresponding to the subdomain of domain design, the item in the above example is the commodity subdomain in our guide)

  • Constant definitions should follow the relative class as much as possible. As a static field of the class, do not have a large and complete Constant class (except for those related to Switch, but also split Switch classes by duty).

✎ ✎ Constract Code Specification

Code specifications on the recommendation of Ali economy development regulations, very comprehensive, is also the basic requirements of Ali students. Code specifications on the recommendation of “Ali economy development statute”, very comprehensive, is also the basic requirements of Ali students, open source version: Alibaba Java development manual

Based on my own experience, I will focus on the following points:

named

  • Naming without generic names (counterexample: processData)

  • Use as many words as possible to describe the purpose and function

  • Object suffix Domain objects without suffix DTO: objects provided by the RPC interface. VO: Objects used for front-end interaction. PO: objects used for direct interaction with the database

The log

  • There should be operation logs and data change logs in all backgrounds

  • Asynchronous write disks must be configured for logs

  • Only WARN and ERROR logs are reserved online

  • All logs must have traceId

  • The exception log should have a stack, input, and information that tells you what the error was (can be out of the unified component)

  • Do not use the JSON tool to convert an object to a String when printing logs

abnormal

  • How to throw: Try to use unchecked exceptions to improve code readability

  • How to handle: Uniform exceptions handled with sections, or rely on SpringMvc’s ControllerAdvice for uniform handling

  • Keep exception catch scope as small as possible, distinguish stable code from unstable code

  • Do not swallow exceptions directly

  • Always be aware of NPE and use Optional treatment

annotation

  • Comments are just to explain why you’re doing something, not what you’re doing

object-oriented

  • Principles: SRP/OCP/LSP/ISP/DIP

  • Try to expose only behavior, not data

  • Avoid inheritance in favor of composition

Other specification

  • Keep method lines within one screen (less than 30 lines)

  • Control the amount of code per commit (one function per commit)

  • Try to use immutable objects for parameters (do not change input parameters, keep explicit input and output parameters) and try not to use implicit input parameters (ThreadLocal)

  • LinkedList replaces ArrayList when data structures are not read randomly

  • Style Layering, same style for each layer (design/code)

Production safety

Safety in production has not been systematically summarized, combined with their own work experience in stability to make some points, and then learn more from the students responsible for safety in production, and then update:

Prevent information loss

  • Have capital loss assessment/monitoring

Easy to recover

  • Any new function on-line must have gray capacity

Monitoring/alarm

  • Pocket bottom design/monitoring

  • Performance monitoring

  • Abnormal monitoring

  • Low tolerance errors call the police

  • Key metrics to monitor (business/technical)

  • Reduce unnecessary alarms

Degrade/limit traffic

  • Identify weak dependencies and ensure that they can be degraded

  • Identify dependent parties that can limit traffic and perform monitoring and traffic limiting configurations

Practice: How to practice norms

Give some principle and skill suggestion, help ground standard.

design

You don’t have to have a picture, you just have to explain how you do it, why you do it

coding

  • Using aone-idea, it has integrated PMD/FindBugs/CheckStyle functionality. Open source version: Alibaba, Java Coding Guidelines Alibaba plugins.jetbrains.com/plugin/1004…

  • With Lombok, keep your code simple

  • Keep refactoring and follow these principles: DRY/YAGNI/Rule Of Three/KISS/POLA Every requirement is a refactoring opportunity to ask yourself if you can do better in [readability/maintainability]

  • Make code read like natural language

  • Separation of functional and non-functional code

Production safety

This should follow the company and department rules, learn and supplement.

Measurement: How to verify practice effect -CodeReview

Review the timing

  • The first time after the project is put into test: do not review the project the night before it goes online. If there is no time to change it, the review results will be easily shelved and the youth of participants will be wasted

Review way

  • Small module: anytime /Aone code review /@backup classmates

  • Project code: Face-to-face screen casting /Aone code review + IDE show/ project team + focus on students

Review the content

  • How does the design of the code address the requirements

  • The overall process

  • The key design

  • The key function

Review the premise

  • The code is compiled

  • Enable real-time detection of aone-idea

Checklist

  • normative

    readability

    Maintainability (high cohesion and low coupling, object-oriented principles, implementation complexity, etc.)

    Changeability (extensibility, etc.)

  • Security/robustness input checking Exception handling boundary checking

  • Performance dependent rationality

Improvements: Tracking execution of CodeReview results

  • Issues with runtime risk must be changed before going live

  • For other problems, try to complete the modification before going online. If no modification is made, todo should be added and the modification time should be specified

  • Use tools to measure and suggest improvements in CR results

Conclusion optimization

  • Regular review and summary (weekly session)

  • Update checklists and code specifications

  • Find good code and design, show it regularly, and reward it

The latter

The above is picked from the words of each, plus some of their own thinking. Learning is a gradual process, I am still learning code quality, if I gain, I will update. If DISs, I still feel justified, I will update in.

These are my own learning and practice directions, so if you find that my code doesn’t do this, tease me and give me suggestions to make it better.

Tao Department technology department – global marketing team

Recruitment for back-end technology, data technology, P6-P8. We are one of the most important marketing sites of Ali. We go deep into the core e-commerce business, accept the biggest challenges and get the growth you expect. For more information, click “Read the original article” below.

Please send your resume to 📮 : [email protected]

References:

There are plenty of books out there telling us how to write good code, but here are some that I’ve read and learned:

  • The Art of Writing Readable Code

  • “Refactoring”

  • Refactoring and Patterns

  • The Way to Better Code

Google Engineering Practices Documentation

C4 model for software architecture