Java development habits _ from Alibaba

Source: Internet
Author: User

---restore content starts---

"Force" The variable of the Boolean type in the Pojo class, do not add is, or some of the framework parsing will cause serialization errors. Issuccess: A property that is defined as a basic data type, Boolean, whose method is also issuccess (), when the RPC framework, in reverse parsing, "thinks" that the corresponding property name is success, causes the property to be fetched, and throws an exception.

The "Force" package name is uniformly used in lowercase, and there is only one natural semantic English word between the point separators. The package name is unified using the singular form, but if the class name has a plural meaning, the class name can use the plural form.
Example: Application tool class package named Com.alibaba.open.util, class name Messageutils (this rule references spring's frame structure)

Methods and properties in the "recommended" interface class do not add any modifiers (public nor add), keep the code concise, and add a valid Javadoc comment. Try not to define variables in the interface, if you must define a variable, it is definitely related to the interface method and is the underlying constant for the entire application.
Example: Interface method signature: void F ();

Interface base constant representation: String company= "Alibaba";
Counter Example: Interface method definition: Public abstract void f ();
Description: The default method is a default implementation that is valuable to all implementation classes, as the interface in JDK8 allows for the implementation of the defaults.

There are two sets of rules for naming interfaces and implementing classes:
1) "Mandatory" for service and DAO classes, based on the SOA concept, exposed services must be interfaces, internal

The implementation class is distinguished from the interface using the Impl suffix. Positive example: Cacheserviceimpl implements Cacheservice interface.

2) "Recommended" If it is the interface name that describes the ability, take the corresponding adjective to do the interface name (usually the form of –able). Positive example: Abstracttranslator implements Translatable.

"Reference" the naming conventions of each layer:
A) Service/dao layer method naming protocol

1) The method to get a single object is prefixed with get.
2) The method to get multiple objects is prefixed with the list.
3) The method that gets the statistic value is prefixed with count.
4) Insert the method prefix with save (recommended) or insert.

5) Remove the method prefix with remove (recommended) or delete.

6) The modified method is prefixed with update.

B) domain model naming conventions
1) Data object: Xxxdo,xxx is the name of the data table.
2) Data Transfer object: Xxxdto,xxx the name that is relevant for the business domain.

3) Display object: Xxxvo,xxx is generally the name of the page.

Constant definition

No magic values (that is, undefined constants) are allowed to appear directly in the code. Counter example: String key= "Id#taobao_" +tradeid;

Cache.put (Key,value);


4) Pojo is a general term for DO/DTO/BO/VO, and is forbidden to be named Xxxpojo.

"Recommended" do not use a constant class to maintain all constants and should be categorized by constant function and maintained separately. For example: Cache-related constants are placed under Class: Cacheconsts; system configuration-related constants are placed under class: Configconsts. Description: Chatty constant class, must use the Find function to locate the modified constant, is not conducive to understanding and maintenance.

The reuse level of the recommended constant is five layers: across application shared constants, in-app shared constants, in-sub-engineering shared constants, in-package shared constants, and in-Class shared constants.

1) shared constants across applications: Placed in a two-party library, usually under the constant directory in Client.jar.

2) in-app shared constants: placed in the constant directory in the modules of a party library.

Inverse example: the easy-to-understand variable is also uniformly defined as an in-app shared constant, and two siege divisions define a variable that represents "Yes" in two classes:

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 the actual return is false, resulting in a problem on the line.

OOP protocol

"Force" avoids accessing static or static methods of this class through the object reference of a class, unnecessarily increasing the compiler parsing

   It can be accessed directly using the class name.
"Force" externally exposed interface signature, in principle, does not allow the modification of the method signature, to avoid affecting the interface callers. Interfaces that are obsolete must be annotated with @deprecated and clearly describe what the new interface or new service is used for.

The Equals method of the "force" object is prone to throwing null pointer exceptions, and you should call equals using constants or determining which objects have values.

Positive example: "Test". Equals (object);
Counter Example: Object.Equals ("test"); Description: Recommended use of java.util.objects#equals (JDK7 introduced tool Class)

"Force" all comparisons between the values of the same type of wrapper class object, all using the Equals method. Description: For integer var=? In the assignment between 128 and 127, the integer object is generated in Integercache.cache, and the existing object is reused, and the integer value within this interval can be judged directly using = =. However, all data outside this interval will be generated on the heap and will not be reused for existing objects, which is a big pit, and it is recommended to use the Equals method for judgment.

Mandatory usage criteria for basic data types and wrapper data types are as follows:

1) All Pojo class properties 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 "recommended" use basic data types.

Description: The Pojo class attribute does not have an initial value, it is a reminder that the user must make an explicit assignment when needed, any

The NPE issue, or inbound check, is guaranteed by the user.

It is forbidden to add any business logic inside the "force" constructor, and if there is initialization logic, put it in the Init method.

The "force" Pojo class must write the ToString method. Using the IDE's Medium tool: Source>generate toString, if you inherit another Pojo class, be careful to add super.tostring to the front. Description: When the method execution throws an exception, you can directly call Pojo's ToString () method to print its property values for easy troubleshooting.

In-class method definition order is: Public method or Protection method > Private Method >getter/setter

Method. Description: The public method is the caller and maintainer of the class most concerned about the method, the first screen display the best; Although the protection method is only a subclass of care, it may be the "template design pattern" under the core approach, while the private method outside generally do not need special care, is a black box implementation; Because the value of the method information is low, All service and DAO Getter/setter methods are placed at the end of the class body.

The "recommended" loop body, the way strings are joined, is extended using the StringBuilder append method.

Counter Example:

String str = "Start"; for (int i=0; i<100; i++) {

str = str + "Hello";}

Description: The deserialized bytecode file shows that each loop will be new to a StringBuilder object, then the append operation, and finally the ToString method to return the string object, resulting in a waste of memory resources.

"Recommended" final improves program responsiveness and is declared final: 1) variables that do not need to be re-assigned, including class attributes, local variables.
2) The object parameter is final, which means that the point of the reference is not allowed to be modified.
3) The class method determines that it is not allowed to be overridden.

"Recommended" class members and method access control are strictly:

1) If the external object is not allowed to be created directly from new, then the constructor must be private. 2) The tool class does not allow public or default construction methods.
3) class non-static member variable and shared with subclass, must be protected.
4) class non-static member variable and used only in this class, must be private.

5) class static member variable if used only in this class, it must be private.

6) If the static member variable, you must consider whether it is final.
7) The class member method is only intended for internal invocation of the class and must be private.
8) The class member method is only exposed to the inheriting class, so it is limited to protected.

Description: Any class, method, parameter, variable, strict access to the scope. A wide range of access is not conducive to module decoupling. Think: If it is a private method, want to delete the deletion, but a public service method, or a public member variable, delete it, not palms sweat it? Variables like their own children, as far as possible within their own sight, the variable scope is too large, If you run around indefinitely, you'll be worried.

(v) Collection processing

"Enforce" the handling of hashcode and equals, following the following rules:
1) If you rewrite equals, you must rewrite hashcode.
2) Because set stores objects that are not duplicates and are judged according to Hashcode and equals, the set stored objects must override both methods.
3) If the custom object is a key to map, you must override Hashcode and equals.
A positive example: string overrides the Hashcode and equals methods, so we can use the string object as a key very happily.

The sublist result of the "force" ArrayList cannot be strongly turned into ArrayList, otherwise a classcastexception exception will be thrown: Java.util.RandomAccessSubList cannot is cast to java.util.ArrayList; Description: Sublist returns the inner class sublist of ArrayList, not ArrayList, but a view of ArrayList, All actions for the Sublist sub-list will eventually be reflected on the original list.

"Force" in the sublist scene, a high degree of attention to the number of elements of the original collection of changes, will cause the child list traversal, increment, delete all produce concurrentmodificationexception exception.

The "force" generic wildcard character <?extends t> to receive the returned data, and the generic collection of this notation cannot use the Add square method.

Description: After the Apple is boxed and returned a <?extends fruits> object, this object cannot be added to any fruit, including apples.

"Force" do not perform the remove/add operation of elements in the Foreach loop. remove element Please use iterator

method, if concurrent operation, need to lock the iterator object.

Counter Example:

List<string> a = new arraylist<string> ();

A.add ("1");
A.add ("2");
for (String temp:a) {

          if ("1". Equals (temp)) {             a.remove (temp);

}}

Java development habits _ from Alibaba

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.