Alibaba Java Development Manual personal finishing compact version (i)

Source: Internet
Author: User
Tags compact constant definition logical operators lowercase serialization variable scope wrapper stringbuffer

Personal programming time, though not short, but the overall project experience is still relatively deficient, and the individual's programming style has not formed, in order to make their own programming more pleasing (not sad) recently saw Ali Java development programming of the Statute want to have some positive impact on their own programming style, Here are some of my notes and summaries:
I. Programming protocol
(i) Naming conventions
1. "Mandatory" all programming-related names cannot begin with an underscore or dollar sign, or end with an underscore or dollar sign. Anti-Example: _name/__name/object/name/name object/name_/name/object$
2. "Mandatory" all programming-related naming is strictly prohibited the use of Pinyin and English mixed mode, but also do not allow direct use of the Chinese way.
Description: Correct English spelling and grammar can make reading readers easy to understand and avoid ambiguity. Note that even the pure phonetic naming method should be avoided. Anti-Example: dazhepromotion [discount]/Getpingfenbyname () [rating]/int variable = 3;
For example: Ali/alibaba/taobao/cainiao/aliyun/youku/hangzhou and other international common names can be regarded as English.
3. The "Mandatory" class name uses the Uppercamelcase style and must be in the Hump form, except in the following cases: (correlation naming of domain models) Do/dto/vo/dao etc. Positive Example: Marcopolo/userdo/xmlservice/tcpudpdeal/tapromotion Counter Example: Macropolo/userdo/xmlservice/tcpudpdeal/tapromotio N
4. "Mandatory" method name, parameter name, member variables, local variables are unified use Lowercamelcase style, must follow the hump form. Positive example: Localvalue/gethttpmessage ()/Inputuserid
5. "Mandatory" constant name all uppercase, the words are separated by an underscore, to achieve the semantic expression of complete and clear, not too long name. Positive Example: Max_stock_count Counter Example: Max_count
6. The "force" abstract class name begins with abstract or base; The exception class name uses the exception end; The test class is named with the name of the class it wants to test, ending with test.
7. The "force" bracket is part of the array type, and the array is defined as follows: string[] args; Anti-Example: do not use string args[as a way to define
8. "Force" Pojo any boolean-type variable in the class without the IS, or partial framework parsing can cause serialization errors. Anti-Example: a property defined as a Boolean issuccess of the base data type, its method is also issuccess (), and the RPC framework, when it is reverse parsing, "thinks" the corresponding property name is success, causing the property to be fetched, which throws an exception.
9. "Mandatory" package name unified use lowercase, dot delimiter between there is and only a natural semantics of English words. The package name is uniformly singular, but if the class name has a plural meaning, the class name can use the plural form. Example: Utility class Package name is Com.alibaba.mpp.util, class name is messageutils (this rule references spring's frame structure)
10. "Mandatory" to eliminate the complete irregular abbreviations, to avoid the hope that the text does not know righteousness. Anti-Example:< a business code >abstractclass "abbreviation" named absclass;condition "abbreviation" named Condi, such arbitrary abbreviations severely reduce the readability of the code.
11. "Recommended" If the design pattern is used, it is recommended to reflect the specific pattern in the class name. Description: The design pattern is embodied in the name, which helps the reader to understand the architecture design idea quickly.
Positive example: public class orderfactory; public class Loginproxy; public class Resourceobserver;
12. The methods and properties in the "recommended" interface class do not add any modifiers (public or not) to keep the code concise and to add a valid Javadoc annotation. Try not to define variables in the interface, if you must define variables, it must be related to the interface method, and the entire application of the underlying constants.
Positive example:
interface method signature: void F ();
Interface base constants represent: String company = "Alibaba";
Counter Example:
Interface method definition: Public abstract void f ();
Note: The JDK8 interface allows a default implementation, and this default method is a value-only implementation for all implementation classes.
13. Interfaces and implementation classes are named with two sets of rules:
1 "coercion" for service and DAO class, based on SOA concept, the exposed service must be the interface, the internal implementation class with Impl suffix and interface difference.
In the positive example: Cacheserviceimpl implements the Cacheservice interface.
2 "recommend" if it is the interface name of the description ability, take the corresponding adjective to do the interface name (usually the form of –able).
Positive example: Abstracttranslator realizes translatable.
14. The "Reference" enumeration class name is recommended with the enum suffix, the enumeration member names need to be all uppercase, and the words are separated by an underscore.
Description: Enumerations are actually special constant classes, and the constructor method is private by default.
Positive Example: enumeration name: Dealstatusenum; member name: Success/unkown_reason.
15. Naming conventions for "reference":
A) Service/dao layer method naming protocol
1 The method of obtaining a single object is prefixed with get.
2 The method of obtaining multiple objects is prefixed with list.
3 The method of obtaining the statistic value is prefixed with count.
4 The inserted method is prefixed with save or insert.
5 The method of deletion is prefixed with remove or delete.
6) The modified method is prefixed with update.
(B) domain model naming conventions
1 data object: XXXDO,XXX is the data table name.
2 Data Transfer object: Xxxdto,xxx is the name of the business domain.
3) Display object: Xxxvo,xxx is generally the name of the Web page.
4) Pojo is a general designation of DO/DTO/BO/VO, which is forbidden to be named Xxxpojo.
(ii) Constant definition
1. "Force" does not allow any magical value (that is, undefined constants) to appear directly in your code.
Counter Example:
String key= "Id#taobao_" +tradeid;
Cache.put (key, value);
2. When "mandatory" long or long initial assignment, must use uppercase L, not lowercase l, lowercase easily confused with the number 1, resulting in misunderstanding.
Description: Long a = 2l; Is that a 21 of the number or a long type of 2?
3. "Recommended" do not use a constant class to maintain all constants, should be categorized by the constant function, separate maintenance. For example, cache-related constants are placed under class: Cacheconsts, and system configuration-related constants are placed under class: Configconsts.
Description: All-Inclusive of the constant class, it is necessary to ctrl+f to the modified constants, not conducive to understanding, but also not conducive to maintenance.
4. The reuse level of the "recommended" constant has five layers: shared constants across applications, shared constants within applications, shared constants within a subproject, shared constants within packages, shared constants within a class.
1 shared constants across applications: Placed in a two-party library, usually under the const directory in Client.jar.
2 Application-Shared constants: The const directory placed in the modules of one side library. Anti-Example: easy to understand variable also to be defined as the application of shared constants, two of the siege in two classes, respectively, defines the variable representing "Yes": Class A: public static final String Yes = "yes"; Class B: public static final String YES = "Y"; A.yes.equals (B.yes), expected to be true, but actually returned to false, resulting in an online problem.
3 The Sub-project internal share constant: that is, in the current sub-project const directory.
4 shared constants within the package: that is, under the current package under a separate const directory.
5 shared constants within the class: private static final definition directly within the class.
5. "Recommended" If the variable value changes only within one range with the Enum class. If you also have an extension property other than the name, you must use the Enum class, and the number in the example below is the extension information, which means the day of the week. Example: Public enum{MONDAY (1), Tuesday (2), Wednesday (3), Thursday (4), FRIDAY (5), SATURDAY (6), SUNDAY (7);
(iii) Format specification
1. "Mandatory" braces for the use of the Convention. If the braces are empty, simply write {} without wrapping, or if the Non-empty code block:
1) The left curly brace is not wrapped before wrapping.
2) left Curly brace after line.
3 The right curly brace before wrapping.
4) After the closing brace, there are other codes that do not wrap, and the closing brace must be wrapped.
2. There is no space between the "force" opening parenthesis and the last character; Similarly, no spaces appear between the closing parenthesis and the previous character. See article 5th below the founder's prompt.
3. There must be a space between the reserved words "mandatory" if/for/while/switch/do and the left and right brackets.
4. "Force" any operator must add a space.
Description: Operators include assignment operators =, logical operators &&, subtraction symbols, three-head run characters, and so on.
5. "Force" code block indent 4 spaces, if you use the tab indent, set 1 tab to 4 spaces. Positive example: (involving 1-5 points)

public static void Main (String args[]) { 
    //indent 4 spaces 
    String say = "Hello"; 
    operator must have a space of 
    int flag = 0; 
    There must be a space between the keyword if and the parentheses, the F and the opening parenthesis in parentheses, and the 1 and closing brackets do not require a space 
    if (flag = 0) { 
    System.out.println (say); 
    }
    The left brace is followed by a space and does not wrap, and the left curly brace is changed to
    if (flag = 1) { 
    System.out.println ("World"); 
    The right curly brace before wrapping, after the right curly braces have else, do not change lines 
    } else {
        System.out.println ("OK"); 
        Closing curly braces must be wrapped as ends
    } 
}
"Force" the number of characters in a single line is limited to 120, beyond the need to wrap, change lines, following the following guidelines:
1 indent 4 spaces relative to the previous line.
2) operator wraps with the following line.
3 the point symbol of the method call wraps with the following line.
4 in more than a long parameter, after the comma to wrap.
5 do not wrap before parentheses, see counter example.
Positive example:
StringBuffer sb = new StringBuffer (); 
In the case of more than 120 characters, the newline indents 4 spaces, and the point symbol before the method wraps together
sb.append ("Zi"). Append ("Xin") ... 

Counter Example:

StringBuffer sb = new StringBuffer (); 
In the case of more than 120 characters, do not wrap 
sb.append ("Zi") before parentheses. Append ("Xin") ... append 
("Huang"); 
Many of the parameters of the method call also more than 120 characters, after the comma is the line at the newline 
(ARGS1, ARGS2, ARGS3, ... 
, ARGSX);
The force method parameter, when defined and passed in, must be added with a space behind multiple parameter commas. Positive example: In the following example, the argument "a" must have a space behind it. Method ("A", "B", "C"); "Recommended" There is no need to add several spaces to align the characters of a line with the corresponding characters on the previous line.
Positive example:
int a = 3;
Long B = 4L;
float C = 5F;
StringBuffer sb = new StringBuffer ();
Note: Add SB This variable, if you need to align, then give a, B, c to add a few spaces, in the case of more variables, is a cumbersome thing. The "force" IDE's text file encoding is set to UTF-8; Line breaks for files in the IDE are in UNIX format and do not use Windows format.
10. Insert a blank line between the execution statement group in the body of the recommendation method, the definition statement group of the variable, the different business logic, or the different semantics. No blank lines need to be inserted between the same business logic and semantics.
Note: It is not necessary to insert multiple lines of space to separate.
(iv) OOP protocol "coercion" to avoid the use of a class of object references to such static variables or static methods, needless to increase the compiler resolution costs, directly with the class name to access. To "force" all of the overridden methods, you must add @override annotations. Anti-Example: GetObject () and Get0bject () problems. One is the letter O, one is the number of 0, plus @override can accurately determine whether the overwrite success. In addition, if you modify the method signature in an abstract class, the implementation class compiles the error immediately. "Enforce" the same parameter type, the same business meaning, you can use Java variable parameters, avoid the use of object. Note: The variable parameter must be placed at the end of the argument list. (Encourage students to do as much as possible without variable parameter programming) Example: Public User getusers (String type, Integer ... IDs); "Force" externally exposed interface signatures, in principle, are not allowed to modify method signatures to avoid having an impact on interface callers. An interface is obsolete and must be @deprecated annotated with a clear indication of the new interface used or what the new service is. Force cannot use obsolete classes or methods. Description: The method decode (string encodestr) in Java.net.URLDecoder is obsolete and should use a two-parameter decode (string source, string encode). The interface provider has the obligation to provide the new interface at the same time, since it is clear that it is an outdated interface; As called callers said, there is an obligation to verify what the new implementation of obsolete methods is. The Equals method of the "force" object is easy to throw a null pointer exception, and you should use a constant or a value-determining object to call equals.
Positive example:
"Test". Equals (object);
Counter Example:
Object.Equals ("test");
Note: It is recommended to use the Java.util.objects#equals (JDK7 introduced tool Class) to "enforce" a comparison of values between all the same types of wrapper classes, all using the Equals method. Note: For the integer var= the assignment between 128 and 127, the integer object is generated in Integercache.cache, will reuse the existing object, the integer value in this interval can be directly used to judge, But all the data outside this interval will be generated on the heap and will not reuse the existing object, which is a large pit, which is recommended to be judged using the Equals method. The use criteria for the basic data types and wrapper data types are as follows:
1 All Pojo class attributes must use the wrapper data type.
2 The return value and parameters of the RPC method must use the wrapper data type.
3 All local variables recommend the use of basic data types.
Note: Pojo class properties do not have an initial value is to remind users in need of use, you must explicitly carry out the assignment, any NPE problems, or warehousing inspection, by users to ensure.
In the positive example: The query result of the database may be null, because automatic unboxing, with the basic data type to receive the NPE risk.
Counter Example: A business transaction report shows the total turnover, that is, positive and negative x%,x for the basic data type, RPC service calls, the call is unsuccessful, the return is the default value, the page display: 0%, this is unreasonable, should be shown in the underlined-. So the null value of the wrapper data type can represent additional information, such as a remote call failure and an exception exit. When you define a Pojo class such as DO/DTO/VO, do not set any property default values.
Anti-Example: the default value for do gmtcreate for a business is new Date (), but this property does not place a specific value when the data is fetched, and updates the field when the other fields are updated, causing the creation time to be modified to the current time.
10. When the "force" serialization class adds new properties, do not modify the Serialversionuid field, avoid the deserialization failure, and if the upgrade is completely incompatible to avoid deserialization confusion, modify the Serialversionuid value. Note: It is noted that Serialversionuid inconsistency throws a serialized Run-time exception.
11. The "force" construct method prohibits the addition of any business logic, and if there is initialization logic, place it in the Init method. 12. The "force" Pojo class must write the ToString method. When using the tool class source> generate toString, if you inherit another Pojo class, pay attention to adding super.tostring to the front. Note: When a method executes an exception, the Pojo's ToString () method can be called directly to print its property values to facilitate troubleshooting. "Recommended" using the index to access the array of string split method, you need to do the last delimiter after the content of the check, otherwise there will be the risk of throwing indexoutofboundsexception.
Description
String str = "a,b,c,,";
string[] ary = Str.split (",");
Expected to be greater than 3, the result is 3
System.out.println (ary.length);
14. "Recommended" When a class has multiple constructor methods, or multiple methods with the same name, these methods should be placed together in order to facilitate reading.
15. The method definition order in the "Recommended" class is: Public method or Protection method > Private Method > Getter/setter method.
Description: Public method is the most concerned method for the caller and maintainer of the class. The first screen display is the best; Although the protection method is only a subclass concern, it may be the core method under "Template design pattern", while the private method outside generally does not need special care, is a black box implementation, because the method information value is low, All service and DAO Getter/setter methods are placed at the end of the class body. In the recommended setter method, the parameter name is the same as the class member variable name, this. member name = parameter name. In the Getter/setter method, try not to increase the business logic, increase the difficulty of troubleshooting.
Counter Example:
Public Integer GetData () {
 if (true) {return
      data + =}
   else {return
        data-100;
      } 
  }
The "recommended" loop body, the way strings are joined, is extended using the StringBuilder append method.
Description: The reverse-compiled bytecode file shows that each loop will create a StringBuilder object, then perform the append operation, and finally return the string object through the ToString method, resulting in a waste of memory resources.
18. "Recommended" final can improve the efficiency of the program response, declared as final situation:
1 variables that do not need to be assigned a value, including class attributes, local variables.
2 The object parameter is previously added final, indicating that the reference is not allowed to be modified.
3 The class method determines that it is not allowed to be overridden.
19. "Recommended" carefully use the object of the Clone method to copy objects.
Description: The Clone method of an object is a shallow copy by default, and if you want to implement a deep copy, you need to override the Clone method to implement a copy of the Property object.
20. "Recommended" class members and methods access control strict:
1 if the external object is not allowed to be created directly by new, then the construction method must be private.
2 The tool class does not allow public or default construction methods.
3 class is not a static member variable and is shared with subclasses, it must be protected.
4 class is not a static member variable and only used in this class, must be private.
5 class static member variable if only used in this class, must be private.
6 if the static member variable, must consider whether is final.
7 The class member method is only to be invoked within the class, and must be private.
8 The class member method is only exposed to the inherited class and is limited to protected. Description: Any class, method, parameter, variable, strictly controlled the scope of access. A wide range of access, not conducive to module decoupling. Thinking: If it is a private method, want to delete on the delete, but a public service method, or a public member variable, delete, not palms to take a little sweat. Variables like their own children, as far as possible in their own view, variable scope is too large, if unrestricted to run around, then you will worry about.
Not to be continued ....

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.