What kind of code is good code? In October, read the manual of what Ali JAVA development

Foreword

Recently Alibaba Java development manual review of this book, thinking of what kind of code is good code to share with you my thoughts, where there is wrong, please point out, very grateful.

What kind of code is good code?

What good is the code? Just realized the functions of a qualified code, but really good code that has the following characteristics:

  • Named easy to understand, semantic clarity without people try to figure out
  • Code logic clear and transparent, structured
  • Public code format whole beautiful
  • High efficiency performance
  • Safety

Good name

Good name, easy to understand naming, semantic clarity. The first step in brewing is good code. Here are a few manual Ali JAVA development, emphasizing good name is easier to read.

Abstract class name or the beginning of the use Abstract Base; exception class named using ends Exception; test class named after the name of its class to be tested beginning to the end of the Test.

Reason: Everybody convention write, the reader a look at this class knows that it is an abstract class or abnormal class, not Miya.

Recommendation: Five Star

Eliminate completely non-standard abbreviations, meaning I do not know to avoid looking text.

Reason: AbstractClass "abbreviated" named as AbsClass; condition "abbreviated" named as condi, such a casual abbreviation severely reduces code readability

Recommendation: Five Star

In order to achieve the target code is self-explanatory, any custom programming elements in the name, try to use the full word combinations to express its meaning

Positive Example: in the JDK, expressed atoms updated class named: AtomicReferenceFieldUpdater.

Anti Example: int a random variable naming

Reason: the complete word, expression meaning more clearly.

Recommendation: four-star

If the modules, interfaces, classes, methods of using the design pattern, the need to reflect the specific naming pattern.

Positive examples:

   public class OrderFactory;     
   public class LoginProxy;      
   public class ResourceObserver;
复制代码

Rationale: The design pattern is reflected in the name, help the reader quickly understand the architectural design concept.

Recommendation: four-star

Do not allow any mana (ie without predefined constants) directly in the code.

Counterexample:

String key = "Id#taobao_" + tradeId;      
cache.put(key, value); 
复制代码

Reason: mana only the developers themselves know, or once in a while he does not know. . . Also talk about how to maintain. . .

Recommendation: Five Star

Enum class name is recommended to bring Enum suffix, enumeration member name needs to be in all uppercase, separated by an underscore between words.

Positive examples: enum name as a member of ProcessStatusEnum name: SUCCESS / UNKNOWN_REASON.

Reason: Enumeration is actually a special class, domain members are constants, and is forced to default constructor is private.

Recommendation: Samsung

Clearly structured, clear hierarchy, clear logic

Good code, but also in a clear structure, clear hierarchy, clear logic. Not only in the functional layer of code next, code blocks, functions, duties, consistent with the design pattern design, but also in the project structure chiseled. It lists the following points:

Do not use a constant maintenance of all class constants, according to Constant function to classify, separate maintenance.

Example n: constants in the class buffer related CacheConsts, correlation constants in the system configuration based ConfigConsts.

Reason: large and constant class, disorganized, use the Find function to locate to modify constants, is not conducive to understand and maintain.

Recommendation: four-star

Too long a period of a function or a comment to make people understand the need to use the code, you can consider it to be cut into a function unit features a clear, brief and clearly defined function name, this will make the code more elegant.

Counterexample:

  private String name;
    private Vector<Order> orders = new Vector<Order>();

    public void printOwing() {
        //print banner
        System.out.println("****************");
        System.out.println("*****customer Owes *****");
        System.out.println("****************");

        //calculate totalAmount
        Enumeration env = orders.elements();
        double totalAmount = 0.0;
        while (env.hasMoreElements()) {
            Order order = (Order) env.nextElement();
            totalAmount += order.getAmout();
        }

        //print details
        System.out.println("name:" + name);
        System.out.println("amount:" + totalAmount);
    }

复制代码

Positive examples:

private String name;
    private Vector<Order> orders = new Vector<Order>();

    public void printOwing() {
        
        //print banner
        printBanner();
        //calculate totalAmount
        double totalAmount = getTotalAmount();
        //print details
        printDetail(totalAmount);
    }

    void printBanner(){
        System.out.println("****************");
        System.out.println("*****customer Owes *****");
        System.out.println("****************");
    }

    double getTotalAmount(){
        Enumeration env = orders.elements();
        double totalAmount = 0.0;
        while (env.hasMoreElements()) {
            Order order = (Order) env.nextElement();
            totalAmount += order.getAmout();
        }
        return totalAmount;
    }

    void printDetail(double totalAmount){
        System.out.println("name:" + name);
        System.out.println("amount:" + totalAmount);
    }
复制代码

Recommendation: four-star

Use polymorphism pattern or a suitable alternative design complex and lengthy if ... else / switch

such as:

 int getArea() {
        switch (shape){
        case SHAPE.CIRCLE:
        return 3.14 * _r * _r; break;
        case SHAPE.RECTANGEL;
        return width *,heigth;
        }
    }
复制代码

After polymorphic:

class Shape {
        int getArea(){};
    }

    class Circle extends Shape {
        int getArea() {
            return 3.14 * r * r; 
        }
    }

    class Rectangel extends Shape {
        int getArea() {
            return width * heigth;
        }
    }

复制代码

Recommendation: Samsung

Project structure needs chiseled, short subcontractors were clearly defined.

Description: The following is a configuration diagram rocketMq source projects.

Recommendation: four-star

Elegant code format

Elegant code format, is to make the code has a good-looking skins, so usually pay attention to use shortcut keys to write code to optimize what format.

Use braces conventions. If it is empty, succinctly written within braces {}, you do not need wrap; if it is not empty block

  • 1) does not wrap before the opening brace.
  • 2) After the opening brace wrap.
  • 3) before the closing brace wrap.
  • 4) After the closing brace else there is no line feed code, etc.; a rear right brace must wrap termination.

Recommendation: Five Star

Space does not occur between the left parenthesis and character; likewise, there occurs a space between the right parenthesis and character; and before the opening brace need space

Counterexample:

if (空格 a == b 空格)
复制代码

Recommendation: Five Star

Different logical, inserted between the different semantics of different service codes separated by a blank line to improve readability.

Description: any case, there is no need to insert a plurality of spaced-blank lines.

Recommendation: four-star

Efficiency

There just is not enough good-looking skins, of course, but also durable and practical too, can be regarded as good spine code. Ali development manual following points will help to improve code performance. Of course, in addition to these, there are daily development, whether the process which code can be optimized, which interfaces whether to call more, that code is not useless to. In short, this depends on your own summary and accumulation.

When a set of initialization, the initial value of a specified set size.

Description: HashMap using HashMap (int initialCapacity) initialization.

Positive Example: initialCapacity = (the number of elements need to store / load factor) + 1. Note that the load factor (i.e., loader factor) 0.75 default, if the initial value is temporarily unable to determine the size, set to 16 (i.e., default value).

Counter-example: HashMap 1024 elements need to be placed, because there is no capacity to set the initial size, with elements increasing the capacity of seven were forced to expand, resize need to rebuild the hash table, seriously affect performance.

Recommendation: four-star

Thread resources must be provided by the thread pool is not allowed to explicitly create their own threads in the application.

Description: The benefits of using the thread pool is to reduce the overhead in creating and destroying threads consumed time and system resources, to solve the problem of insufficient resources. If you do not use the thread pool, it may cause the system to create a large number of similar threads lead consumed or memory problem "excessive handover".

For the interface performance, consider caching, in batches, SQl index and other such means.

Note: the above points, is optimized for the performance of the code block. For interface with SQL, where relevant, consider adding an index and other means, if it involves large amounts of data, consider batch ideas, you can also consider adding cache data to distinguish between hot and cold and so on.

safety

Safety standards for judging good code, has a veto. For this, we usually can accumulate, avoiding some of the following minefield outside and have time to look at some common frameworks, middleware, source code, such as rocketMq, sring, jdk source, etc., to learn some of the wording of which, as well as to avoid possible pit .

equals method of Object readily shorting pointer exception, should be used with a constant value or determined to call the object equals

Positive examples: "test".equals(object);

Counterexample:object.equals("test");

Description: Recommended use java.util.Objects#equals(tools JDK7 introduced)

Recommendation: Five Star.

subList result ArrayList of ArrayList can not turn into a strong, otherwise it will throw a ClassCastException that java.util.RandomAccessSubList can not be cast to java.util.ArrayList

Reason: subList returns the internal ArrayList class SubList, but not a view ArrayList of ArrayList, all operations for SubList sub-list will eventually be reflected in the original list

Recommendation: Five Star.

Users must request any parameters passed to do validation.

Description: Ignore parameter calibration may result in:

  • page size is too large memory overflow
  • Malicious order by causing the database query slow
  • Any redirection
  • SQL Injection
  • Deserialization injection
  • Regular input source string denial of service ReDoS

Description: Java code with the regular inputs to authenticate the client, and some regular written verification ordinary user input is no problem, but if the attacker to use a specially constructed to validate the string, the result may lead to an endless loop.

Recommendation: Five Star.

Caution unbounded queue thread pool thread pool newFixedThreadPool as a result of soaring memory.

Description: Memory soared problem newFixedThreadPool thread pool may result, because it uses unbounded queue. So we need to accumulate these points and look at the source code commonly used type, such as thread pools, AQS and so on.

Recommendation: Samsung.

to sum up

So have several characteristics of the following codes, the code is good

  • Good name
  • Clearly structured
  • The elegant format
  • Good performance, high efficiency
  • safe and stable

Usually we can multi-point accumulation, reading, watching the source code, we recommend a few books here

  • Alibaba Java development books. "
  • "Refactoring to improve the design of existing code."
  • "Spring Source depth analysis"
  • "HeadFirst Design Patterns"

Reference and thanks

  • "Ali Baba Java development books."
  • "Refactoring to improve the design of existing code."

Personal Public Number

  • If you are a love of learning boy, I can focus on the public number, learning together discussion.
  • What if you feel that this article is not the right place, can comment, I can also concerned about the number of public, private chat me, we will study together progress Kazakhstan.

Guess you like

Origin juejin.im/post/5da5e810518825420a28151c