Alibaba Java Development Manual Learning Record

Alibaba Java Development Manual Learning Record

1. Programming conventions

1. Naming style

  • It is strictly prohibited to use a mixture of English + Pinyin

  • Class names should capitalize the first letter of all words except (UserDO, XxxDTO, XxxPo, etc.)

  • Constants should be named in uppercase letters + underscores between words.

  • Abstract classes should start with Abstract/Base

  • POJO类中的布尔变量,都不要以is前缀,否则某些框架解析会引起序列化错误, 。(I read an article before because the XxxDTO method was named isXxxXxx(), which caused the method to be incorrectly serialized, causing an online accident. Article: https://mp.weixin.qq.com/s/994BAkKPEeBz_gs_6LN2DQ)

  • If modules, interfaces, classes, and methods use design patterns, they should be reflected in the naming.

  • Domain model naming convention

    • Data object: xxxDO, xxx is the name of the data table
  • Data transfer object: xxxDTO, xxx is related to the business field

  • Display object, xxxVO, xxx is the name of the web page

  • POJO is the collective name for DO/DTO/BO/VO. The use of xxxPOJO is prohibited.

  • If the variable value only changes within a fixed range, declare it with enum

2. Code format

  • The single-line character limit does not exceed 120 characters. If exceeded, a new line is required:
    • The second line is indented 4 spaces relative to the first line
    • The operator is wrapped with the following (for example: ".")
    • Multiple parameters in method call,在逗号后换行
  • You can insert a blank line to separate different logic, semantics, and business discussions to improve readability.

3.OOP protocol

  • All methods that override the parent class need to add @Override to determine whether the rewriting is successful.
  • If the interface is obsolete, @Deprecated must be added, and the location of the new interface must be explained.
  • Do not use obsolete classes and methods
  • 在使用equals时,应使用常量或者确定有值的对象的equals的方法
  • All POJO class attributes must use wrapper types, and the return values ​​and parameters of RPC methods must use wrapper types.
  • If it is completely incompatible with the upgrade, to avoid deserialization confusion, modify the serialVersionUID.
  • No business logic is added to the constructor
  • It is forbidden to have the isXxx() and getXxx() methods of an attribute in a POJO class at the same time.
    • Because during serialization, it is not sure which method to call first. For enumeration variables starting with is, the is of the attribute will be eaten when isXxx is called during serialization, causing serialization errors. (Case: https://zhuanlan.zhihu.com/p/265869701)
    • Solution: 1. Follow development specifications and do not use variables starting with is. 2. Use JSONField (name = "anotherName") to customize the attribute name. 3. Getters and setters can be modified manually.
  • The order of method definition within a class: public method>private>getter/setter method
  • The clone method of an object defaults to a shallow copy. If you want to implement a deep copy, you need to override the clone method.
  • Tool classes are not allowed to have public and default constructors

4. Collection processing

  • As long as equals is rewritten, hashcode must be rewritten
  • When using set to store custom objects, the custom object needs to override the equals and hashcode methods.
  • 在使用sublist方法时,对原集合的增加或删除,均会导致子列表遍历、增加、删除产生并发修改异常。
  • 在进行list的toArray(size)方法转数组时,应该传入list.size()作为参数这样返回的就是当前类型的数组, if the parameterless toArray method is used directly, the return value is an array of type Object.
  • When Arrays.asList() converts an array into a collection, you cannot use add and other modification methods, otherwise an exception will be thrown.
  • PECS( Producer Extends Consumer Super) principle: If you frequently read content from outside, <? extends T> is suitable. For frequent insertions, <? super T> is suitable.
  • There is no need to perform element remove/add operations in foreach. Remove can use the iterator method. If concurrent operations require locking the Iterator object. (Although it is said here foreach本质也是迭代器实现,但是反编译以后会发现最后删除时是通过list直接remove, but 迭代器删除的是通过迭代器的remove方法删除的)

5. Concurrent processing

  • Obtain单例对象时,需要保证线程安全
  • should useThreadPoolExecutor创建线程池
  • SimpleDateFormat is not thread-safe. If it is defined as static, it must be locked. DateUtils can also be used.
  • If it is a JDK8 application, you can use Instant instead of Date, LocalDateTime instead of Calendar, and DateTimeFormatter instead of SimpleDateFormat.
  • When locking multiple resources (tables, objects) at the same time, the consistency of the locking sequence should be maintained to avoid deadlock.
  • When modifying the same record concurrently, to avoid losing updates, you can lock at the application layer, cache, or use optimistic locking at the database layer. (If accessed every time 冲突概率小于20%,推荐使用乐观锁, otherwise use pessimistic locking. 乐观锁的重试次数不得小于3 次.)
  • To avoid multiple threads using a Random (Random or Math.random), which will cause performance degradation, you can use ThreadLocalRandom
  • When counting in multi-thread scenarios, volatile cannot cope with multi-write scenarios. Generally, we will choose AtomicInteger, but it 竞争比较激烈的场景下can be used LongAdder性能更好(space for time, internally 数组分段计数最后求和, but only in counting scenarios).
  • ThreadLocal recommends using static modification. It only needs to be created once, and all objects in a thread have already operated this variable.

6.Control statements

  • In high-concurrency scenarios, avoid using equal as a condition for interruption or exit., if the concurrency conditions are not handled well, equal value "breakdown" will occur, so you should use greater than or less than
  • Avoid using complex methods in if conditional judgments (except getXxx/isXxx)
  • Performance must be considered inside the loop, so some unnecessary operations should be performed outside the loop.

7. Annotation convention

  • The main function of comments: to accurately reflect design ideas and code logic, and to describe business meanings.
  • When the code logic is modified, the comments should also be modified accordingly, especially parameters, return values, exceptions, and core logic.
  • All enumeration type fields must be annotated

8.Exception handling

  • When catching an exception, for unstable code, try to distinguish the exception type and then handle the corresponding exception. Do not try-catch a large section of code.
  • Once an exception is caught, it should be handled
  • NPE should be strictly avoided

9. Log protocol

  • Applications cannot directly use the APIs in the log system (Log4j, Logback), but should rely on the APIs in the log framework SLF5J.
  • Extended log naming in the application: appName_logType_logName.log
  • For trace/debug/info level log output, conditional output or placeholders should be used (slf4j supports placeholders).
  • The production environment prohibits the output of debug level logs, and selectively outputs info logs. When writing log output statements, think: Is anyone watching? What can I do after seeing this log? Can it help troubleshoot problems?
  • You can use the warn log level to log user output parameter errors.

10. Unit testing

  • Unit testing should follow AIR principles (automation, independence, repeatability)
  • The granularity of unit testing should be small enough to help locate problems, usually at the method level.
  • The incremental code of core business and logic should be covered by unit tests
  • For untestable code, it is recommended to refactor to make the code testable.

11.Safety regulations

  • User-related functions must undergo permission verification
  • Users’ sensitive information needs to be desensitized
  • Any parameters passed in by the user request must be verified for validity.
    • Excessive page size causes memory overflow
    • Malicious order by causes slow database query
    • arbitrary redirect
    • SQL injection
    • Deserialization injection
    • Regular input source string denial of service ReDoS (when we use regular input to verify client input, it may be attacked by special strings)
  • When using platform resources, such as text messages, emails, phone calls, orders, and payments, correct anti-resend mechanisms must be implemented, such as quantity limits, fatigue control, and verification code verification, to avoid abuse and waste of resources.

11.Index specification

  • Fields with unique characteristics in business, even if they are a combination of multiple fields, must be built into a unique index
  • When creating an index on a varchar field, you must specify the index length. There is no need to index the entire field (you can use the distinction of count(distinct left(column name, index length))/count(*) to determine)
  • It is strictly forbidden to use left or full blur in page search. If necessary, please use a search engine to solve the problem.
  • MySQL does paging query. MySQL does not skip the offset row, but takes the offset+N row, then returns the offset row before giving up, and returns N rows.
  • Do not use count (column name) or count (constant) instead of count(*). count(*) is the standard syntax for counting rows defined by SQL92. It has nothing to do with the database. count(*) will count rows with NULL values. And count (column name) will not count rows with NULL values ​​in this column.
  • count(distinct col) calculates the number of unique rows in this column except NULL, and will not count NULL rows
  • When the values ​​of a certain column are all NULL, count(col) is 0, but sum(col) is NULL, so you need to pay attention to the NPE problem when using sum()
  • Foreign keys and cascades are not allowed, and logic related to foreign keys must be solved at the application layer.
  • Stored procedures are prohibited

Continually updated…

Guess you like

Origin blog.csdn.net/qq_50876039/article/details/132267076