Home >Java >javaTutorial >java code coding specifications
Standards need to be paid attention to during the daily coding process, and it is a good habit to develop slowly
1. Basic principles
Mandatory principles:
1. StringBuilder must be used for string addition operations;
2.try…catch Usage
try{ }catch{Exception e e.printStackTrace(); }finally{ }//在最外层的Action中可以使用,其它地方一律禁止使用;
try{ //程序代码 }catch(Exception e){ //为空,什么都不写 }//在任何场景中都禁止使用
try{ }catch{Exception e throw new runtimeException(e);//最优先采用的写法 }finally{ }
1. For situations where you don’t know what to do or how to handle it after catching it, don’t catch the exception and leave it to the outgoing layer to catch and handle it;
2. If the return type is a collection, in the method declaration Generics must be used, and the javadoc must indicate under what circumstances null is returned and under what circumstances an empty collection is returned.
3. For methods and variable declaration scopes, the following priorities should be adopted: private, protected, public. For variables, the following priorities should be adopted: local variables, instance variables, and class variables. If instance variables or class variables must be used, Next, to ensure thread safety, try to use ThreadLocal to save instance variables or class variables if possible;
4. If it is not necessary, do not define variables or new objects in the loop; try to use new objects at the last moment when needed;
5. If it is not necessary, do not use try...catch in the loop;
6. For more complex logic in the class, line comments should be used for comments. Block comments are absolutely not allowed in java code (/**/ ) to comment;
7. The first letter of the name of the Java class must be capitalized. It consists of multiple words, and the first letter of each word is capitalized
8. The file name of jsp must be all lowercase;
9. Spring’s bean The configuration file name must be lowercase, in the format of xxx.bean.xml, e0af6e3a30bebe6575f03ea264bbb019方式如
char[] buffer;
而不是
char buffer[];
4.方法编写规范
1.对成员方法,不要轻易的采用public的成员变量。主要的修饰符有public, private, protected, 无
2.空方法中方法声明和函数体可都在一行。如: void func(){}
3.方法和方法之间空一行
4.方法的文档注释放在方法的紧前面,不能空一行。
5.避免过多的参数列表,尽量控制在5个以内,若需要传递多个参数时,当使用一个容纳这些参数的对象进行传递,以提高程序的可读性和可扩展性
6.方法中的循环潜套不能超过2层
7.对于设计期间不需要子类来重载的类,尽量使用final
8.每个方法尽量代码行数尽量不要超过100行(有效代码行,不包括注释),但必须保证逻辑的完整性
9.接口中的方法默认级别为protected,只有很确认其它子系统的包会调用自己子系统的接口中的方法时,才将方法暴露为public.
5.语言使用及书写规范
1.避免变量的定义与上一层作用域的变量同名。
2.方法与方法之间用需要用一空行隔开
3.局部变量在使用时刻声明,局部变量/静态变量在声明时同时初始化
4.在与常数作比较时常数放在比较表达式的前面如:
if(“simpleCase”.equals(obj))… if(null == obj)….
5.return语句中,不要有复杂的运算。
6.switch语句,需要一个缺省的分支