Reading "Ali Java Development Manual" summary (2)

Enumeration member name needs to be in all uppercase, with underscores between words separated SUCCESS

1) Data Objects: xxxDO, xxx is the table name.

2) Data Transfer Object: xxxDTO, xxx is the name associated with the business.

3) display objects: xxxVO, xxx generally page name.

 

Capital L Long a = 2L

 

Constant internal sub-project sharing: that in the current sub-project of the constant directory.

Shared encapsulated constants: i.e., a separate directory in the constant current package.

Sharing the constants categories: direct private static final class is defined within the

 

Any two items, ternary operator needs both sides of a space.

 

Do not change a single sentence in a row before commas or parentheses wrap

 

1. Long minimize the use of variable length parameter ... IDS

The method is easy to shorting 2.equals pointer exception, should be used with a constant value or determined to call the object equals.

Determining equivalence between the float 3, the basic data types can not be == comparison, the pack data type can not be judged by equals. The reason is that both the number of 1.0000001 and 1.0 in most cases, they are considered equal

(1) a specified tolerance, the difference of the two floating-point numbers within this range are considered equal. float a = 1.0f - 0.9f; float b = 0.9f - 0.8f; float diff = 1e-6f;

 

    if (Math.abs(a - b) < diff) {

        System.out.println("true");

    }

(1) BigDecimal to define values, then the floating-point arithmetic operation.

    BigDecimal a = new BigDecimal("1.0");

    BigDecimal b = new BigDecimal("0.9");

    BigDecimal c = new BigDecimal("0.8");

 

    BigDecimal x = a.subtract(b);

    BigDecimal y = b.subtract(c);

 

    if (x.equals(y)) {

        System.out.println("true");

    }

 

4. Comparison between all the object values ​​of integral packaging, all using the equals method of comparison (Integer, etc.) reasons:? Assignment for Integer var = -128 to 127 range, Integer object is IntegerCache.cache produced, will reusing existing objects, Integer values ​​within this range may be used directly for determination ==, but all data outside this range, the heap will have, and will not reuse an existing object, which is a pit, recommended use equals method to judge

 

bigint 5. database fields must correspond to the Long type of the properties. (If using integer, id with more and more large, more than it represents the range of Integer overflow become negative.)

 

6. BigDecimal (double) the presence of risk of loss of precision, the exact calculation of the comparison values ​​or the scene may cause the business logic exception.

推荐:BigDecimal recommend1 = new BigDecimal("0.1");

    BigDecimal recommend2 = BigDecimal.valueOf(0.1);

 

7. RPC parameter and return value data type packaging must be used. Recommended] all local variables using the basic data types. Packaging type may be null

 

8. The method of construction was added which prohibits any business logic, if initialization logic, please put the init method

 

9. When the new serialization class property, please do not modify the serialVersionUID field, to avoid de-serialization failure; if not completely compatible upgrade, to avoid confusion deserialization, then modify the serialVersionUID value.

 

10.toString, if inherited another POJO class, pay attention to add about super.toString in front.

 

After an array of split 11.String obtained by the method to be done last delimiter has no content checking, otherwise there will be risk IndexOutOfBoundsException is thrown.

Description:

String str = "a,b,c,,";

String[] ary = str.split(",");

// expect more than 3, 3 result

System.out.println(ary.length);

 

12. The method Object clone caution to copy target.

Note: The default method is to clone the object shallow copy, are to achieve the depth required to traverse a deep copy the copy-implemented method clone override domain objects.

 

13. tools have allowed public or default constructor. Class non-static member variables and shared with subclasses, must be protected.

 

14. As long as override equals, it must override hashCode. Set storage because it is not duplicate objects, determined by their hashCode and equals, so Set stored object must override these two methods. If the custom objects as Map keys, you must override hashCode and equals. Description: String hashCode and equals method has been overwritten, so we can happily use a String object to use as a key

 

15. A method of using a set of arrays turn, must toArray (T [] array) set, is passed exactly the same type, length 0 empty array.

 

16. When using addAll Collection any interface implementation class () method, a set of parameters to be inputted NPE determination.

 

17. generic wildcard <? Extends T> to receive the data back, the wording of this generic collection add method can not be used, and <? Super T> get method can not be used, as the interface call assignment error-prone.

Description: Extension talk about PECS (Producer Extends Consumer Super) principles: first, frequently read out the content, suitable for use <extends T?>. Second, often inserted inside, suitable for use <? Super T>

 

18. In a generic set of non-limiting generic definition of the limits set assignment when using the set of elements, the need for instanceof determines, to avoid a ClassCastException exception.

 

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

 

20. Due to interference HashMap, many people think ConcurrentHashMap can put null value, and in fact, store null throws NPE exception value.

 

21. Please specify a meaningful name when you create a thread pool thread or threads, easy backtracking on error

 

22. The thread pool Executors are not allowed to create, but by ThreadPoolExecutor way, this approach allows the students to write more explicit operating rules thread pool, to avoid the risk of resource depletion.

 

23.5. SimpleDateFormat is not thread-safe class, usually not defined as a static variable, if defined as static, must be locked, or use DateUtils tools. Positive examples: Note thread-safe, use DateUtils. Also we recommend the following process:

private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {     

 @Override        protected DateFormat initialValue() {            return new SimpleDateFormat("yyyy-MM-dd");      

}  

};  

Note: If you are JDK8 applications, can be used instead of Instant Date, LocalDateTime instead of Calendar,

DateTimeFormatter place SimpleDateFormat, official explanation given: simple beautiful strong immutable thread-safe.

 

24. ThreadLocal variable must be recycled custom, especially in the thread pool scene, threads often be reused, if you do not clean up ThreadLocal variable custom, may affect subsequent business logic and cause memory leaks and other problems.

Make use of try-finally block agent recovered. Positive examples:

objectThreadLocal.set(userInfo); try {     // ... } finally {     objectThreadLocal.remove();

}

 

25. The lock can be subject, not as a class lock, so as to lock the block work as small as possible to avoid the RPC method call in the lock block.

 

26. multiple resources, database tables, objects simultaneously locking, locking the need to maintain a consistent order, as this may cause a deadlock. Description: Thread a need for after table A, B, C can be updated in order to lock all operations, then the order of the thread locking two must be A, B, C, or it may deadlock.

 

27. In the embodiment using blocks waiting to acquire the lock must be outside the try block, and there is no call will throw locking manner between the try block, to avoid the locking successful, the finally unable to unlock

 

28 .. volatile memory to solve the multi-threaded invisible problem. For a write once read many, synchronization problems can be solved variables, but if you write, the same can not solve thread safety issues.

 

29.HashMap be resize when capacity is insufficient due to high concurrency dead links may occur, leading to soaring CPU, or other data structures can be used to lock in the development process to avoid this risk.

 

30. ThreadLocal object uses static modification, ThreadLocal can not solve the problem of shared update objects. Description: This variable is for all operations within a thread shared, set to a static variable, all such instances share the static variables, that is to say in class is used to load the first time, allocates only a storage space, all this object class (as long as it is defined within this thread

A) you can manipulate the variables.

 

11. In a concurrent scenario, delay, initiated by the optimized double checks the lock (double-checked locking)

Hidden problem (refer to The "Double-Checked Locking is Broken" Declaration), the recommended solution is more simple in (applies to JDK5 and above), the target property declared as volatile type.

 

 

31. The thread pool Executors are not allowed to create, but by ThreadPoolExecutor way, this

Kind of approach to make students more clearly written operating rules thread pool, to avoid the risk of resource depletion.

Description: Executors malpractice thread pool objects returned as follows:

1) FixedThreadPool 和 SingleThreadPool:

The request queue length allowed Integer.MAX_VALUE, may accumulate a large number of requests, thereby causing OOM.

2) CachedThreadPool:

The number of threads created to allow Integer.MAX_VALUE, may create a large number of threads, resulting OOM.

 

SimpleDateFormat is not thread-safe class, usually not defined as a static variable, if defined as

static, must be locked

Note that thread safety, use DateUtils. Also we recommend the following process:

private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {

@Override

protected DateFormat initialValue() {

return new SimpleDateFormat("yyyy-MM-dd");

}

};

 

If JDK8 applications, can be used instead of Instant Date, LocalDateTime instead of Calendar,

DateTimeFormatter 代替 SimpleDateFormat

 

ThreadLocal variable must be recycled custom, especially in the thread pool scene, threads often be reused,

If you do not clean up ThreadLocal variable custom, it may affect subsequent business logic and cause memory leaks and other problems.

Make use of try-finally block agent recovered.

objectThreadLocal.set(userInfo);

try {

// ...

} finally {

objectThreadLocal.remove();

}

 

Concurrent modify the same record, avoid lost updates, need to lock. Either at the application level locking, either in the cache

Lock, or use optimistic locking at the database level, using the updated version as a basis.

Note: If the collision probability is less than 20% per visit is recommended to use optimistic locking, otherwise use pessimistic locking. The number of retries of not less than optimistic locking

3 times.

 

 

Check the parameters:

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

2. The need for high reliability and availability of the method.

 

Not negated logic 1 condition, i.e.,! condition

 

Note the use of the class, class attributes, class methods / ** * content / format

 

All the abstract methods (including interface methods) must be used Javadoc comments

1. Internal use multi-line comments / * * / comment, and note that the code is aligned.

 

All comments must be enumerated type field, indicating the purpose of each data item

 

Make good use of regular expressions pre-compiled function, improve the matching speed

Pattern to be defined as static final static variables, in order to avoid performing multiple precompiled

In vivo methods can not be defined Pattern pattern = Pattern.compile ( "Rules"); (each need to match the regular time, are required to compile the pattern again, inefficient)

This is not a pre-compiler is not enough: Pattern.matches (regexRule, content)

 

 

If the basic data types are boolean variable (boolean name is no need to add the prefix), it will automatically call isXxx () method.

 

velocity template engine: Background delivered to the variable page must be added $ {var} - in the middle of an exclamation point!.

Note: If var is equal to null, or is not present, then the $ {var} will be displayed directly on the page.

 

Get current milliseconds System.currentTimeMillis () to System.nanoTime nanosecond ()

JDK8, the time for statistical and other scenes, it is recommended to use Instant timestamp class: https: //blog.csdn.net/weixin_42124622/article/details/81944113

 

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

 

For the time being is commented out, the subsequent recovery code snippet may use the code in the comment above, uniform regulations with three slashes (///)

To explain the reasons commented code.

 

NullPointerException do not go to catch, parameter detection

 

Do not try-catch of large sections of the code, can not make the appropriate treatment for different exceptions, is not conducive to localization issues

 

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.

 

There try block into the transaction code, the catch exception, if the need to roll back the transaction, we must pay attention to manually roll back the transaction. (Let thrown)

https://blog.csdn.net/qq_40784783/article/details/88060747

   

After capturing a RuntimeException spring, will carry out the transaction is rolled back.

Therefore, the catch block, add:

} catch (Exception e) {

                e.printStackTrace ();

                map.put("number", 0);

                // set manually roll back the current transaction

                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

                // or manually throw runTimeException

              throw new RuntimeException();

            }

 

Do not use the return in the finally block. Relentless discarded return point try block.

 

The RPC call, when a two-way packet related methods, or dynamically generated class must catch an exception class Throwable intercept, may throw error

 

Optional use JDK8 the class to prevent NPE problem https://www.cnblogs.com/rjzheng/p/9163246.html

When the value is null, of (T value) will report a NullPointerException; ofNullable (T value) does not throw Exception, ofNullable (T value) directly back to a EMPTY object.

I do not want to hide NullPointerException. But to immediately report such cases to use Of function. But have to admit, this scene is really very little

 

Avoid direct throw new RuntimeException (), but not allowed to throw Exception or Throwable, custom business meaning there should be an exception to use. Recommended industry is already defined custom exceptions, such as: DAOException / ServiceException etc.

 

Result using the embodiment, the package isSuccess () method "error code", "short error message."

 

Try to copy and paste the code (extract)

 

Logging system can not be used directly (Log4j, Logback) in the API, but rather rely on the use of logging framework API SLF4J

 

All log files are kept for at least 15 days, because some anomalies with the "week" is characterized by frequency of occurrence. Network health, security-related information, system monitoring, management background operation, the user needs to retain sensitive operations related to the blog of not less than six months.

 

Log (such as RBI, temporary surveillance, access logs, etc.) naming appName_logType_logName.log. logType,: logType, such as the stats / monitor / access the like; logName: log Description

force-web region translation exception when application individually monitored, such as: force_web_timeZoneConvert.log

 

Print Log avoid duplication, waste of disk space, be sure to set additivity = false in log4j.xml in.

 

Exception information should be recorded crime scene information and exception stack information

logger.error (various parameters or the object toString () + "_" + e.getMessage (), e);

 

Production environment disable output debug log; selectively output info log; if used to warn record business behavior when just on the line information, log output must pay attention to and remember to remove them promptly observation logs

 

Warn log level can be used to record the user input parameter errors, to avoid customer complaints, loss. If not necessary, do not play error level in this scenario, to avoid frequent alarms. 

 

For trace / debug / info log output level must be determined log level switch

// If the judgment is true, you can trace and debug output level log

      if (logger.isDebugEnabled()) {            logger.debug("Current ID is: {} and name is: {}", id, getName());     }

 

Unit testing: insert does not comply with the rules of business, resulting in abnormal test results. As usual to

 

Disable the output of user data without security filtering or improperly escaped to the HTML page. (Regardless of the obvious is not displayed)

 

database:

Expression is the concept of whether or not the field name must is_xxx manner, the data type is unsigned tinyint (1 is represented, 0 for No). UNSIGNED attribute is an unsigned type of digital

If any field is non-negative, must be unsigned.

POJO class in any Boolean variables, do not add the prefix is

 

Database names, table names, field names, do not allow any uppercase letters

 

Table name does not use a plural noun

 

Decimal type is decimal, prohibit the use of float and double. there are float and double precision loss problem, if the stored data exceeds the range decimal range, it is recommended to split into integer and fractional data and stored separately, corresponding to the java BigDecimal

 

• Manager Layer: Generic treatment layer, which has the following characteristics:

1) on third-party platforms encapsulation layer, and returns the result pretreatment conversion abnormality information.

2) the ability to sink to General Service layer, such as caching scheme, the middleware general processing.

3) interacts with the DAO layer, a combination of a plurality of multiplexed DAO.

 

1. DAO layer, there are many types of exceptions generated, the abnormality can not be grained into

The catch line, using the catch (Exception e) embodiment, and throw new DAOException (e), the printing log not required because the log necessarily captured and printed Manager / Service layer to the log file, if the same call log server, performance and waste storage. Service layer when an exception occurs, it must record the error logs to disk, tape parameter information as possible, which is equivalent to protect the crime scene. If the Service Manager layer coincides with the deployment of the same plane, with the log mode DAO layer processing, if it is deployed separately, it is consistent with the Service handling. Web layer should not continue throwing up abnormal, if aware of this anomaly will not cause the page to render properly, then they should go directly to the friendly error page

 

To open interface layer code error and exception handling to return an error message mode.

 

• DO (Data Object): This one-object database table structure, upwardly through the transport layer DAO data source object.

• DTO (Data Transfer Object): data transfer object, Service Manager or outward transfer of the object.

• BO (Business Object): business objects, business logic encapsulated by the output layer Service object.

• AO (Application Object): application object, in the abstract object model multiplexing layer between the Web and Service layer, very close to the presentation layer, reusability is not high.

• VO (View Object): Object display layer, typically a Web rendering engine to the transmission layer template object.

• Query: query object data, the upper layers of receiving a query request. Note that more than two parameter query package, prohibit the use of the Map class transmitted.

 

 

utils layer: Tools layer, universal, regardless of the business, may be independent, to use for other projects;

tools layer: For certain operations, only certain commonality between several traffic class;

 

Layer manager: Generic treatment layer, which has the following characteristics, the layer of the third-party platform package, and return the results pre-conversion abnormality information; generic capability to sink Service layer, such as caching scheme, a general purpose processing middleware; and DAO layer interaction, the combination of multiplexing a plurality of DAO.

 

service layer: business process layer, in large systems, the layer is more complex, it can be extracted common treatment layer (manager layer), and a service layer may correspond to a plurality of manager layer, but small systems, it is often not necessary to extract manager layer, a service layer is sufficient.

 

helper layer: auxiliary based layer, typically a number of auxiliary functions, such as operation of a database connection provides SqlHelper package database operation target, ConfigHelper help create configuration information is used to build the initialization module, in fact, acting much like the tools, universal tools but no good .

Guess you like

Origin www.cnblogs.com/shineipangtuo/p/12395588.html