文档介绍:JAVA编码最佳实践指南
版本:
文档审批修订记录
文件状态:
[ ]草稿
[√]正式发布
当前版本:
作者:
审核人:
发布日期:
日期
版本编号
修订号
简要说明
著者
审核者
审核日期
1
说明:“简要说明”主要是对修订原因和修订的内容进行简单说明。
目录
1 JAVA代码相关 1
2 HIBERNATE相关 4
3 SQL/数据库相关 5
Java代码相关
打开文件、流之后应及时关闭,避免过多占用系统IO资源。
避免在for循环中做if判断,便于编译优化。
不要两次初始化变量。
例如:
String a=new String();
String a=();
优化为:
String a=null;
String a=();
使用final static声明log4j对象,减少内存占用。
例如:
public class a {
private Log _logger=();
}
优化为:
public class a {
private final static _logger=();
}
使用StringBuffer拼接字符串。
例如:
String a=”abcdefg”+”hijklmno”+”xyz”;
优化为:
StringBuffer ab=New StringBuffer().append(“abcdefg”).append(“hijklmno”).append(“xyz”);
String a=();
使用预编译语句prepareStatement代替createStatement,并使用占位符生成SQL语句,传递参数。
例如:
String sql=”select * from a where id=’”+id+”’”;
Statement st=(sql);
();
优化为:
String sql=”select * from a where id=?”;
PreparedStatement pstmt=(sql);
(1,id);
(sql);
避免在循环中声明对象、操作数据库、打开文件等。
例如:
for (int i=0;i<n;i++) {
String date=();
String sql=”update a set updateDate=? Where id=?”;
(sql,new Object[]{date,i });
}
优化为:
String date=();
String sql=”update a set updateDate=? Where id in ?”
int[] ids=new int[n];
for (int i=0;i<n;i++) {
ids[i]=I;
}
(sql,new Object[]{date,ids});
尽量避免使用递归调用
合理使用缓存。
异常在需要抛出的地方抛出,try catch能整合就整合
try {
(); // Difficult for javac
} catch( method1Exception e ) { // and the JVM runtime
// Handle exception 1 // to optimize this
} // code
try {
();
} catch( method2Exception e ) {
// Handle exception 2
}
try {
();
} catch( method3Exception e ) {
// Handle exception 3
}
以下代码更容易被编译器优化
try {
(); // Easier to optimize
();
();
} catch( method1Exception e ) {
// Handle exception 1
} catch( method2Except