Java developers the most basic norms do not understand, ye developed every day! - end of the text to send books

Original link: https://item.jd.com/12566109.html

Click on the top [ full-stack developer community ]upper right corner [...][set to star ⭐ ]

640?

Author: silianpan

juejin.im/post/5ada99fff265da0b8a672fbd


Based on Alibaba JAVA development specifications finishing

https://github.com/alibaba/p3c

A named style

[Mandatory] use UpperCamelCase style class name, must comply with the hump form, but the following exceptional circumstances: DO / BO / DTO / VO / AO

  • 正例:MarcoPolo / UserDO / XmlService / TcpUdpDeal / TaPromotion

  • 反例:macroPolo / UserDo / XMLService / TCPUDPDeal / TAPromotion

[Mandatory] method name, parameter name, member variables, local variables are consistent use lowerCamelCase style, you must comply with the hump form.

  • 正 例: localValue / getHttpMessage () / inputUserId

[Mandatory] constant naming all uppercase, separated by an underscore between words, semantic integrity and strive to clear, not too long name.

  • Positive examples: MAX_STOCK_COUNT counter-example: MAX_COUNT

[Mandatory] use Abstract abstract class name or the beginning of the 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.

[Forced] in Boolean variables Model class, do not add is, or part of the analytical framework will cause serialization error.

  • Anti Example: is defined as the basic data types Boolean isDeleted; attribute, which is a method isDeleted (), RPC frame when the reverse analysis, "that" is deleted corresponding to attribute names, attribute acquisition not cause, in turn thrown .

[Mandatory] for Service and DAO classes, based on the concept of SOA, must be exposed service interfaces, internal interfaces of the implementation class suffix Impl and with a difference. Positive Example: CacheManagerImpl CacheManager implement the interface.

[Recommended] To achieve the object code self-explanatory, any custom programming elements in the name, try to use the full word combinations to express its meaning.

Positive Example: pulling code from a remote repository class is named PullCodeFromRemoteRepository

  • A random named; variable int a: counterexample.

[Recommended] interface class methods and properties do not add any modification symbol (public and do not add), to maintain simplicity of the code, plus effective Javadoc comments. Try not defined in the interface in variable, if we must define a variable, it is certainly related to the interface method, and is the basis for constant throughout the application.

  • Positive Example: Interface Method Signature: void f (); interface base represented by the constants: String COMPANY = "alibaba";

  • Counterexample: interface method definitions: public abstract void f ();

  • Description: JDK8 interfaces allow a default implementation, then the default method is the default for all classes have realized the value of implementation.

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

  • Description: enumeration constants is actually a special class, and is forced to default constructor is private.

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

[Reference] layers naming conventions:

Service / DAO layer naming convention method

  • Gets a single object method prefixed with get.

  • Acquiring a plurality of object methods prefixed with list.

  • Obtain a statistical value of the method prefixed with count.

  • The method of insertion is prefixed with save / insert.

  • Remove method prefixed with remove / delete.

  • Modified method prefixed with update.

Second, the definition of variables

[Recommended] Do not use a constant maintenance of all class constants, the constants are classified according to function, are maintained separately. Description: large and constant class, have to use the Find function to locate to modify constants, is not conducive to understand and maintain.

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

Third, the code format

[Mandatory] braces usage conventions. If it is empty, succinctly written within braces {}, you do not need wrap; if the block is not empty:

  • Does not wrap before opening brace.

  • Left back brace wrap.

  • Before the closing brace wrap.

  • After the right brace else there will not line feed code, etc. a rear right brace must wrap termination.

[Forced] does not appear spaces between the left parenthesis and character; likewise, there occurs a space between the right parenthesis and character.

  • Anti Example: if (a == b blank spaces)

[Mandatory] between if / for / while / switch / do and other reserved words and brackets must be spaces.

[Force] any two items, ternary operator needs both sides of a space.

  • Description: operators include assignment operators =, logical operators &&, arithmetic symbols.

[Mandatory] using 4 spaces to indent, prohibit the use of tab characters.

  • Description: Vue project uses two spaces to indent

There is only one space between [mandatory] double slash comment and annotation content. Positive examples: // annotation content, note that there is a space between // comments and content.

[Mandatory] when defining method parameters and pass multiple parameters must be a space behind the comma.

  • Positive Example: The following example argument "a", there must be a space behind. method ( "a", "b", "c");

[Mandatory] IDE's text file encoding to UTF-8; line breaks in the IDE using the Unix file format, do not use the Windows format.

[Recommended] The method is performed in vivo group of statements, statements inserted between the set of variables is defined, between the different business logic or a blank line different semantics. Without inserting a blank line between the business logic and the same semantics.

  • Description: There is no need to insert a plurality of spaced-blank lines.

Four, OOP Statute

[Mandatory] overrides all methods, it must be added @Override comment.

[Force] can not use outdated classes or methods.

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

  • 正例:"test".equals(object);

  • 反例:object.equals("test");

Comparison between the value of [force] packaging all objects of the same type, all using the equals method to compare.

  • ? Description: For assignment Integer var = -128 to 127 range, Integer object is generated IntegerCache.cache will reuse existing object, Integer values ​​within this range may be used directly for determination ==, but this interval All data outside, the heap will be produced, not reusing existing object, which is a pit, is determined using the equals method recommended.

[Force] RPC parameter and return value data type packaging must be used.

[] Constructor which prohibits forced to join any business logic, if there is initialization logic, put it in the init method.

[Recommended] When a class has multiple constructors, the same name or a plurality of methods, which should be placed together in the order, easy to read.

[Recommended] circular body, connection strings, using the StringBuilder append extension method.

  • Description: decompile the byte code files are displayed for each cycle a new StringBuilder object, then append operation, and returns the String object using the toString method, resulting in a waste of memory resources.

  • Counterexample:

  String str = "start";
  for (int i = 0; i < 100; i++) {
  str = str + "hello";
  }

[Recommended] caution Object clone method to copy objects. Description: clone method is the default object shallow copy, the copy you want to achieve deep copy clone implemented method to rewrite attribute object.

Fifth, the collection process

[Use] set force transfer array, must be set toArray (T [] array), is passed in exactly the same type of array size is list.size ().

  • Description: using parameterized toArray method, an array reference into the allocated space is not large enough, the internal toArray method reallocate memory space, and returns the new address of the array; if the array elements is greater than is actually required, the subscript [list.size () ] array element is set to null, the other array elements holding the original value, so the same method is preferable to set the number of parameters to define the size of the collection elements.

  • Positive examples:

List<String> list = new ArrayList<String>(2);
list.add("guan");
list.add("bao");
String[] array = new String[list.size()];
array = list.toArray(array);

  • Anti Example: no problems directly toArray reference method, this method can only return value Object [] class, if other types of arrays turn strongly ClassCastException error occurs.

[] Do not force the elements remove / add operations in the foreach loop. remove elements, use Iterator way, if concurrent operations, the need for Iterator object locking.

  • Positive examples:

  Iterator<String> iterator = list.iterator();
  while (iterator.hasNext()) {
      String item = iterator.next();
      if (删除元素的条件) {
        iterator.remove();
      }
  }

  • Counterexample:

  List<String> list = new ArrayList<String>();
  list.add("1");
  list.add("2");
  for (String item : list) {
    if ("1".equals(item)) {
      list.remove(item);
    }
  }

[Recommended] Use entrySet traverse Map collection of classes KV, rather than keySet way to traverse.

Sixth, control statements

[In] a forced switch block, or in each case terminated by a break / return, etc., or explanatory notes to which the program will continue until the case; within a switch block, must contain a default statement and placed at the end even if it is what the code does not.

[Mandatory] you must use braces if / else / for / while / do statement. Even if only one line of code to avoid a single line encoding: IF (for condition Condition) statements;

[Recommended] In addition to commonly used methods (such as getXxx / isXxx) endures, do not perform other complex conditional statements, the result of a complex Boolean logic judge is assigned to a variable name makes sense, to improve readability.

  • Description: a lot of logic in the if statement is fairly complicated, the reader need to analyze the final result of the conditional expression, what kind of conditions in order to be clear what kind of statement is executed, then, if the reader analyze logic expressions mistake?

  • Positive examples:

//伪代码如下
final boolean existed = (file.open(fileName, "w") != null) && (...) || (...);
if (existed) {
  ...
}

  • Counterexample:

if ((file.open(fileName, "w") != null) && (...) || (...)) {
  ...
}

[Recommended] loop statements to performance considerations, the following in vitro processing proceeds to the loop as much as possible, as defined objects, variables, database connection, unnecessary try-catch operation (if the try-catch cycle may move in vitro ).

[Reference] the following cases, the need for calibration parameters:

  • Call the low frequency method.

  • Great execution time overhead method. In this case, the parameter calibration time is almost negligible, but if because of parameter error led to the middle of a rollback or error, and that more harm than good.

  • Require extremely high stability and availability of the method.

  • Open interfaces provide external, whether RPC / API / HTTP interface.

  • Sensitive permissions entrance.

Seven of the Statute comments

[ Mandatory] classes, class properties, class methods must be annotated using Javadoc specification, use the / * content / format may not be used // xxx way.

[Mandatory] all the abstract methods (including interface methods) must be used Javadoc comments, in addition to the return values, parameters, exceptions stated, it must be noted that the method to do something, to achieve what functions.

  • Description: achieve sub-class requirements, or call precautions, please also explain.

[Mandatory] All classes must be added the creator and creation date.

[Mandatory] internal method of single-line comments in the above statement is a comment on a separate line, using // comments. The method of using the internal multi-line comment / * * / comment, and note that the code is aligned.

[Mandatory] all the enumerated type field must have a note about the purpose of each data item.

[Recommended] code changes at the same time, comments should be modified accordingly, in particular, parameters, return values, abnormality, the core logic and other modifications.

  • Description: Notes code updates are not synchronized, like road network and navigation software update does not synchronize the same, if navigation software is seriously lagging behind, it lost the meaning of navigation.

[Reference] cautious commented code. Described in detail above, rather than simply comment out. If useless, it is deleted.

[Reference] For footnotes requirements: first, the reaction can be accurately design and code logic; second, meaning able to describe the service, so that other programmers to quickly learn the code behind the information. No comments for large sections of the code reader just like hieroglyphics, the comment is for yourself, even if separated for a long time, but also a clear understanding at that time the idea; Notes also look to his successor, so that it can quickly take over their own jobs.

[Reference] good name, code structure is self-explanatory, comments to be simple and accurate expression in place. To avoid the emergence of an extreme comments: Logic excessive number of comments, of any revision of the code, modify the note is a considerable burden.

[Reference] special comment tags, please indicate the mark of man and mark time. Note that the timely processing of these markers by marking the scan, frequent cleaning of such marks. Sometimes the fault line is derived from the code at these marks.

  • Do (TODO) :( person mark, mark time, [estimated processing time]) the need to achieve, but has yet to achieve the function. This is actually a Javadoc tag, the current Javadoc not yet implemented, but has been widely used. It can be applied to classes, interfaces and methods (because it is a Javadoc tag).

  • Error, can not work (FIXME) :( person mark, mark time, [estimated processing time]) labeled with a code in comments FIXME is wrong and does not work, the situation needs to be corrected in time.

Eight other

[Forced] when using regular expressions, make good use of its pre-compiled function, can effectively accelerate the speed of a regular match. Note: Do not vivo method defined: Pattern pattern = Pattern.compile (rule);

[Note] forced Math.random () This method returns a double type, attention range of values ​​0≤x <1 (to a zero value can be taken, in addition to zero exception noted), if you want to acquire the random number integer type, do not x is then enlarged several times rounding 10, directly or nextLong nextInt Random object method.

[Force] Gets the current number of milliseconds System.currentTimeMillis (); instead new Date () getTime ().;

[Recommended] construct or initialize any data structures should specify the size of the data structure to avoid unlimited growth eat memory.

Nine, exception handling

[Forced] to catch the exception to handle it, do not capture the process, but nothing abandon it, if you do not deal with it, the abnormal thrown to its caller. Outermost service user must handle the exception, the converted content to the user can be appreciated.

Ten, MySQL database

Creating tables Statute

[Mandatory] table names, field names must be lowercase letters or numbers, start with a number banned, prohibited only the middle two numbers appear underlined. Modify the cost of a large database field names, because they can not carry out a pre-release, so the field names need to be carefully considered.

  • Description: MySQL is not case sensitive in Windows, but by default in Linux is case sensitive. Therefore, the database names, table names, field names, do not allow any uppercase letter, to avoid any further complications.

  • 正例:aliyun_admin,rdc_config,level3_name 反例:AliyunAdmin,rdcConfig,level_3_name

[Forced] to disable a reserved word, such as desc, range, match, delayed, please refer to the official MySQL reserved words.

[Mandatory] primary key index named pk_ field names; unique index called uk_ field names; ordinary index name was idx_ field name. Description: PK_ Key i.e. Primary; uk_ Key i.e. UNIQUE; idx_ i.e. short index.

[Mandatory] decimal type is decimal, prohibit the use of float and double.

[Force] If the length of a string is almost equal, the use of fixed-length string type char.

[Varchar] mandatory variable length strings, not pre-allocated storage space, a length not more than 5000, if the memory length is greater than this value, the field type is defined as text.

[Mandatory] table must have three fields: the above mentioned id, create_time, update_time, delete_flag

[Force] field for the Boolean type, using decimal type

[Mandatory] tables and fields need to add annotation information.

[Recommended] single table rows over 5 million lines or single-table capacity of more than 2GB, it is recommended sub-library sub-table. Note: If the amount of data expected after three years failed to reach this level, you do not sub-library sub-table when creating tables.

[Reference] Suitable character storage length, not only save space database tables, saving index storage, more importantly, to enhance the retrieval speed.

Index Statute

[ Force] fields having unique operational characteristics, even when a combination of a plurality of fields, a unique index must be completed.

  • Note: Do not think that unique index affects the insert speed, the speed loss is negligible, but to improve the search speed is obvious; In addition, even at the application layer to do a very comprehensive check control, as long as there is no unique index, according to Murphy's Law, there must be dirty data generated.

[Mandatory] prohibits more than three tables join. Need to join the field, data types must be absolutely consistent; multi-table associated with the query, ensure that fields are associated with the need to have an index.

  • Note: Also note that even if the two-table join table index, SQL performance.

[Mandatory] indexing on varchar fields, you must specify the length of the index, no need for indexing the whole field, you can determine the length of an index based on the actual text of discrimination.

  • Description: the length of the discrimination index is a contradiction, the general type of string data length of the index 20, the discrimination will be more than 90%, can count (distinct left (column name, index length)) / count (*) to determine the degree of differentiation.

[Reference] when creating an index to avoid extreme misunderstanding following:

  • Ninglanwuque. I think a query needs to build an index.

  • Ningquewulan. Think the index will consume space, a serious slow down the speed of updates and additions.

  • The only index boycott. The only think that all of the business need to be addressed in the application layer through the "check the plug after the first" approach.

SQL statements

[Mandatory] Do not use the count (column name) or count (constant) instead of count ( ), count ( ) syntax is the number of rows SQL92 standard statistical definition, has nothing to do with the database, nothing to do with NULL and non-NULL.

  • Description: count (*) counts the value NULL row, while count (column name) does not count rows in this column is NULL values.

[Force] count (distinct col) calculates the number of columns is not repeated rows other than NULL, the note count (di col1, col2) If a whole is NULL, then even if another row have different values, but also returns to zero.

[Force] value when a column is full NULL, count (col) returns a value of 0, but the sum (col) returns a value of NULL.

[] Shall not be used to force a foreign key with a cascade, all foreign key concepts that must be addressed in the application layer.

[Mandatory] prohibit the use of stored procedures, stored procedures, difficult to debug and extend, and no portability.

[Recommended] in operation can be avoided, avoid, if it can not avoid the need to carefully assess the number of elements in the set back control in the 1000's.

[Reference] If there is need for globalization, all the characters are stored and representation, are utf-8 encoding, note the difference of characters.

  • Description: SELECT LENGTH ( "light work"); returns 12 SELECT CHARACTER_LENGTH ( "light work"); return to 4 if needed to store expressions, then select utfmb4 for storage, pay attention to the difference between it and UTF-8 encoding.

[Force] When the updated data table records, update records must update_time field value corresponding to the current time.

[Reference] @Transactional affairs do not abuse. Transactions affect QPS database, in addition to the use of local affairs to consider a rollback of all aspects of the program, including the rollback cache, search engine rollback, the message compensation, and other statistical correction.

Recommended: " Machine Learning Linear Algebra "

640?wx_fmt=png

Editors: Linear algebra is the cornerstone of machine learning

Copy Amoy password "€ UxB4YMdwFDg €" or read the original to learn more. . .

I think this paper help you? Please share with more people

Watch " full-stack developer community ," starred, full-stack upgrade skills

This number will be public to everyone from time to time send welfare, including sending books, learning resources, please look forward to it!

If you feel the push content is good, it may be a lower right corner looking forward circle of friends or favorites, thanks for the support.

Good article, I look at ❤️

Guess you like

Origin blog.csdn.net/weixin_35681869/article/details/101730923