1、【建議】: 不要在常量和變量中出現易混淆的字母
- 基本規範:包名全小寫,類名首字母全大寫,常量全部大寫並用下劃線分隔,變量採用駝峯命名法(Camel Case)命名等。
- 爲了讓程序更容易理解,字母“l”(還包括大寫字母“O”)儘量不要和數字混用,以免使閱讀者的理解與程序意圖產生偏差。如果字母和數字必須混合使用,字母“l”務必大寫,字母“O”則增加註釋。
- 字母“l”作爲長整型標誌時務必大寫。
2、【建議】: 莫讓常量蛻變成變量
- 常量就是常量,在編譯期就必須確定其值,不應該在運行期更改,否則程序的可讀性會非常差
- 變化是指每次運行都會變化。常量就應該是確定的值,不是運行時才確定。除非有特別的需求。
package com.hao.test;
import lombok.extern.slf4j.Slf4j;
import java.util.Random;
/**
* @author haoxiansheng
*/
@Slf4j
public class Client {
public static void main(String[] args) {
log.info("Const1=>{}",Const.RAND_CONST);
log.info("Const1=>{}",Const1.RAND_CONST);
log.info("Const1=>{}",Const.RAND_CONST);
log.info("Const1=>{}",Const1.RAND_CONST);
}
}
interface Const {
// 是否爲常量
public static final int RAND_CONST = new Random().nextInt();
}
class Const1{
// 是否爲常量
public static final int RAND_CONST = new Random().nextInt();
}
3、【建議】: 三元操作符的類型務必一致
- 代碼案例
package com.hao.test;
import lombok.extern.slf4j.Slf4j;
/**
* @author haoxiansheng
*/
@Slf4j
public class Test1 {
public static void main(String[] args) {
int a = 80;
String s1 = String.valueOf(a < 100? 90 : 100);
String s2 = String.valueOf(a < 100? 90 : 100.0);
log.info("si==s2?=>{}",s1.equals(s2));
log.info("s1=>{}, s2=>{}", s1, s2);
}
}
2)三元操作符類型的轉換規則
a:若兩個操作數不可轉換,則不做轉換,返回值爲Object類型。
b:若兩個操作數是明確類型的表達式(比如變量),則按照正常的二進制數字來轉換,int類型轉換爲long類型,long類型轉換爲float類型等。
c:若兩個操作數中有一個是數字S,另外一個是表達式,且其類型標示爲T,那麼,若數字S在T的範圍內,則轉換爲T類型;若S超出了T類型的範圍,則T轉換爲S類型
d:若兩個操作數都是直接量數字,則返回值類型爲範圍較大者。
- 保證三元操作符中的兩個操作數類型一致,即可減少可能錯誤的發生。
4、【建議】: 避免帶有變長參數的方法重載
- 代碼案例
package com.hao.test;
import lombok.extern.slf4j.Slf4j;
import java.text.NumberFormat;
/**
* @author haoxiansheng
*/
@Slf4j
public class Test2 {
public static void main(String[] args) {
Test2 client = new Test2();
client.calPrice(49900, 75);
}
// 複雜多折扣計算
public void calPrice(int price, int... discounts) {
float knockdownPrice = price;
for (int discount : discounts) {
knockdownPrice = knockdownPrice * discount / 100.0F;
}
log.info("複雜多折扣後的價格折扣=>{}", formateCurrency(knockdownPrice));
}
// 簡單折扣計算
public void calPrice(int price, int discount) {
float knockdownPrice = price * discount / 100.0F;
log.info("簡單折扣後的價格折扣=>{}", formateCurrency(knockdownPrice));
}
// 格式化成本的貨幣形式
private String formateCurrency(float price) {
return NumberFormat.getCurrencyInstance().format(price / 100);
}
}
- 慎重考慮變長參數的方法重載
5、【建議】:別讓null值和空值威脅到變長方法
- 代碼編譯錯誤,重載導致
package com.hao.test;
/**
* @author haoxiansheng
*/
public class Test3 {
public static void main(String[] args) {
Test3 client = new Test3();
// 錯誤
client.methodA("hello", null);
client.methodA("hell0");
// 正確
String[] strings = null;
client.methodA("hello", strings);
}
public void methodA(String str, Integer...integers) {
}
public void methodA(String str, String...strings){
}
}