Java开发规范
1.代码中不允许定义未使用的变量、方法参数、私有方法、字段和多余的括号
2.包命名不允许大写
反例:
cn.com.test.Controller
正例:
cn.com.test.controller
3.java类命名使用驼峰命名法(首字母大写)
反例:
public class String_Utils {
}
public class numberUtils {
}
正例:
public class StringUtils {
}
public class NumberUtils {
}
4.类中的成员变量不允许使用与类名相同的名称
反例:
public class BookInfo {
private String bookInfo;
}
正例:
public class BookInfo {
private String bookInfoPro;
}
5.if语句、for语句严格遵循Java语法
反例:
if (condition)
logger.info("");
for (;;)
logger.info("");
正例:
if (condition) {
logger.info("");
}
for (;;) {
logger.info("");
}
6.【生产环境】代码中不允许出现System.out.println()
反例:
System.out.println("test...........");
正例:
logger.info("test.........");
7.迭代entrySet()获取Map的key和value
反例:
HashMap<String, String> map = new HashMap<>();
for (String key : map.keySet()){
String value = map.get(key);
//todo
}
正例:
HashMap<String, String> map = new HashMap<>();
for (Map.Entry<String, String> entry : map.entryMap()){
String key = entry.getKey();
String value = entry.getValue();
//todo
}
8.比较两个字符串是否是相等
反例:
// 直接比较两个字符
if ("string1" == "string2") {
//todo
}
// 传入某个参数与特定字符串比较
String param = "";
if (param.equals("string")) {
//todo
}
正例:
// 直接比较两个字符串
if ("string1".equals("string2")){
//todo
}
// 传入某个参数与特定字符串比较
String param = "";
if ("string".equals(param)) {
//todo
}
9.使用Collection.isEmpty()检测空
反例:
LinkedList<Object> collection = new LinkedList<>();
if (collection.size() == 0){
//todo
}
正例:
LinkedList<Object> collection = new LinkedList<>();
if (collection.isEmpty()){
//todo
}
// 检测是否为null,可以使用CollectionUtils.isEmpty()
if (CollectionUtils.isEmpty(collection)) {
//todo
}
10.初始化集合时尽量指定其大小
反例:
// 初始化list,往list中添加元素
int[] array = new int[]{1,2,3,4};
List<Integer> arrayList = new ArrayList<>();
for (int i : array) {
arrayList.add(i);
}
正例:
// 初始化list,往list中添加元素
int[] array = new int[]{1,2,3,4};
List<Integer> arrayList = new ArrayList<>(array.length);
for (int i : array) {
arrayList.add(i);
}
11.在循环中使用StringBuilder、StringBuffer拼接字符串
反例:
String str = "";
for (int i = 0; i < 10; i++){
str += 1;
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 10; i++) {
builder.append(i + ",");
}
正例:
String str1 = "Hello";
String str2 = "World";
String strConcat = str1 + str2;
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 10; i++) {
builder.append(i);
}
12.若需要频繁调用Collection.contains()方法,则使用Set
反例:
List<Object> list = new ArrayList<>();
for (int i = 0; i < Integer.MAX_VALUE; i++) {
if (list.contains(i)) { // 时间复杂度为O(n)
//todo
}
}
正例:
Set<Object> set = new HashSet<>();
for (int i = 0; i < Integer.MAX_VALUE; i++) {
if (set.contains(i)) { // 时间复杂度为O(1)
//todo
}
}
13.使用静态代码块实现静态成员变量赋值
反例:
private static Map<String, Integer> map = new HashMap<>(){
{
map.put("Leo", 1);
map.put("Address", 2);
}
};
private static List<String> list = new ArrayList<>(){
{
list.add("hello");
list.add("world");
//todo
}
};
正例:
private static Map<String, Integer> map = new HashMap<>();
private static List<String> list = new ArrayList<>();
static{
map.put("Leo", 1);
map.put("Address", 2);
list.add("hello");
list.add("world");
}
14.工具类中屏蔽构造函数
反例:
public class PasswordUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(PasswordUtils.class);
public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
public static String encryptPassword(String password) throws IOException {
return new PasswordUtils(password).encrypt();
}
}
正例:
public class PasswordUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(PasswordUtils.class);
public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
private PasswordUtils(){
}
public static String encryptPassword(String password) throws IOException {
return new PasswordUtils(password).encrypt();
}
}
15.删除多余的异常捕获并抛出
反例:
private static String fileReader(String fileName) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
StringBuilder builder = new StringBuilder();
while((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (Exception e) {
throw e;// 仅仅是重复抛出异常 未做任何处理
}
}
正例:
private static String fileReader(String fileName) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
StringBuilder builder = new StringBuilder();
while((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
}
16.字符串转化使用String.valueOf(value)代替 “” + value
反例:
int num = 520;
String result = "" + num;
正例:
int num = 520;
String result = String.valueOf(num);
17.避免使用BigDecimal(double),存在丢失精度
反例:
BigDecimal bigDecimal = new BigDecimal(0.11);
正例:
BigDecimal bigDecimal = BigDecimal.valueOf(0.11);
18.返回空数组和集合而非null
反例:
public static Result[] getResult() {
return null;
}
public static List<Result> getResultList() {
return null;
}
public static Map<String, Result> getResultMap() {
return null;
}
正例:
public static Result[] getResult() {
return new Result[0];
}
public static List<Result> getResultList() {
return Collections.emptyList();
}
public static Map<String, Result> getResultMap() {
return Collections.emptyMap();
}
19.优先使用常量或者确定值调用equals()方法
反例:
private static boolean fileReader(String fileName) throws IOException {
return fileName.equals("chart");
}
正例:
private static boolean fileReader(String fileName) throws IOException {
return "chart".equals(fileName);// 或者使用 Object.equals("chart", "fileName");
}
20.枚举的属性字段必须是私有且不可变
反例:
public enum SwitchStatus {
// 枚举的属性字段反例
DISABLED(0, "禁用"),
ENABLED(1, "启用");
public int value;
private String description;
private SwitchStatus(int value, String description) {
this.value = value;
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
正例:
public enum SwitchStatus {
// 枚举的属性字段正例
DISABLED(0, "禁用"),
ENABLED(1, "启用");
// final 修饰
private final int value;
private final String description;
private SwitchStatus(int value, String description) {
this.value = value;
this.description = description;
}
// 没有Setter 方法
public int getValue() {
return value;
}
public String getDescription() {
return description;
}
}
21.mybatis不要为了多个查询条件而写 1 = 1,update操作也一样,可以用<set>
标记代替 1 = 1
反例:
<select id="queryBookInfo" parameterType="cn.com.mochasoft.entity.BookInfo" resultType="java.lang.Integer">
select count(*) from t_rule_BookInfo t where 1=1
<if test="title !=null and title !='' ">
AND title = #{title}
</if>
<if test="author !=null and author !='' ">
AND author = #{author}
</if>
</select>
正例:
<select id="queryBookInfo" parameterType="cn.com.mochasoft.entity.BookInfo" resultType="java.lang.Integer">
select count(*) from t_rule_BookInfo t
<where>
<if test="title !=null and title !='' ">
AND title = #{title}
</if>
<if test="author !=null and author !='' ">
AND author = #{author}
</if>
</where>
</select>
22.抽象类命名
反例:
public abstract class ElasticsearchCustom {
//todo
}
正例:
public abstract class AbstractElasticsearchCustom {
//todo
}