Java programming rules

Posted by binumathew on Mon, 17 Jan 2022 21:52:11 +0100

Java programming rules

In our work and study, the specification of writing code can not only improve the cleanliness of the code and facilitate reading, but also help us read other people's code and improve our ability. This article provides general guidance for code writing and can help you with good program design.

1.1 programming rules

(1) Class names should be capitalized. The initials of fields, methods, and objects (handles) should be lowercase. For all identifiers, all words contained in them should be close together and capitalize the first letter of the middle word. For example:

ThisIsAClassName
thisIsMethodOrFieldName

If the constant initialization character appears in the definition, all letters in the static final basic type identifier are capitalized. This will mark them as compile time constants.

Java packages are a special case: they are all lowercase letters, even if the words in the middle are the same. For domain name extension names, such as com, org, net or edu, all should be lowercase (this is also one of the differences between Java 1.1 and Java 1.2).

(2) When creating a class for general purposes, please take the "classic form" and include the definition of the following elements:

equals()
hashCode()
toString()
clone()(implement Cloneable)
implement Serializable

(3) For each class you create, consider putting in a main() that contains the code to test that class. In order to use classes in a project, we don't need to delete the test code. If any form of change is made, it is easy to return to the test. These codes can also be used as an example of how to use classes.

(4) The method should be designed as a brief and functional unit to describe and implement a discontinuous class interface part. Ideally, the method should be concise. If the length is large, it can be divided into several shorter methods in some way. This also facilitates the reuse of code within classes (sometimes methods must be very large, but they should still do the same thing).

(5) When designing a class, please put yourself in the position of the client programmer (the use method of the class should be very clear). Then, put yourself in the shoes of the person who manages the code (anticipate what types of changes are possible, and think about ways to make them easier).

(6) Make classes as short and concise as possible and solve only one specific problem. Here are some suggestions for class design:

■ a complex switch statement: consider using the "polymorphic" mechanism

■ a large number of methods involve operations with very different types: consider implementing them separately with several classes

■ many member variables have very different characteristics: consider using several classes

(7) Let everything be "private" as much as possible. If you can make a part of the library "public" (a method, class, field, etc.), you can never take it out. If forced out, it may destroy other people's existing code and force them to rewrite and design. If you only publish what you must publish, you can safely and boldly change anything else. Privacy is a particularly important factor in a multithreaded environment -- only private fields can be protected in case of asynchronous use.

(8) Beware of "huge object syndrome". For some novices who are used to sequential programming thinking and are new to the OOP field, they often like to write a sequential program first, and then embed it into one or two huge objects. According to programming principles, objects should express the concept of the application, not the application itself.

(9) If you have to do some unsightly programming, at least put that code inside a class.

(10) Whenever you find that classes are closely combined with each other, you need to consider whether to use internal classes to improve coding and maintenance.

(11) Add comments as carefully as possible, and generate your own program documents with javadoc annotation document syntax.

(12) Avoid using "magic numbers", which are difficult to match well with the code. If you need to modify it later, it will undoubtedly become a nightmare, because you don't know whether "100" means "array size" or "other completely different things". Therefore, we should create a constant, use persuasive descriptive names for it, and use constant identifiers throughout the program. This makes the program easier to understand and easier to maintain.

(13) When it comes to builders and exceptions, you usually want to re discard any exceptions caught in the builder -- if it causes the creation of that object to fail. In this way, the caller will not think that the object has been created correctly and continue blindly.

(14) When the client programmer runs out of objects, if your class requires any cleanup, consider putting the cleanup code in a well-defined method with a name like cleanup() to clearly indicate its purpose. In addition, you can place a boolean flag in the class to indicate whether the object has been cleared. In the finalize() method of the class, make sure that the object has been cleared and that a class inherited from RuntimeException (if not already) has been discarded, indicating a programming error. Before adopting a solution like this, make sure that finalize() works in your own system (you may need to call system. Runfinalizesonexit (true) to ensure this behavior).

(15) * * in a specific scope, if an object must be cleared (not handled by the garbage collection mechanism), please use the following methods: initialize the object; If successful, immediately enter a try block containing finally clauses and start the cleanup.

(16) If you need to override (cancel) finalize() during initialization, remember to call super Finalize() (not necessary if the Object belongs to our direct superclass). In the process of overriding finalize(), super The call to finalize () should belong to the last action, not the first action, so as to ensure that they are still valid when the basic class components are required.

(17) When creating a collection of the fixed size objects, transfer them to an array (especially if you are going to return collection from a method). In this way, we can enjoy the benefit of type checking of arrays at compile time. In addition, in order to use them, the receiver of the array may not need to "shape" objects into the array.

(18) * * try to use interfaces instead of abstract class** If something is known to be ready to become a base class, the first choice should be to turn it into an interface. Only when you have to use method definitions or member variables, you need to turn them into an abstract class. The interface mainly describes what the customer wants to do, while a class focuses on (or allows) specific implementation details.

(19) Inside the builder, only the work required to set the object to the correct state is done. Avoid calling other methods as much as possible, because those methods may be overwritten or cancelled by others, resulting in unpredictable results in the construction process.

(20) Objects should not simply contain some data; Their behavior should also be well defined.

(21) * * use inheritance as little as possible** This aspect should be considered only when their own design requirements must be inherited. If inheritance is used where new creation is allowed, the whole design will become unnecessarily complex.

(22) * * inheritance and method override are used to represent the differences between behaviors, while fields are used to represent the differences between states** A very extreme example is to represent colors through inheritance from different classes, which should definitely be avoided: you should use a "color" field directly.

(23) each name corresponds to only one class. Otherwise, the compiler may first find another class with the same name and report an error message. If you suspect that you have encountered a classpath problem, try searching for the same name at each starting point of the classpath Class file.

(24) when using the event "adapter" in Java 1.1 AWT, it is particularly easy to encounter a trap. If an adapter method is overwritten and the spelling method is not particularly particular, the final result is to add a new method instead of overwriting the existing method. However, since this is perfectly legal, you won't get any error tips from the compiler or the runtime system -- just the code doesn't work properly.

(25) eliminate "pseudo function" with reasonable design scheme. In other words, if you only need to create one object of the class, don't restrict your use of the application in advance, and add a "generate only one" comment. Consider encapsulating it as an "only child". If you have a lot of scattered code in the main program to create your own objects, consider adopting a creative scheme to encapsulate these codes.

(26) guard against "analysis paralysis". Remember, in any case, to understand the status of the whole project in advance, and then examine the details. By grasping the overall situation, you can quickly understand some unknown factors and prevent falling into "dead logic" when investigating details.

(27) be alert to "premature optimization". Let it run first, then think about getting faster -- but you should optimize only if you have to do so and it is proven that there is a performance bottleneck in some part of the code. Unless you use special tools to analyze bottlenecks, you may be wasting your time. The implicit cost of performance improvement is that your code becomes difficult to understand and difficult to maintain.

(28) remember that you spend much more time reading code than writing code. Clear thinking design can obtain easy to understand programs, but notes, detailed explanations and some examples are often of immeasurable value. They are very important to yourself and later people. If you still have doubts about this, think about the setbacks you encounter when trying to find useful information from online Java documents, which may convince you.

(29) if you think you have made good analysis, design or implementation, please change your thinking angle slightly. Try inviting outsiders - not necessarily experts, but people from other departments of the company. Ask them to take a completely fresh look at your work and see if they can find out the problems you once ignored. In this way, we can often find out some key problems at the most suitable stage for modification, so as to avoid the loss of money and energy caused by solving the problems after the product is released.

(30) good design can bring the greatest return. In short, it usually takes a long time to find the most appropriate solution to a specific problem. But once you find the right way, your future work will be much easier and you will no longer have to struggle for hours, days or months. Our hard work will bring the greatest return (even immeasurable). Moreover, due to his great efforts, he finally obtained an excellent design scheme, and the pleasure of success is also exciting. Insist on resisting the temptation of hasty completion - it's often not worth the loss.

##Java coding specification

As the saying goes, "no rules, no radius". Programming is often carried out by a team, so it is very necessary to have a consistent coding specification. The code written in this way is easy for other personnel in the team to read and for the writers to read in the future.

2.1 naming conventions

Identifiers are everywhere in the program code, so it is very important to choose a consistent and standard name.

There are many naming methods, but the more famous and widely accepted naming methods include the following two.

  • Hungarian naming generally only names variables. The principle is: variable name = type prefix + description. For example, bFoo represents boolean type variables and pFoo represents pointer type variables. Hungarian naming is still controversial, and it is basically not adopted in the Java coding specification.
  • Camel case, also known as "camel nomenclature", refers to the mixed use of upper and lower case letters. Hump naming is divided into small hump method and large hump method. The small hump method is that the first word is all lowercase and the following word is capitalized, such as myRoomCount; Compared with the small hump method, the big hump method capitalizes the first letter of the first word. It is commonly used in class name, function name, attribute and namespace. For example, public class StudentInfomation;
    Supplementary note: in JAVA, the identifier of class name is generally written in large hump format, and the identifier of method and variable is mostly written in small hump format.

In addition to packages and constants, the naming method of Java coding specification adopts hump method, which is described below.

- Package name: package names are all lowercase letters, which can be separated by dots. As a namespace, the package name should be unique. It is recommended to use the inversion of the company or organization domain name, such as com.apple.quicktime.v2. but Java The package name of the core library does not adopt the inverted naming of the domain name, such as java.awt.event. 
- Class and interface name: adopt the large hump method, such as SplitViewController. 
- File name: large hump method is adopted, such as BlockOperation.java. 
- Variable: small hump method, such as studentNumber. 
- Constant name: all uppercase. If it is composed of multiple words, it can be separated by underscores, such as YEAR and WEEK_OF_MONTH. 
- Method name: small hump method, such as balanceAccount,isButtonPressed Wait.

Examples of naming conventions are as follows:

package com.wjh;

public class Date extends java.util.Date {

    private static final int DEFAULT_CAPACITY = 10;

    private int size;

    public static Date valueOf(String s) {

        final int YEAR_LENGTH = 4;
        final int MONTH_LENGTH = 2;

        int firstDash;
        int secondDash;
        ...
    }

    public String toString () {
        int year = super.getYear() + 1900;
        int month = super.getMonth() + 1;
        int day = super.getDate();
        ...
    }
}

2.2 notes and specifications

There are three types of annotation syntax in Java: single line annotation (/ /), multi line annotation (/... /), and document annotation (/ * *... * /). This section describes how to standardize the use of these notes.

2.2.1 document notes

File comments are comments added at the beginning of each file. File notes usually include the following information: copyright information, file name, module, author information, historical version information, file content and function, etc.

Here is an example of a file Comment:

/*
* Copyright xxx
* View license for license information Txt file
* Description:
*   Realize the basic functions of date
* Historical version:
*   2015-7-22: xxx
*   2015-8-20: xxx
*   2015-8-22: xxx
*/


The above notes only provide copyright information, file content and historical version information. The file notes should include the content according to their actual situation.

2.2.2 document notes

Document annotation means that this annotation content can generate API help documents. The javadoc command in JDK can extract these annotation information and generate HTML files. Document annotations mainly annotate classes (or interfaces), instance variables, static variables, instance methods and static methods.

The prompt document is a help document for others to see. Generally, the instance variables, static variables, instance methods and static methods of notes should be non private. The contents that are only for yourself can not be annotated.

Example of document comments:

package com.wjh;

/**
 * The user-defined date class has the basic function of date and inherits Java util. Date
 * <p>Realize the conversion between Date object and string</p>
 * @author wjh
 */
public class Date extends java.util.Date {

    private static final int DEFAULT_CAPACITY = 10;

    /**
     * capacity
     */
    public int size;

    /**
     * Converts a string to a Date object
     * @param s String to convert
     * @return Date Date object
     */
    public static Date valueOf(String s) {

        final int YEAR_LENGTH = 4;
        final int MONTH_LENGTH = 2;

        int firstDash;
        int secondDash;

      ...
    }

    /**
     * Converts a date to a string in yyyy MM DD format
     * @return yyyy-mm-dd Formatted string
     */
    public String toString () {
        int year = super.getYear() + 1900;
        int month = super.getMonth() + 1;
        int day = super.getDate();
      ...
    }
}

Since document comments eventually generate HTML documents, you can use HTML tags in document comments

Is an HTML paragraph tag.

In addition, document annotation tags such as @ author, @ return and @ param are also used in the above document annotations. These tags can easily generate API help documents. The following figure shows the common document annotation tags.
Document comment label

If you want to generate API help documents, you can use the javadoc command to enter javadoc - d apidoc data on the command line Java instruction, - d parameter indicates the directory to generate documents. Apidoc is the apidoc directory under the current directory. If javadoc does not exist, an apidoc directory will be created; Data.java is the Java source file in the current directory.

If the generation is successful, many HTML files will be generated in the current apidoc directory, including index The HTML file is the entry of the document. Double click the file and it will be visible on the page on date The content of comments in Java will appear in the HTML page.

Note that some Chinese translations in the javadoc generated document are inconsistent with this book. For example, "constructor" is the "construction method" in this book, and the "field" in the document includes "instance variable" and "static variable" in this book.

2.2.3 code Notes

Processing document comments in program code also requires adding code comments in some key places. Document comments are generally help documents for people who can't see the source code, and code comments are for people who read the source code. Code comments generally use single line comments (/ /) and multi line comments (/... /).

The example code is as follows:

public class Date extends java.util.Date {

    // The default capacity is a constant ①
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * capacity
     */
    public int size;

    /**
     * Converts a string to a Date object
     * @param s String to convert
     * @return Date Date object
     */
    public static Date valueOf(String s) {

        final int YEAR_LENGTH = 4;
        final int MONTH_LENGTH = 2;

        int firstDash;
        int secondDash;

        Date d = null;
        ...

        /*                             ②
        * Judge whether d is empty,
        * Throw the exception IllegalArgumentException if it is empty, otherwise return d.
        */
        if (d == null) {
            throw new java.lang.IllegalArgumentException();
        }

        return d;
    }

    /**
     * Converts a date to a string in yyyy MM DD format
     * @return yyyy-mm-dd Formatted string
     */
    public String toString () {
        int year = super.getYear() + 1900; //Calculation year ③
        int month = super.getMonth() + 1; /*Calculation month*/  ④
        int day = super.getDate();
        ...
    }
}

Line ① of the above code adopts a single line comment, which requires the same indentation level as the subsequent code. If there is a lot of text in the comment, you can use multiple lines of comment, see line ② of the code. Multiline comments also require the same indentation level as subsequent code. Sometimes comments are made at the end of the code, which requires that the comment content is very short, and there should be enough blank space to separate the code and comments. See lines ③ and ④ of the code.

2.2.4 use of landmark notes

IDE tools such as Eclipse provide some special comments for Java source code, that is, add some marks in the code to facilitate ide tools to quickly locate the code, which is called "landmark comments". Although this annotation is not officially provided by Java, the mainstream languages and mainstream ide tools also support "landmark Annotation".

Eclipse, IDEA and other tools support the following three landmark annotations:

  • //TODO: describe the tasks to be handled here, or the code has not been written.
  • //FIXME: the code here is wrong and needs to be corrected.
  • //30: Note although the code here realizes the function, the implementation method remains to be discussed. I hope it can be improved in the future.

The example code is as follows:

    @Override
    public Order findById(int orderid) {
        // Method stub automatically generated by TODO
        return null;
    }

    @Override
    public int modify(Order order) {
        // FIXME method has no return value
        return 0;
    }

    @Override
    public int remove(Order order) {
        // XXX can use data connection pool
        return 0;
    }

These comments are viewed in the task view of Eclipse tool. If the task view is not opened, you can click window → display view → task, and double-click the task to jump to the comment.

2.3 code layout

Code layout includes blank lines, spaces, line breaks and indents. The content of code typesetting is relatively large, the workload is large, and it is also very important.

2.3.1 blank line

Blank lines are used to separate logically related code segments to improve readability. Blank line usage specification:

  1. Leave two empty lines between the class declaration and the interface declaration. See example date Lines ⑧ and ⑨ of the Java code.
  2. Leave a blank line between the two methods. See example date Line ⑦ of Java code.
  3. Method before the first statement of the. See example date Line ⑤ of Java code.
  4. Leave a blank line before the code comment (outside the trailing comment). See example date Lines ①, ②, ③ and ④ of Java code.
  5. Between two logical segments within a method. See example date Line ⑥ of Java code.

Example date The Java code is as follows:

/*
* Copyright 2015 xxx
* View license for license information Txt file
* Description:
*   Realize the basic functions of date
* Historical version:
*   2015-7-22: xxx
*   2015-8-20: xxx
*   2015-8-22: xxx
*/
package com.wjh;
    ①
/**
 * The user-defined date class has the basic function of date and inherits Java util. Date
 * <p>Realize the conversion between Date object and string</p>
 * @author wjh
 */
public class Date extends java.util.Date {
         ②
    // The default capacity is a constant
    private static final int DEFAULT_CAPACITY = 10;
                ③
    /**
     * capacity
     */
    public int size;
            ④
    /**
     * Converts a string to a Date object
     * @param s String to convert
     * @return Date Date object
     */
    public static Date valueOf(String s) {
            ⑤
        final int YEAR_LENGTH = 4;
        final int MONTH_LENGTH = 2;

        int firstDash;
        int secondDash;
                ⑥
        Date d = null;
        ...

        /*
        * Judge whether d is empty,
        * Throw the exception IllegalArgumentException if it is empty, otherwise return d.
        */
        if (d == null) {
            throw new java.lang.IllegalArgumentException();
        }

        return d;
    }
                ⑦
    /**
     * Converts a date to a string in yyyy MM DD format
     * @return yyyy-mm-dd Formatted string
     */
    public String toString () {

        int year = super.getYear() + 1900; //Year of calculation
        int month = super.getMonth() + 1; /*Calculation month*/
        int day = super.getDate();
        ...
    }
}

                ⑧
class A {

}

                ⑨
class B {

}

2.3.2 spaces

Some places in the code need spaces, which is also a lot of work. Here are the specifications for using spaces:

1**. There is a space * * before and after the assignment symbol "=". Examples are as follows:

int YEAR_LENGTH = 4;
int day = super.getDate();
  1. All binary operators should be separated from operands by spaces. Examples are as follows:

    a += c + d;
    prints("size is " + foo + "\n");
    
  2. Unary operators: negative sign "-", self increasing "+ +" and self decreasing "–", etc. there is no space between them and operands. Examples are as follows:

    int a = -b;
    a++;
    --b;
    
  3. There should be no space after the opening parenthesis' ('and before the closing parenthesis')'. Examples are as follows:

    a = (a + b) / (c * d)
    
  4. There is a space before the opening brace '{'. Examples are as follows:

    while (a == d) {
        n += 1
    }
    
  5. There is no space before the open parenthesis "(", and there is a space after the close parenthesis ")" in the method parameter list, and there is also a space after the parameter comma "," in the parameter list. Examples are as follows:

    String format(Object obj, StringBuffer toAppendTo, FieldPosition fieldPosition) {
            ...
    }
    
  6. **The keyword is followed by an open parenthesis "(", and there should be a space after the keyword. * * in the following example, there is a space after while.

    while (a == d) {
        ...
    }
    

2.3.3 indent

Four spaces are often used as a unit of indentation. Although programmers use tabs to indent during development, and a tab is equal to 8 spaces by default, the number of tabs and spaces in different IDE tools will be different. In Eclipse, one tab corresponds to four spaces by default.

Indentation can be based on general specifications, as follows.

  1. In code blocks containing braces "{}" such as methods, Lambda and control statements, the content of the code block is indented by one level (4 spaces) relative to the first line.
  2. if it is a line break of a conditional expression in an if statement, the new line should be indented two levels (8 spaces) relative to the previous line, and the next line break should be aligned with the first line break.

Examples are as follows:

public class Date extends java.util.Date {

    ...

    public String getString() {

        int year = super.getYear() + 1900; // Year of calculation
        int month = super.getMonth() + 1; /* Calculation month */
        int day = super.getDate();

        if ((longName1 == longName2)
                || (longName3 == longName4) && (longName3 > longName4)     ①
                && (longName2 > longName5)) {  ②

        }

        return null;
    }
}

Lines ① and ② of the above code are the line breaks of the conditional expression of the if statement, and lines ① and ② of the code should be aligned.

2.3.4 line break

The length of a line of code shall not exceed 80 characters as far as possible. If it exceeds 80 characters, it needs to be broken. It can be broken according to the following general specifications:

  1. Break after a comma.
  2. Break in front of an operator, select the higher-level operator (not the lower-level operator) to break.
  3. The new line should be indented two levels (8 spaces) relative to the previous line.

Here are some examples:

longName1 = longName2 * (longName3 + longName4 - longName5)
        + 4 * longName6    ①
longName1 = longName2 * (longName3 + longName4
        - longName5) + 4 * longName6  ②

private static DateFormat get(int timeStyle, int dateStyle,
                                  int flags, Locale loc) {  ③
    ...
}

if ((longName1 == longName2)
    || (longName3 == longName4) && (longName3 > longName4)
    && (longName2 > longName5)) {    ④

}

 boolName1 = (longName3 == longName4)
     ? (longName3 > longName4)
     : (longName2 > longName5);     ⑤


Lines ① and ② of the above code are expressions with parentheses. The disconnection position of line ① of the code is better than that of line ②. Because the break in line ① of the code is outside the parenthesis expression, this is a high-level break.

Line ③ of the code is the method name, and the disconnection is after the comma of the parameter.

Line ④ of the code is an if judgment statement. Since there may be many long conditional expressions, the disconnection position should be at the logical operator.

Line ⑤ of the code is the disconnection of the ternary operator.

2.4 other specifications

In addition to the above specifications, there are many scattered specifications. Some important specifications are supplemented below.

  1. **It is recommended to declare variables or constants one at a time** Examples are as follows:

    Recommended:

    int longName1 = 0 ;
    int longName2 = 0 ;
    

    Not recommended:

    int longName1 = 0, longName2 = 0 ;
    
  2. **The left brace "{" is at the end of the declaration statement line. The right brace "}" starts on another line and is aligned with the corresponding declaration statement. Unless it is an empty statement, the right brace "}" should immediately follow the left brace "{". * * examples are as follows:

    public class Date extends java.util.Date {
    
        int longName1 = 0;
        int longName2 = 0;
    
        boolean boolName1 = true;
    
        public String getString() {
    
            int year = super.getYear() + 1900; // Year of calculation
            int month = super.getMonth() + 1; /* Calculation month */
            int day = super.getDate();
    
            return null;
        }
    
        public void setString() {}
    }
    
  3. **Each line contains at most one statement** Examples are as follows:

    Recommended:

    argv++;
    argc--;
    

    Not recommended:

    argv++; argc--;
    
  4. Although * * Java language allows you to omit the left and right braces when there is only one line of code for control statements such as if and for, the coding specification does not recommend this** Examples are as follows:

    Recommended:

    if (1 == 3) {
        x = 2.3;
    }
    

    Not recommended:

    if (1 == 3)
        x = 2.3;
    

    public String getString() {

        int year = super.getYear() + 1900; // Year of calculation
        int month = super.getMonth() + 1; /* Calculation month */
        int day = super.getDate();
    
        return null;
    }
    
    public void setString() {}
    

    }

    ``

  5. Each line contains at most one statement. Examples are as follows:

    Recommended:

    argv++;
    argc--;
    

    Not recommended:

    argv++; argc--;
    
    
  6. Although the Java language allows you to omit the left and right braces when there is only one line of code for control statements such as if and for, the coding specification does not recommend this. Examples are as follows:

    Recommended:

    if (1 == 3) {
        x = 2.3;
    }
    

    Not recommended:

    if (1 == 3)
        x = 2.3;
    

    In fact, there are many norms that cannot be exhausted, so I won't repeat them here.

Topics: Java Programming Code Style