Based on the “alibaba Java development manual” and the company actual situation, summed up the actual project developers in the development process should follow the development the process specification, the process specification in a certain extent to ensure the quality of the final project delivery, through summary patterns in time, to avoid developers easily mistakes in practice, Ensure that goals are achieved in large scale collaborative projects. This article mainly discusses the use of Java language development needs to pay attention to the place, does not distinguish between Java Web and Android, some content has nothing to do with Android, Android colleagues if interested can also understand.

Exception handling

“Mandatory” definition of a class of RuntimeException in Java class library, we can check in advance to avoid, and should not catch to processing, such as: IndexOutOfBoundsException, NullPointerException, etc.

Note: Exceptions that do not pass the pre-check, such as catch NumberFormatException when parsing an externally passed string number.

If (obj! = null) {… }

Try {obj.method()} catch (NullPointerException e) {… }

Vernacular: empty is an eternal topic, as long as you are not sure whether the variable is empty, should be empty, otherwise infinite trouble.

[Mandatory] Exceptions should not be used for process control or condition control, because the processing efficiency of exceptions is lower than that of condition branches.

In plain English: Do not use exceptions to encapsulate business logic. Business exceptions should be represented by error codes. System exceptions should use Java native exceptions.

Exception handling is achieved by exception table query, which is certainly not as high as jump statement performance.

It is irresponsible to try and catch large chunks of code. For catch, distinguish between stable code and unstable code. Stable code is code that will not fail no matter what. For the catch of unstable code, distinguish the exception type as far as possible, and then do the corresponding exception processing.

Vernacular: do things to the point, can not generalize.

Instead of simply catching Throwable and then printing a log, this is irresponsible, there should be a specific catch and handle exception.

Catch an exception to handle it. Do not throw it away without handling it. If you do not want to handle it, throw the exception to its caller. The outermost business consumer must handle the exception and turn it into something that the user can understand.

To eat an exception is to catch an exception without doing anything or throwing it, which is also irresponsible behavior.

Throwing exceptions that cannot be handled, but letting the user know about it, is a way of programming the provider contract.

[Mandatory] If you need to roll back a transaction after a catch exception occurs, manually roll back the transaction.

In plain English: we basically use declarative transactions. If there is an exception that needs to be rolled back, it is recommended that we continue to throw exceptions so that the declarative transactions can be rolled back automatically. It is not recommended to manually control transactions in the code.

【 Mandatory 】 The finally block must be used to close resource objects and stream objects, and try-catch exceptions must also be performed. Note: If JDK7 or higher, try-with-resources can be used.

In plain English: The eternal resource shutdown principle.

[Mandatory] You cannot use a return ina finally block. The method ends when a finally block returns, and the return statement in the try block is not executed.

In plain English: does override a return statement inside a try block. No one writes a return statement ina finally statement without confusion.

[Mandatory] Catch and throw must match exactly, or catch must be the parent of throw.

If the opposite party is expected to throw the ball is hydrangea, actually received is shot put, there will be an accident.

After handling an exception, make the exception smaller, not bigger.

The return value of a method can be null. It is not mandatory to return an empty collection, or an empty object, etc. Comments must be added to fully explain when null is returned. The caller needs to make null judgments to prevent NPE problems.

Note: This specification makes it clear that preventing NPE is the responsibility of the caller. Even if the called method returns an empty collection or an empty object, it is not easy for the caller to worry about null returns for remote call failures, runtime exceptions, and other scenarios.

Vernacular: as mentioned above, as long as the uncertain variables, must be empty, don’t ask for trouble.

【 Recommended 】 Preventing NPE is a basic training for programmers. Pay attention to the scenarios where NPE is generated:

The return type is the wrapper data type, which may be null.

Counterexample: public int f() {return Integer object}; If the value is null, the NPE is automatically unpacked and thrown.

The database query result may be NULL.

The element in the set, even if it’s isNotEmpty, can pull out data elements that are null.

The object returned by remote call always requires NPE judgment.

NPE is recommended to check data obtained in Session to avoid null Pointers.

Cascade call obj.geta ().getb ().getc (); A series of calls, easy to generate NPE.

Example: You can use the Optional class of JDK8 to prevent NPE problems.

In plain English: empty, empty, cached data, other people’s data, all to empty.

[Recommendation] Use “throw exception” or “return error code” in the code. You must use “error code” for HTTP/API open interfaces outside the company. In-app recommendation exceptions are thrown; The Result method is preferred for inter-application RPC calls, and isSuccess, Error code, and Error brief message are encapsulated.

Explanation: The reason why RPC method return method Result method is used:

With the throw exception return method, the caller will generate a runtime error if it is not caught.

If you do not add stack information, just new custom exception, add their own understanding of the error message, for the caller to solve the problem will not be much help. If stack information is added, performance loss in data serialization and transmission is also an issue in the case of frequent invocation errors.

In plain English: Business exceptions use the Result pattern, system exceptions use Java native exceptions.

RPC recommends using the Result pattern, rather than having an exception jump from system to system, which contains the call stack.

Discard RuntimeException or Throwable. Use user-defined exceptions with business significance. Custom exceptions defined in the industry are recommended, for example, DAOException/ServiceException.

In plain English: Do not integrate all exceptions from Runtime exceptions. You want the caller to handle the exceptions with checked exceptions.

Don’t Repeat Yourself, the DRY principle.

Note: Copy and paste code at will, will inevitably lead to code duplication, in the future need to modify, need to modify all copies, easy to miss. Extract common methods, or abstract common classes, or even common modules, if necessary.

Example: If multiple public methods in a class require the same parameter verification operation, extract: private Boolean checkParam(DTO DTO) {… }

Colloquialisms: If you don’t know the DRY principle, but look back and you’ve written code like this, congratulations, you’re a good programmer, and sorry for you.

Concurrent processing

Fetching a singleton must be thread-safe, and the methods must be thread-safe.

Note: Resource-driven classes, utility classes, and singleton factory classes all need attention.

Vernacular: if the singleton implemented lazily requires concurrency control; If the new singleton is itself thread-safe when initialized, the method fetching the instance does not need to be synchronized.

[Mandatory] Specify a meaningful thread name when creating a thread or thread pool to facilitate backtracking in case of errors.

Is:

public class TimerTaskThread extends Thread { public TimerTaskThread() { super.setName(“TimerTaskThread”); . }}

In plain English: When writing code, think about what information you will use to find bugs, and decide how to name them, print logs, and so on.

[Mandatory] Thread resources must be provided through a thread pool. Explicit creation of threads in an application is not allowed.

Note: The benefit of using thread pools is to reduce the time spent creating and destroying threads and the overhead of system resources, solving the problem of insufficient resources. If you don’t use thread pools, you can run out of memory or “overswitch” by creating a large number of similar threads.

One is that caching threads using thread pools is more efficient, and the other is that thread pools help us manage threads, providing elegant shutdowns, interrupt threads waiting for I/OS, saturation policies, and so on.

【 Mandatory 】 Thread pools cannot be created by Executors. Use ThreadPoolExecutor to clear the running rules of the thread pool and avoid resource depletion.

* If the thread pool object returns by Executors, it has the following disadvantages:

FixedThreadPool and SingleThreadPool: The allowed request queue length is integer. MAX_VALUE, which may accumulate a large number of requests and result in OOM.

CachedThreadPool and ScheduledThreadPool: The number of threads allowed to be created is integer. MAX_VALUE, which may create a large number of threads, resulting in OOM.

If there is no limit on the number of threads in a thread pool, it will generate oom: unalbe to create native threads when the thread pool is opened due to insufficient memory or the system configuration exceeds the maximum number of threads.

The core parameters of a component should be passed in explicitly, not by default, just like when you give a task to a subordinate, the goal, principle, time point, boundary of the task should be clear, not fuzzy processing, so as to avoid bicker.

[Mandatory] SimpleDateFormat is a thread-unsafe class. Do not define it as static. If you define it as static, you must lock it or use the DateUtils utility class.

Example: For thread safety, use DateUtils. The following treatment is also recommended:

private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() { 
    @Override
    protected DateFormat initialValue() {
        return new SimpleDateFormat("yyyy-MM-dd"); }};Copy the code

If you are using JDK8, you can use Instant instead of Date, LocalDateTime instead of Calendar, DateTimeFormatter instead of Simpledateformatter. Simple Beautiful Strong immutable thread-safe.

In plain English: Remember, I’m not going to share SimpleDateFormat with a class.

In high concurrency, synchronous calls should consider the performance cost of locking. If you can use lock-free data structures, don’t use locks; If you can lock blocks, don’t lock the whole method body. If you can use object locks, don’t use class locks.

Vernacular: priority no lock, no lock can solve must not use the lock, that is, the use of lock also to control the granularity, the finer the better.

[Mandatory] When multiple resources, database tables, and objects are locked at the same time, ensure that the lock sequence is consistent; otherwise, a deadlock may occur.

Note: Thread 1 must lock tables A, B, and C in sequence before updating. Thread 2 must lock tables A, B, and C in sequence; otherwise, deadlock may occur.

Vernacular:

Deadlocks can be resolved by sequentially locking resources, timeout, priority, deadlock detection, and so on.

See the philosopher’s dining problem for more insight on concurrency.

[Mandatory] When the same record is concurrently modified, the update is not lost and a lock is required. Either the application layer locks, the cache locks, or the database layer optimistic locks, using Version as the basis for updates.

Note: If the probability of each access conflict is less than 20%, optimistic lock is recommended; otherwise, pessimistic lock is recommended. The number of optimistic lock retries must be at least three.

In plain English: state flow, maintain available balance and so on, it is best to directly use the database row-level lock, do not need explicit lock.

[Mandatory] When multiple threads process timed tasks in parallel, when a Timer runs multiple TimerTasks, other tasks will automatically terminate as long as one of them does not catch the exception thrown. ScheduledExecutorService does not have this problem.

In vernacular: the thread body, the top level of the task, and so on must grab the Throwable and process it accordingly, otherwise the thread will terminate.

The countDown method must be called before each thread exits. The thread execution code will notice the catch exception to ensure that the countDown method can execute and avoid the main thread being unable to execute to the await method. The result is not returned until timeout.

Note: The child thread throws an exception stack that cannot be caught in the main try-catch thread.

Please try… A finally statement executes the countDown method, similar to closing a resource.

[Recommendation] Avoid Random instances being used by multiple threads. Although sharing the Random instance is thread-safe, it will degrade performance due to competing for the same seed.

Note: Random instances include instances of java.util.random or math.random ().

Example: After JDK7, you can use API ThreadLocalRandom directly. Before JDK7, you can do one instance per thread.

In plain English: You can put Random in a ThreadLocal and use it only in the local thread.

[Recommendation] In concurrent scenarios, double-checked locking is used to realize optimization problems of delayed initialization (see The “double-checked locking is Broken” Declaration). One of the simpler solutions recommended (for JDK5 and above) is to declare the target attribute as volatile.

Example:

class Foo {
    private Helper helper = null; 
    public Helper getHelper() {
        if (helper == null) 
            synchronized(this) { 
                if (helper == null)
                    helper = new Helper();
            }
            return helper; 
    }
    // other functions and members...
}
Copy the code

There has been a lot of discussion about double checking on the web, but it is a responsibility to tell you that as long as you are not particularly old JDK versions (under 1.4), double checking is ok.

Volatile Solves the problem of multithreaded memory not being visible. Multiple reads on one write can solve variable synchronization problems, but multiple writes cannot solve thread safety problems. For count++, use the following class: AtomicInteger count = new AtomicInteger(); count.addAndGet(1); If it is JDK8, the LongAdder object is recommended for better performance than AtomicLong (reducing the number of optimistic lock retries).

Volatile has only memory visibility semantics, synchronized has mutually exclusive semantics. Volatile is used for write read, synchronized is used for write read, and synchronized is used for fetch-mod-get.

[Reference] When the capacity of HashMap is insufficient for resize, dead chain may occur due to high concurrency, which may lead to CPU surge. Pay attention to avoid this risk in the development process.

Vernacular:

  1. When developing the program, estimate the amount of usage and set the initial value based on the amount of usage.
  2. Resize requires reconstructing the hash table, which severely affects performance and can cause a long tail of response time.

ThreadLocal does not solve the problem of updating shared objects. Static is recommended for ThreadLocal objects. This variable is common to all operations within a thread, so it is set to static. All instances of this class share this static variable, which means that the class is loaded when it is first used, only a chunk of storage is allocated, and all objects of this class (if defined within this thread) can manipulate this variable.

Vernacular:

  1. ThreadLocal is essentially a Map of variables from thread ids. Each time a ThreadLocal variable is fetched, the current thread ID is fetched, and the associated variable is fetched using the current thread ID.
  2. ThreadLocal uses WeakHashMap, so when the key is reclaimed, the value is also reclaimed, without worrying about memory leaks.

The log specification

[Mandatory] Applications must rely on the API of SLF4J rather than the API of logging system (Log4j and Logback). Using the facade logging framework helps maintain and unify the log processing modes of each class.

java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger logger = LoggerFactory.getLogger(Abc.class);
Copy the code

Vernacular:

  1. Slf4jAPI is more refreshing and refreshing.
  2. Not only is the code clear by using placeholders, but methods such as toString on objects are also called according to the log level.

[Mandatory] It is recommended that log files be saved for at least 15 days, because some exceptions occur in “weekly” intervals.

Vernacular:

  1. In fact, it needs to be longer, some online accident recovery cycle is longer, need longer log saving.
  2. It is not the responsibility of development to build big data logging systems such as ELK, etc.

[Mandatory] Extension logs (such as log management, temporary monitoring, and access logs) are named appname_logtype_logname.log.

LogType: indicates the logType. The recommended types are stats, desc, monitor, and visit.

LogName: log description.

The advantage of this naming is that the file name allows you to know which application, type, and purpose the log file belongs to, and also facilitates categorization and lookup.

For example, mPPServer monitors a time zone conversion exception, for example, mppServer_Monitor_timezoneconvert.log

Note: You are advised to classify logs and store error logs and service logs separately for developers to view and monitor the system in a timely manner.

Vernacular:

Logical separation is better for log management.

In terms of performance, if the mechanical disk is single-file, sequential disk write can be used to improve performance to a certain extent.

[Mandatory] Conditional output or placeholders must be used to output trace, debug, or INFO logs.

Logger. debug(“Processing trade with ID: “+ ID +” symbol: “+ symbol); If the log level is WARN, the above log will not be printed, but string concatenation will be performed. If symbol is an object, the toString() method will be executed, wasting system resources, and the log will not be printed.

(condition)

java
if (logger.isDebugEnabled()) {
logger.debug("Processing trade with id: " + id + " symbol: " + symbol);
}
Copy the code

Example: (placeholder)

logger.debug("Processing trade with id: {} symbol : {} ", id, symbol);
Copy the code

Vernacular: never add strings, always use placeholders.

[Mandatory] Set additivity=false in log4j. XML to avoid repeating log printing and wasting disk space.

Is:

Common terms: Logs require CPU processing, memory for caching, I/O bandwidth for printing, and storage space for storing logs to disks. Therefore, logs must be environmentally friendly.

[Mandatory] The exception information contains two types of information: the scene information and the exception stack information. If no, throw upward through the keyword throws.

Example: Logger. error(toString + “_” + LLDB message (), e);

Colloquial: print log must contain the environment, otherwise find the bug when the log is not on, hard working people will understand what I am saying.

[Recommended] Record logs carefully. Debug logs cannot be generated in the production environment. Selectively output info logs; If warn is used to record service behavior information when the logs are first launched, be careful about the output of logs to avoid overloading server disks, and delete these logs in time.

Note: A large number of invalid logs are generated, which is not conducive to system performance improvement or fault location. When journaling, think: Is anyone really reading these journals? What can you do with this log? Does it benefit troubleshooting?

In plain English: I often tell my friends that when writing code, we should think about how to find bugs and what logs are needed. Printing logs only needs to print the core content. Do not serialize the object JSON and print it out casually.

The WARN log level can be used to record user input parameter errors to avoid user complaints. Pay attention to the log output level. The error level records only important errors such as system logic errors and exceptions. Do not type the error level in this scenario unless necessary.

In plain English: Make proper use of WARN level logs, error level logs are most important, and ideally the error and WARN logs generated in production development should be combed regularly.

Security code

[Mandatory] Permission control verification must be performed on pages or functions belonging to users.

Note: Prevent to do not do horizontal permission check can access, modify, delete other people’s data, such as viewing other people’s private message content, modify other people’s orders.

Vernacular:

  1. All user-facing services must have permission verification.
  2. Back-end services without permission verification, but also call permission management under the servitization platform.

[Mandatory] It is forbidden to display sensitive data directly, and desensitization of displayed data is required.

Note: The personal mobile phone number will be displayed as 158****9119. Hide the middle four digits to prevent privacy leakage.

Vernacular:

  1. There will be more sensitive information in finance than just phone numbers.
  2. Anti-leak must be encrypted, anti-tamper must be signed, and anti-repudiation must be asymmetric signed.

[Mandatory] The SQL parameters entered by users must be bound with parameter or METADATA field values to prevent SQL injection and prevent string concatenation SQL from accessing the database.

Vernacular:

  1. This is usually checked by code checking tools.
  2. Developers should never do string concatenation of SQL.

[Mandatory] Any parameter passed in the user request must be validated.

Description:

Ignoring parameter verification may result in:

  1. The page size is too large, causing memory overflow.

  2. Malicious order BY causes slow database query.

  3. Arbitrary redirection.

  4. SQL injection.

  5. Deserialize injection.

  6. The regex input source string denies service ReDoS.

Note: Java code uses re to validate client input. Some re writing methods validate normal user input with no problem, but if an attacker uses a specially constructed string to validate, it may result in an endless loop.

Vernacular:

  1. In general, special characters are filtered at the framework layer, including greater-than (), less-than (), and single quotes.
  2. Any time you use a set, any time you use a set as an input parameter, any time you return a set, you have to have a limit of numbers, not infinitely large.

[Mandatory] Prohibit the output of unfiltered or improperly escaped user data to HTML pages.

Vernacular:

  1. Special characters are blocked at the entry point of the system, which could be a Web interface or a development interface.
  2. Special characters are also blocked at the exit of the system, which generally refers to the Web interface.

[Mandatory] CSRF security filtering must be performed for forms and AJAX submissions.

CSRF(Cross-site Request Forgery) is a common programming vulnerability. For the application/website with CSRF vulnerability, the attacker can construct the URL in advance. As long as the victim user visits, the background will modify the user parameters in the database without the user’s knowledge.

Block the entrance to the system!

[Mandatory] When using platform resources, such as SMS, email, phone, order and payment, correct anti-replay restrictions must be implemented, such as quantity limit, fatigue control and verification code verification, to avoid excessive brushing and loss.

Note: If the verification code is sent to the mobile phone during registration, if there is no limit on the number and frequency, then this function can be used to harass other users, and cause a waste of SMS platform resources.

Vernacular: For user input, be sure to do defensive programming.

[Recommendation] Risk control policies must be implemented in the scenario of Posting, commenting, and sending user generated content, such as brush prevention and filtering of prohibited words in text content.

In plain English: This is generally the big data department to provide decision-making data, each business side buried point.

OOP code

Avoid using a class’s object reference to access static variables or methods of that class, which unnecessarily increases compiler resolution costs.

Vernacular: also not intuitive, see call code can not see is static method, easy to misunderstand.

All Override methods must be annotated with @override.

Counterexample: the getObject() and get0bject() problem. One is the letter O, the other is the number 0, plus @override can accurately determine whether the Override is successful. In addition, if you change a method signature in an abstract class, the implementation class will compile an error immediately.

Java is not like C++, which is the parent class of the declaration of virtual function subclass before overwriting, Java is any method can overwrite, may not overwrite, so the compiler does not check overwriting, unless a method in the interface is not implemented at all will compile errors.

[Mandatory] Java variable parameters can be used only when the parameter types and service meanings are the same, instead of Object.

Note: Variable arguments must be placed at the end of the argument list. (Students are encouraged not to use variable parameter programming.)

Public User getUsers(String type, Integer… ids)

In plain English: not very useful, you can use overloaded methods or array arguments instead.

It is generally used in the API definition of logs to pass variable log parameters.

[Mandatory] It is not allowed to modify the method signature of the interface that is being called externally or the interface that the library depends on to avoid impact on the interface caller. Obsolete interfaces must be annotated with @deprecated and clearly state what the new interface or service is being adopted.

Vernacular:

  1. The interface design is not fully considered, and needs to be modified by adding new interfaces and migrating the old ones.
  2. REST interfaces can only add parameters, not subtract them, and the content of the returned value is also added.

[Mandatory] Do not use obsolete classes or methods.

Java.net.URLDecoder method decode(String encodeStr) this method is outdated, should use a double parameter decode(String source, String encode). An interface provider is obliged to provide a new interface if it is clearly an outdated interface. It is incumbent on the caller to verify what the new implementation of the obsolete method is.

In plain English: defined responsibilities and obligations, the interface provider also has the obligation to promote the interface user to migrate as soon as possible and not to accumulate technical liabilities.

【 mandatory 】Object’s equals method is prone to null-pointer exceptions. Call equals using constants or objects that are determined to have values.

Is: “test”. The equals (object);

Example: the object. The equals (” test “);

Java.util. Objects#equals (a utility class introduced in JDK7)

In vernacular: constant over variable, the principle that never changes.

【 Force 】 Compare the values of all wrapper objects of the same type using equals.

Note: For Integer var =? If the value is between -128 and 127, the Integer object is generated in integercache. cache and will reuse the existing object. The Integer value in this interval can be determined directly by using ==. This is a pit, and it is recommended to use the equals method.

Equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals

The criteria for using basic data types and wrapper data types are as follows:

All POJO class attributes must use wrapper data types.

The return values and parameters of RPC methods must use wrapper data types.

【 Recommended 】 All local variables use primitive data types.

Note: The absence of initial values for POJO class attributes reminds users that they must explicitly assign values when they need to use them. Any NPE problems, or entry checks, are guaranteed by the user.

Example: The query result of the database may be null because of automatic unpacking and NPE risk of receiving with basic data type.

Counterexample: for example, the rise and fall of total transaction volume is displayed, that is, plus or minus X %. X is the basic data type, and the RPC service is called. When the call is unsuccessful, the default value is returned, and the page shows :0%, which is unreasonable and should be displayed as a dash -. So the null value of the wrapper data type can indicate additional information, such as: remote call failure, abnormal exit.

In plain English: Wrapper datatypes add a null state to carry more semantics than primitive datatypes.

[Mandatory] DO not set any attribute defaults when defining POJO classes such as DO, DTO, and VO.

Counterexample: The POJO class gmtCreate defaults to new Date(); However, this property does not place a specific value in the data extraction and is updated with other fields, causing the creation time to be changed to the current time.

In plain English: Although the counterexample here is not easy to follow, remember that the persistent domain object is assigned the gmtCreate and gmtModify fields uniformly by the application layer.

[Mandatory] Do not modify the serialVersionUID field when serializing new attributes of the class to avoid anti-sequence failure; Change the serialVersionUID value if the upgrade is completely incompatible to avoid deserialization clutter.

Note: Note that inconsistent serialVersionUID throws a serialization runtime exception.

In plain English: Don’t use the JDK’s own serialization unless you absolutely have to.

[Mandatory] Constructor does not include any business logic, if there is initialization logic, please put it in init method.

In plain English: One way to do this is to standardize, code is clear, and methods and statements on the exception stack are easier to identify.

POJO classes must write toString methods. If you inherit another POJO class using the IDE’s middle tool :source> generate toString, note that super.tostring is added in front of it.

Note: When a method executes an exception, you can directly call the toString() method of the POJO to print its attribute value, which is convenient for troubleshooting.

Sometimes toString calls the instance variable toString, and the instance variable is null for some reason, causing the NPE to terminate without handling it properly.

“Recommended” String index access using the split method to get the array, to do the last check whether content after the delimiter, otherwise there will be a risk of IndexOutOfBoundsException.

Description:

String str = "a,b,c,,";			
String[] ary = str.split(","); // Expect more than 3, result is 3 system.out.println (ary.length);Copy the code

Vernacular:

  1. Programming should be careful, any uncertain place to judge and deal with, otherwise it is difficult to climb out of the pit.
  2. The idea of Java programming nullifying to implement is on every developer’s mind.

When a class has multiple constructors, or methods with the same name, these methods should be placed together in order for easy reading.

Vernacular: this specification say of zha with my habit one identical!

The order in which methods are defined is public or protected > private > getter/setter.

Description: Public methods are the most concerned methods of class callers and maintainers, the best first screen display; The protection method, though only a subclass concern, may also be the core method in the “template design pattern”; The outside of a private method is usually a black-box implementation that doesn’t need special attention; Because method information is of low value, getters/setters for all services and DAOs are placed at the bottom of the class body.

Vernacular: I recommend putting a logical set of common methods, protected methods, private methods together, and all getters/setters at the end. It feels more logical!

In setter methods, the parameter name is the same as the class member variable name, this. Member name = parameter name. Do not add business logic to getter/setter methods, which makes troubleshooting more difficult.

Example:

public Integer getData() { 
    if (true) {
        return data + 100; 
    } else {
        returndata - 100; }}Copy the code

Vernacular: Agree with both hands.

[Recommendation] String concatenation in the loop body, which is extended by using the Append method of StringBuilder.

Example:

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

Note: The decomcompiled bytecode file shows that each loop generates a StringBuilder object, then append it, and finally returns a String object through toString, resulting in a waste of memory.

In plain English: Always use StringBuilder, not StringBuffer, which is thread-safe and too heavy. I never understood why the Java compiler didn’t make an optimization.

【 recommendation 】 It is more suggestive to declare as final in the following cases:

Variables that do not require reassignment, including class attributes and local variables.

Object arguments are preceded by final to indicate that reference pointing is not allowed to change.

Class methods are definitely not allowed to be overridden.

In plain English: Use the final keyword as much as possible to ensure that the compiler’s verification mechanism works, and also embodies the idea of “programming by contract”.

[Recommendation] Carefully copy objects using the Clone method of objects.

Note: The clone method of the object is a shallow copy by default. If you want to achieve a deep copy, you need to rewrite the Clone method to achieve the copy of the property object.

In plain English: It is best to use constructors to reconstruct objects. With Clone shallow copies, object references can be complex, unintuitive, and hard to understand.

【 Recommended 】 Strict access control of class members and methods:

The constructor must be private if the object is not allowed to be created directly from the outside via new.

Utility classes are not allowed to have public or default constructors.

Class member variables that are non-static and shared with subclasses must be protected.

Class member variables that are non-static and used only in this class must be private.

Class static member variables must be private if they are used only in this class.

If a member variable is static, it must be considered final.

Class member methods are called only from within the class and must be private.

Class member methods are only exposed to inherited classes, so limit them to protected.

Description: Any class, method, parameter, variable, strictly control access scope. Too wide access range is not conducive to module decoupling.

Consider: if it is a private method, delete it if you want, but if it is a public Service method, or a public member variable, delete it without sweating your palms. Variables are like their own children, as far as possible in their own visual line, variable scope is too large, if unlimited running around, then you will worry.

Colloquial: Nothing to say, two words, high cohesion, low coupling, functional module closure, oh, three words.

Set processing

[Mandatory] Handle hashCode and equals according to the following rules:

Whenever you override equals, you have to override hashCode.

Because a Set stores non-repeating objects based on hashCode and equals, objects stored in a Set must override both methods.

If a custom object is used as a Map key, you must override hashCode and equals.

Note: String overrides the hashCode and equals methods, so we can happily use String objects as keys.

In English: Hash is an eternal topic, take a look at Times33 and The Murmurhash algorithm.

[Mandatory] The subList result of ArrayList cannot be forcibly converted to ArrayList, otherwise ClassCastException will be thrown. Exception: Java. Util. RandomAccessSubList always be cast to Java. Util. The ArrayList.

SubList returns the inner subList class of ArrayList. SubList is not an ArrayList, but a view of ArrayList. All operations on subList sublists are reflected in the original list.

In English: this kind of problem can be tested, but development should never rely on the idea of testing, everything is on your own, of course our testers are very reliable.

In mandatory 】 【 subList scenario, highly pay attention to the modification of the original collection element number, can lead to traverse the child list, add, delete, all produce ConcurrentModificationException anomalies.

If you must change the sublist, reconstruct a new ArrayList using public ArrayList(Collection
c).

ToArray (T[] array); list.size(); list.size();

Note: If the array space allocated by the toArray parameter method is not large enough, the toArray method internally reallocates the memory space and returns the new array address. If the array element is larger than needed, the array element subscript [list.size()] is set to NULL, and the rest of the array elements are left unchanged, so it is best to define the method as the group size and the number of elements in the collection.

Is:

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

Counterexample: There is a problem with using the toArray method without arguments. This method can only return the Object[] class, and a ClassCastException will occur if you force an array of another type.

In plain English: I don’t understand why the Java compiler does not optimize, people with logic can deduce, the program must be automatically implemented.

“Forced” to use tools Arrays. AsList () converts an array into a collection, you can’t use the modified method of collection of related party, it’s the add/remove/clear method will throw an UnsupportedOperationException anomalies.

The return object of asList is an inner array class that doesn’t implement collection modification methods. Arrays.aslist is an adaptor pattern, just a conversion interface, and the data behind it is still an array.

String[] str = new String[] { "a"."b" };
List list = Arrays.asList(str);
Copy the code

List.add (“c”); Runtime exception.

STR [0] = “gujin”; So list.get(0) will change as well.

If you need to make changes to the List returned by asList, you can construct a new ArrayList using public ArrayList(Collection
c) constructor.

The generic wildcard < extends T> receives returned data. The generic collection cannot use the add method, and the < super T> cannot use the GET method.

PECS(Producer Extends Consumer Super) PECS(Producer Extends Consumer Super) principles: 1) An upper Extends applies to users who read content frequently. 2) Often inserted, suitable for the lower Super.

Vernacular:

, which must be T or a subclass of T.

Collection write (Add) : There is no way to write because it is not certain that the collection is instantiated with T or a subclass of T. For example, a List <? Extends Number> foo = new ArrayList<Number/Integer/Double>(), you cannot add Number because it can also be an Integer or Double List, In the same way you can’t add an Integer or a Double, which is extends T, you can’t add. Set read (GET) : Only data of type T can be read. < super T>, which must be T or a parent of T. Collection write (add) : You can add T or a subclass of T. Collection read (GET) : There is no way to use get because it is not certain what type is being read from a collection (possibly T or a superclass of T, or Object). For example, a List <? super Integer> foo3 = new ArrayList<Integer/Number/Object>(); You can only guarantee that get is Object.

Here is an example, test1 and test2 both have errors at compile time.

package com.robert.javaspec;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by WangMeng on 2017-04-13.
 * FIX ME
 */
public class Main {
    public static void main(String[] args) {

    }

    public void test1(){
        List<? extends A> childofa=new LinkedList<>();
        B b=new B();
        A a=new A();
        childofa.add(a);
        childofa.add(b);
        A ta= childofa.get(0);
    }

    public void test2(){
        List<? super B> superOfb = new LinkedList<>();
        B b = new B();
        A a = new A();
        superOfb.add(a);
        superOfb.add(b);
        A ta = superOfb.get(0);
        B tb = superOfb.get(0);
    }
}

class A {
    @Override
    public String toString() {
        return "A";
    }
}

class B extends A {

    @Override
    public String toString() {
        return "B"; }}Copy the code

Do not remove/add elements in a foreach loop. The remove element must be Iterator. If the operation is performed concurrently, the Iterator must be locked.

Example:

List<String> a = new ArrayList<String>(); 
a.add("1");
a.add("2");
for (String temp : a) {
    if ("1".equals(temp)) { a.remove(temp); }}Copy the code

Note: the results of the above code will certainly be unexpected, so try to change the “1” to “2”, will be the same result?

Is:

Iterator<String> it = a.iterator(); 
while (it.hasNext()) {
    String temp = it.next(); 
    ifRemove () {it.remove(); }}Copy the code

Vernacular: Always use Iterator for modifications.

The case into 2, throw ConcurrentModificationException, because 2 is the end of the array boundaries.

[Mandatory] For JDK7 and later, the following three conditions must be met by the Comparator; otherwise, Arrays. Sort, collections. sort will report IllegalArgumentException.

Description:

The comparison of x and y is the opposite of the comparison of y and x.

X >y, y>z, x>z.

If x=y, the comparison between x and z is the same as the comparison between y and z.

Counterexample: In the following example, equality is not handled. Exceptions may occur in actual use:

new Comparator<Student>() {
    @Override
    public int compare(Student o1, Student o2) {
        returno1.getId() > o2.getId() ? 1:1; }}Copy the code

In plain English: All of these conditions can be met unless logic is confused.

[Recommendation] During collection initialization, specify the initial value of the collection as much as possible.

ArrayList is initialized as far as possible using ArrayList(int initialCapacity).

Vernacular:

  1. Predicting the size of an array can improve the efficiency of your program. Write code with running in mind.
  2. To learn about performance and capacity evaluation, please refer to the methodology and typical cases of Internet performance and capacity evaluation.

[Recommended] Use entrySet to traverse the Map class KV instead of keySet.

The keySet is iterated twice, once to an Iterator and once to retrieve the value of the key from the hashMap. EntrySet is more efficient by simply iterating once and putting both keys and values into the entry. For JDK8, use the map.foreach method.

Example: Values () returns a set of V values, which is a list object; KeySet () returns a Set of K values, which is a Set object; EntrySet () returns a collection of combinations of k-V values.

In plain English: Writing code is the process of executing code in the programmer’s head, and the intuition is that doing it twice is not as fast as doing it once.

[Recommended] Pay close attention to whether the Map class K/V can store null values as shown in the following table:

Collection classes Key Value Super instructions
Hashtable Null is not allowed Null is not allowed Dictionary Thread safety
ConcurrentHashMap Null is not allowed Null is not allowed AbstractMap Section lock technique
TreeMap Null is not allowed Allow null AbstractMap Thread insecurity
HashMap Allow null Allow null AbstractMap Thread insecurity

Counterexample: ConcurrentHashMap can be used to insert null values due to interference with HashMap. Note that storing null values raises NPE exceptions.

In plain English: There are few scenarios for storing null values. In order to prevent cache penetration, null keys are sometimes cached.

Make good use of the sort and order of the set to avoid the negative effects of unsort and unorder.

Explanation: Orderliness means that the results of traversal are arranged in order according to some comparison rules. Stability means that the order of elements in each iteration of the set is constant. Such as: the ArrayList is the order/unsort; A HashMap is unorder/unsort; TreeSet is order/sort.

In plain English: For a HashMap that is theoretically unordered, I did an experiment where the output was stable every time.

Values:

HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    
map.put(3, 3);
map.put(1, 1);
map.put(2, 2);
map.put(4, 4);

for (Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey());
}
Copy the code

As it turns out, each output is also 1, 2, 3, 4, orderly and stable.

String values:

HashMap<String, String> map = new HashMap<String, String>();
    
map.put("3000"."3");
map.put("1000"."1");
map.put("2000"."2");
map.put("4000"."4");

for (Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey());
}
Copy the code

As it turns out, each output is also 4000, 1000, 2000, 3000, disorderly but stable.

Consult ali experts, here HashMap instability means that the output order will change after rehash.

Using the unique feature of the Set element, a Set can be quickly de-duplicated, avoiding the use of List contains method for traversal, comparison, and de-duplicated operations.

Vernacular: If precise de-weighting is not required, refer to Bloom Filter.

Control statements

【 Force 】 Within a switch block, each case is either terminated by a break/return, etc., or a comment indicating which case the program continues to execute. A switch block must contain a default statement at the end, even if it has no code at all.

In vernacular: it is best to end each case with a break, do not combine several branches into a logic, too unintuitive.

Braces must be used in if/else/for/while/do statements, even if there is only one line of code. Avoid using the following form :if (condition) statements;

Vernacular: this has ambiguity, I think sometimes a line of sentences can not be added.

【 recommendation 】 Use as little else as possible, if-else;

if (condition) { ...
    returnobj; } // go aheadelseBusiness logic code;Copy the code

Note: If you must use if()… Else if ()… The else… [Mandatory] Do not exceed 3 layers, please use state design mode.

Positive example: If-else code that logically has more than 3 layers can be implemented using guard statements, or state patterns.

Vernacular:

  1. My friend said that the design mode of more than three layers of consideration is not completely correct. It can probably be understood that multi-level logical nesting is not a good code style, and it needs to use corresponding reconstruction methods to make optimization, and each bad taste has corresponding optimization methods and steps, as well as advantages and disadvantages constraints.
  2. The main logic is put in the main method, this is the red flower, the sub-logic is encapsulated into small method calls, this is the green leaf, do not write different levels of logic in a large method body, it is difficult to understand, just like the green leaf blocked the red flower, who can see. For example:
public void handleProcess() {// Skeleton logic validate();doProcess();
    declareResource();
}
Copy the code

Generalize, the following similar parallelism of the code is wei statement, used to write this every day but also really just know this is called wei statement 🙂

public double getPayAmount() {  
   if (isDead()) return deadPayAmount();  
   if (isSeparated()) return separatedPayAmount();  
   if (isRetired()) return retiredPayAmount();  
   return normalPayAmount();  
     
}
Copy the code

Not recommended:

public double getPayAmount() {  
   if (isDead()) 
       return deadPayAmount();  
   else if (isSeparated()) 
       return separatedPayAmount();  
   else if (isRetired())
       return retiredPayAmount();  
   else 
       return normalPayAmount();  
}
Copy the code

[Recommendation] Do not execute complex statements in conditional judgment except for common methods (such as getXxx/isXxx). Assign the result of complex logical judgment to a meaningful Boolean variable name to improve readability.

Note: The logic in many if statements is quite complex, and the reader needs to analyze the final result of the conditional expression to determine what kind of statement to execute. So, what if the reader analyzes the logical expression error?

Is:

Boolean existed = (file.open(fileName,"w")! = null) && (...) | | (...). ;if(existed) { ... } counterexamples:if ((file.open(fileName, "w")! = null) && (...) | | (...). ) {... }Copy the code

Vernacular: Isn’t it true that this counterexample is so common that the person who wrote the code doesn’t think it’s ugly?

[Recommendation] The following operations should be moved to the outside of the loop, such as defining objects, variables, obtaining database connections, and performing unnecessary try-catch operations (whether the try-catch can be moved outside the loop).

In plain English: Remember, the circulatory body should try not to acquire resources and handle exceptions.

[Recommendation] Interface input parameter protection. In this scenario, interfaces are commonly used for batch operations.

Vernacular: in vernacular, is to control the number of batch parameters, not too much at a time, otherwise memory overflow.

[Reference] Scenarios for parameter verification in the method:

  1. Methods that are called infrequently.

  2. If the execution time is very expensive, the parameter verification time can be almost ignored, but if the intermediate execution falls back because of the parameter error, or the error, the loss is not worth the gain.

  3. Methods that require extremely high stability and availability.

  4. Open interfaces provided externally, whether RPC/API/HTTP interfaces.

  5. Sensitive access.

In plain English: Within this framework, it is possible to adjust accordingly to the business.

[Reference] Scenarios without parameter verification in the method:

  1. Validation is not recommended for methods that are most likely to be called through a loop. However, external parameter checking requirements must be noted in the method specification.

  2. The frequency of the underlying method calls is relatively high, and generally does not check. After all, as in the final filtration of pure water, parameter errors are unlikely to be exposed at the bottom. Generally, the DAO layer and the Service layer are deployed in the same application and server, so the verification of DAO parameters can be omitted.

  3. Methods that are declared private and will only be called by their own code can be left unchecked if you can be sure that the code passing in the calling method has already checked its arguments or that there is nothing wrong with them.

In plain English: In this box, it is ok to adjust accordingly to the business.

Naming rules

[Mandatory] Names in code cannot start or end with an underscore or a dollar sign.

Example: _name / __name / / Object$

Common variables, class names, and method names must be named in camel shape. It is better not to use underscores or dollar signs, otherwise it looks like scripting language.

[Mandatory] The naming of the code is strictly prohibited to use the mixed way of pinyin and English, let alone the direct use of Chinese.

Explanation: Correct English spelling and grammar make it easy for readers to understand and avoid ambiguity. Note that even pure pinyin naming should be avoided.

Counterexample: DaZhePromotion [discount] / getPingfenByName() [score] / int some variable = 3

Example: International common names such as Alibaba/Taobao/Youku/Hangzhou can be regarded as English.

Have English fast.

In English! English name, western style, generous, lofty…

Class names must be humped in the UpperCamelCase style, except for DO, BO, DTO, VO, etc.

Example :MarcoPolo/UserDO/XmlService/TcpUdpDeal/TaPromotion

Counterexample :macroPolo/UserDo/XMLService/TCPUDPDeal/TAPromotion

Vernacular: Conventional names or abbreviations exception.

[Mandatory] Use the lowerCamelCase style for method names, parameter names, member variables, and local variables.

Example: localValue/getHttpMessage()/inputUserId

Vernacular: A common name or abbreviation exception.

ID is short for both ID and ID.

[Mandatory] Constant names are all capitalized, words are separated by underscores, and semantic expression is complete and clear, not too long name.

Is exemple: MAX_STOCK_COUNT

Example: MAX_COUNT

Vernacular: must be all uppercase, except alphanumeric underscore only, and cannot be used at the beginning and end.

【 Mandatory 】 Abstract class names begin with Abstract or Base. Exception class names end with Exception; A Test class name starts with the name of the class it is testing and ends with Test.

Vernacular: put a bottle of dichlorvos in the home, above do not write label, in case drink big, thirsty, drink, miserable, you understand.

The parentheses are part of the array type, which is defined as follows :String[] args;

Counterexample: use String args[].

Vernacular:

  1. The compiler recognizes this syntax, but we’re writing Java programs, not C/C++ programs.
  2. Blame the Java compiler team for not supporting this syntax in the first place.

[Mandatory] POJO class Boolean variables, do not add is, otherwise part of the framework parsing will cause serialization errors.

Counter example: Define as basic data type Boolean isSuccess; Its method is also isSuccess(). RPC framework “thought” that the corresponding attribute name was SUCCESS during the reverse resolution, so that the attribute could not be obtained and then threw an exception.

Some frameworks use getters and setters to serialize, some according to the property itself value, with is prefix can not find, variable name do not take be verb, syntax error, English makeup test!

[Mandatory] The package name is all lowercase, and there is only one natural semantic English word between the dot delimiters. The package name is singular, but the class name can be plural.

Example: Application utility class package named com.baba.open. Util and class named MessageUtils(refer to Spring framework for this rule)

Vernacular: package name uppercase, with underline, not professional, ugly, not lofty.

[Mandatory] Put an end to completely non-standard abbreviations and avoid looking at the text without knowing the meaning.

Counterexample: AbstractClass “abbreviated” to AbsClass; Condition is “abbreviated” to condi, and such arbitrary abbreviations seriously reduce the legibility of the code.

The variable name will not exist after compiler compilation and optimization. It will compile to the address relative to the bp pointer address of the method stack. The long variable name will not take up more space.

There is a convention for abbreviations in English, which is to remove the vowel and leave the consonant.

【 Recommendation 】 If design patterns are used, it is recommended to show the specific pattern in the class name.

Note: The design pattern is reflected in the name, which is helpful for readers to quickly understand the architectural design ideas.

Is:

public class OrderFactory;

public class LoginProxy;

public class ResourceObserver;
Copy the code

In plain English: Let the world know that you can design patterns. This is a society that values showing off.

Do not add any modifiers to the methods and properties of the interface class (public also), keep the code concise, and add valid Javadoc comments. Try not to define variables in the interface; if you do define variables, they must be related to interface methods and are the base constants for the entire application.

Interface method signature :void f(); Interface base constants :String COMPANY = “wisky”;

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

In JDK8, interfaces are allowed to have default implementations, so this default method is a tacit implementation that is valuable to all implementation classes.

Vernacular: took off pants fart always have a little trouble.

There are two sets of rules for naming interfaces and implementation classes:

[Mandatory] For Service and DAO classes, based on SOA philosophy, the exposed Service must be an interface, and the internal implementation class is distinguished from the interface by the Impl suffix.

Example: CacheServiceImpl Implements the CacheService interface.

[Recommended] If the interface name describes the capability, use the corresponding adjective as the interface name (usually in the form of – able).

Example: AbstractTranslator implements Translatable.

Vernacular: I strongly agree! But think Observer and Observable, and I’ll stop talking.

Enum class names are suffixed with Enum characters. Enumerator names must be in all uppercase letters and separated by underscores (_).

Note: Enumerations are simply special constant classes, and the constructor is forced to be private by default.

Example: Enumeration name :DealStatusEnum, member name: SUCCESS/UNKOWN_REASON.

Colloquialism: No humps! Remember enumerations don’t hump! There are always a lot of people using humps.

[Reference] Naming conventions for each layer:

  1. Service/DAO layer method naming convention:

  2. Methods that get individual objects are prefixed with get.

  3. Methods that get multiple objects are prefixed with list.

  4. Methods that get statistics are prefixed with count.

  5. Insert methods are prefixed with save(recommended) or INSERT.

  6. Delete methods are prefixed with remove(recommended) or delete.

  7. The modified methods are prefixed with update.

Naming conventions for domain models:

  1. Data object :xxxDO, XXX is the name of the data table.

  2. Data transfer object :xxxDTO, XXX indicates the name related to the service domain.

  3. Display object :xxxVO, XXX is usually the name of the web page.

  4. POJO is a general name of DO, DTO, BO, and VO. DO not name it xxxPOJO.

Vernacular: It’s important that everyone agrees.

Constants defined

[Force] No mana values (i.e. undefined constants) are allowed to appear directly in code.

Example: String key = “Id#taobao_”+tradeId; cache.put(key, value);

Vernacular: this needless to say, spit everywhere and everywhere size is not should, Singapore is to whip!

[Mandatory] When assigning the initial value of long or long, use uppercase L instead of lowercase L, which may be confused with 1.

Long a = 2l; Is it a number 21, or a Long 2?

Look at base58 used in blockchain, instead of Base64, second understand what is from the user’s point of view of product design!

[Recommendation] Do not use a constant class to maintain all constants, should be classified according to the constant function, separate maintenance. For example, cache-related constants are placed under class CacheConsts. System configuration-related constants are placed under class ConfigConsts.

Note: large and complete constant class, must use the search function to locate the modified constant, is not conducive to understanding and maintenance.

The standard is that a small module is copied out and can be used directly, rather than missing this and that. Many times, readers copy a set of classes and find that they can not be used when running, missing constants. When copying constant classes, they find that there are many irrelevant constants in the constant class, but also have to clean up.

There are five levels of constant reuse:

  1. Constants are shared across applications, within applications, within subprojects, within packages, and within classes.

  2. Shared constants across applications: Placed in a binary library, usually under the constant directory in client.jar.

  3. In-app shared constants: placed in the constant directory of modules in one library.

Counterexample: Understandable variables should also be defined as in-app shared constants. The two siege masters define “yes” variables 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 true, returns false, causing online problems.

Subprojects share constant internally: that is, in the constant directory of the current subproject.

Intra-package shared constants: that is, in a separate constant directory under the current package.

Intra-class shared constants: Private static final is defined directly within a class.

Vernacular: one party library, 2 square library, tripartite library, calling is very professional, put in from oneself recent above a level can.

【 Recommended 】 Use an Enum class if the value of a variable varies only within a range. If you have extended attributes other than the name, you must use the Enum class, and the number in the example below is the extended information, representing the day of the week.

Public Enum {MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6), SUNDAY(7); }

In plain English: Scenarios where enumeration values need to define extended properties are usually to persist a database or display on an interface.

Format specification

[Mandatory] Conventions for using braces. If the braces are empty, write it succinctly as {} without a line break. If it is a non-empty code block:

  1. No line breaks before open braces.

  2. Newline after opening brace.

  3. Newline before closing brace.

  4. If you have something else after the close curly bracket, you don’t wrap it; Indicates that a line break must be followed by terminating the closing brace.

Vernacular: good style, hate that kind of left curly braces before the line, can not bear.

[Mandatory] No space between the opening parenthesis and the following character. Similarly, there is no empty space between the closing parenthesis and the preceding character. See article 5 below the example tips.

In Eclipse, the shortcut key is Shift + Alt + F. I have a habit when writing a program. Every time I write a piece of code, I will press CTRL + Alt + O, CTRL + Alt + F, CTRL + S.

[Mandatory] Reserved words such as if/for/while/switch/do must have Spaces between the left and right parentheses.

In Eclipse, the shortcut key is Shift + Alt + F. I have a habit when I write a program. Every time I thank a piece of code, I will press CTRL + Alt + O, CTRL + Alt + F, CTRL + S.

[Mandatory] Any operator must have a space around it.

Operators include assignment operator =, logical operator &&, addition, subtraction, multiplication and division symbols, ternary operators, etc.

In Eclipse, the shortcut key is Shift + Alt + F. I have a habit when I write a program. Every time I thank a piece of code, I will press CTRL + Alt + O, CTRL + Alt + F, CTRL + S.

[Mandatory] The indent contains four Spaces and cannot use TAB characters.

Note: If you use TAB indentation, you must set one TAB to four Spaces. IDEA When TAB is set to 4 Spaces, do not select Use TAB character. In Eclipse, you must check insert Spaces for tabs.

Examples: (Involving 1-5 points)

Public static void main(String[] args) {// Indent 4 Spaces String say ="hello"; // There must be a space around the operator int flag = 0; / / keywordsifThere must be a space between the parentheses and the f parentheses, the 0 parentheses and the close parentheses do not need a spaceif(flag == 0) { System.out.println(say); } // Open curly brace preceded by space without newline; Newline after opening braceif (flag == 1) {
        System.out.println("world"); // Wrap a line before and after the closing braceelse, do not use newline}else { System.out.println("ok"); // To end directly after a close brace, you must break a line}}Copy the code

Vernacular: so see used to, how see how clear.

[Mandatory] The maximum number of characters in a single line is 120. If the number exceeds 120, line breaks are required.

  1. The second line is indented 4 Spaces from the first line, starting with the third line and not further indented. See examples.

  2. The operator is wrapped with the following.

  3. The dot symbol of the method call is wrapped with the following.

  4. After multiple arguments are too long, make a line break after commas.

  5. Do not break a line before parentheses, see counterexample.

Is:

StringBuffer sb = new StringBuffer(); // For more than 120 characters, wrap with 4 Spaces, and wrap with the dot symbol before the method sb. Append ("zi").append("xin")...
      .append("huang")...
      .append("huang")...
      .append("huang");
Copy the code

Example:

StringBuffer sb = new StringBuffer(); // Do not wrap sb. Append () before parentheses for more than 120 characters"zi").append("xin")... append ("huang"); Method (args1, args2, args3,... , argsX);Copy the code

Vernacular: a line of code as far as possible do not write too long, long open not to get.

When method parameters are defined and passed in, multiple parameter commas must be followed by Spaces.

Example: In the following example, the argument “a” must be followed by a space.

method(“a”, “b”, “c”);

Vernacular: do not add space too crowded, like the person did not grow like.

【 mandatory 】IDE text file encoding is set to UTF-8; Newlines for files in IDE use Unix format, not Windows format.

In plain English: please do not use the GB character set, there are always problems with changing the environment, Java programs mostly run on Linux, of course use Unix newline.

It is not necessary to add more than one space to align the characters on a line with the corresponding characters on the previous line.

Is:

int a = 3;		
long b = 4L;		
float c = 5F;		
StringBuffer sb = new StringBuffer();
Copy the code

Note: if you need to align a, b, and C with sb, you will need to add several Spaces to each of them.

Vernacular: no need, no need, that would not look good.

Insert a blank line between execution statements, variable definition statements, different business logic, or different semantics in the method body. No blank lines need to be inserted between the same business logic and semantics.

Note: There is no need to insert multiple lines of space for separation.

Vernacular: as same as my habit, a logical empty line. — — — — — — — —

Ramble about the latter

Length is a little long, we can see there is true love around, don’t waste I arrange for such a long time, this is now I set by the company within the Java specification, although it is just a specification manuals, but also dry, full hope that we can progress together ~ everybody if agree, give me some a bai thank ~ ~ thank you

There is a problem? You can leave me a message or a private message

Have a harvest? Just give it a thumbs up

Of course, you can also go to my official account “6 Xi Xuan”,

Reply to “Learn” and you will receive a video tutorial for Advanced Architects for Java Engineers

Reply to “Interview” and you will receive a set of “Java Interview questions I have painstakingly compiled” (part of the table below)

Because, I trained programmers, PHP, Android and hardware are done, but in the end or choose to focus on Java, so have what questions to ask the public for discussion (emotional pouring technology can ha ha ha), see words will reply as soon as possible, hope can with everyone common learning progress, on the server architecture, Java core knowledge analysis, career, interview summary and other articles will be pushed irregularly output, welcome to pay attention to ~~~