8 common non-standard Java code and 8 java specifications
At work, I recently cleaned up an existing Java project code. After that, I found some repeated nonstandard code. So I organized them into a list and shared them with my peers, hoping to attract attention and improve the quality and maintainability of the Code.
This list is not ordered, and all comes from some code quality check tools, such as CheckStyle, FindBugs, and PMD.
Format source code in Eclipse and manage import statements
Eclipse provides the ability to automatically format source code and manage import statements (and Remove unused statements ). You can use the following shortcut keys to use these functions.
Ctrl + Shift + F-Format the source code.
Ctrl + Shift + O-Manage import statements and Remove unused statements.
In addition to manually executing these two functions, you can also enable Eclipse to automatically format the source code and manage the import statements when saving files. In Eclipse, go to Window-> Preferences-> Java-> Editor-> Save Actions and enable Perform the selected actions on save, and select Format source code and organize imports.
Avoid Multiple return statements (exit points) in the method ):
In your method, make sure there is only one exit point. Do not use more than one return statement in a method.
For example, the following code is not recommended because it has multiple exit points (return statements ).
Simplify the if-else method:
We wrote some tool methods that only require one parameter, checked some conditions, and returned a value according to the conditions. For example, see the iseligble method www.twitterchina.net above.
Do not create a new instance for Boolean, Integer, or String:
Avoid creating new instances such as Boolean, Integer, and String. Use Boolean. valueOf (true) instead of new Boolean (true ). The two methods have similar effects but can improve the performance.
Use braces around the code block:
Never forget to use braces around block-type statements (such as if, for, and while. This reduces code ambiguity and avoids new bugs when you modify code blocks.
Not recommended
Declare the method parameters as final type:
The parameter of the method is always declared as final in all compatible places. In this way, when you accidentally modify the parameter value, the compilation will receive a warning and the byte code generated by compilation will be optimized.
Recommendation
Name the public static final member variable in uppercase:
Public static final type variables are always named in uppercase. This makes it easy to distinguish between constants and local variables.
Not recommended
Merge multiple if statements into one:
The following code
Do not forget to add the default statement to the switch:
Always add a default statement to the switch.
To avoid repeated use of the same string, create a constant:
If you need to use the same string in multiple places, create a String constant.
The following code: