1. 多走半里路
很多事情并不難,只是缺乏多走半里路的習(xí)慣!
反例
public boolean isInValid(String str) {
if (str == null || str.trim().length() == 0) {
return true;
}
return false;
}
多走一步,海闊天空
public boolean isInValid(String str) {
return (str == null) || (str.trim().length() == 0);
}
是個(gè)程序員都知道哪個(gè)更好!
還有一種見過很多次的代碼:
public boolean isEmptyName() {
return StringUtils.isEmpty(name)? true: false;
}
難道不感覺到多余嗎?
再走半步,山清水秀
public boolean isEmptyName() {
return StringUtils.isEmpty(name);
}
2. 空對(duì)象
NullPointException,讓我們防不勝防;尤其是使用第三方API,如果拋出這個(gè)異常,會(huì)讓人有罵街的沖動(dòng)。所以:若不想踩坑,請(qǐng)先別給別人挖坑。
理想要求:我們生產(chǎn)的所有public帶返回值的方法體中,不應(yīng)該出現(xiàn)“return null”字樣??諏?duì)象就是這一思想的落地實(shí)現(xiàn)。
案例:查詢并返回一個(gè)名字為steven的老師或者學(xué)生。

public static SearchFilter name(String name) {
return human -> human.getName().equalsIgnoreCase(name);
}
public Human find(SearchFilter filter) {
for (Human human : humans) {
if (filter.isMatched(human)) {
return human;
}
}
return new NullHuman(); //如果你返回NULL,總有一天你會(huì)挨罵!
}
//Test
assertFalse(edu.find(name("steven")).isNull());
3. 單實(shí)例情結(jié)
談起設(shè)計(jì)模式,很多人會(huì)覺得高大上,于是當(dāng)學(xué)會(huì)了其中一個(gè)時(shí),便會(huì)不加節(jié)制的使用。
單例,GOF中最簡(jiǎn)單的一個(gè)設(shè)計(jì)模式,很好用、也非常方便,但說實(shí)話很多人在濫用。我們的系統(tǒng)中隨處可見,但用前請(qǐng)叩問自己該類真的是在系統(tǒng)當(dāng)中有并且只能有一個(gè)實(shí)例嗎?
否則請(qǐng)拒絕單實(shí)例。太多的單實(shí)例會(huì)給你的自動(dòng)化測(cè)試帶來無窮的煩惱。
4. 充分使用枚舉
枚舉有一些比較強(qiáng)大的特性容易被忽視,比如枚舉對(duì)象本身也可以攜帶變量;這一特性讓枚舉在更多的場(chǎng)合發(fā)揮不可替代的功用。
舉例:不同武器具有不同的殺傷力,殺傷力變量可以攜帶到武器的枚舉值中。
public enum EquipmentEnum {
Staff(20), Hammer(10);
double playerRisedAbility;
EquipmentEnum(double playerRiseAbility) {
this.playerRisedAbility = playerRiseAbility;
}
public double getRaiseAbility(double originalAbility) {
return Double.sum(originalAbility, playerRisedAbility);
}
}
5. 提高注釋質(zhì)量
30%的代碼注釋比的時(shí)代已經(jīng)成為過去,最好的注釋的就是無需注釋,程序員應(yīng)該致力于通過命名讓注釋消失。
大量的實(shí)踐證明,隨著重構(gòu)頻率越來越高,重構(gòu)過程中隨著代碼的變更同步更新注釋的可能性幾乎為零。久而久之,注釋與代碼就是南轅北轍。
6. 面向客戶的命名
好的命名能夠愉悅讀者的心情,讓人有想一睹作者真面目的沖動(dòng)!
案例:
一個(gè)房地產(chǎn)開發(fā)商一個(gè)新的樓盤開盤,原價(jià)80萬每套,有如下優(yōu)惠策略,但優(yōu)惠政策可能隨著樓盤存量情況會(huì)不一樣,為開發(fā)商寫一個(gè)房款計(jì)算程序
- 老客戶買二套房可優(yōu)惠4%,可累加
- 一次性全款客戶可優(yōu)惠3%,可累加

public class Customer {
Benefiter benefit = new NullBenefiter();
public void is(Benefiter benefits) { //原本的set方法,重命名會(huì)帶來意想不到的效果。
this.benefit = benefits;
}
public double shouldPay(double srcPrice) {
return srcPrice - benefit.benefit(srcPrice);
}
}
@FunctionalInterface
public interface Benefiter {
abstract double benefit(double srcPrice);
default Benefiter and(final Benefiter otherPolicy) {
return srcPrice -> (benefit(srcPrice) + otherPolicy.benefit(srcPrice));
}
}
受益于良好命名,客戶代碼語義躍然紙上:customer.is(oldCustomer().and(fullPay()));
7. 使用多維數(shù)組
數(shù)組是任何一門相對(duì)高級(jí)的機(jī)器語言的必備數(shù)據(jù)結(jié)構(gòu),但是對(duì)面向?qū)ο箝_發(fā)人員而言,似乎對(duì)它有所忽略。
在一些特定的場(chǎng)景下,它能起到意想不到的效果。
案例:美元、法郎、人民幣三幣種間換算。其中美元:法郎=1:2;美元:人民幣=1:8;
public class ExchangeRate {
public static final int DOLLAR = 0;
public static final int FRANC = 1;
public static final int YMB = 2;
private static final double[][] rates = { //二維數(shù)組定義幣種之間的匯率,簡(jiǎn)單高效
{1.0d, 2.0d, 8.0d},
{0.5d, 1.0d, 4.0d},
{0.125d, 0.25d, 1.0d}
};
public static double getRateOf(Currency src, Currency tgt) {
return rates[src.ID][tgt.ID];
}
}
public class Cash {
private double value;
private Currency unit;
public Cash(double value, Currency unit) {
this.value = value;
this.unit = unit;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Cash) {
Cash other = (Cash) obj;
return value == other.value * getRateOf(other.unit, unit);
}
return false;
}
}
如果匯率的二維數(shù)組使用配置文件定義并初始化,那還可以將設(shè)計(jì)提升一個(gè)新的高度——易于擴(kuò)展,甚至不需修改任何Java代碼即可完成幣種的擴(kuò)展。
8. 規(guī)約函數(shù)入?yún)?/h2>
當(dāng)我們調(diào)用外部API時(shí),最理想的就是零入?yún)?,即便有入?yún)⒁蚕M穷愋兔鞔_且范圍可枚舉的,這樣會(huì)讓我們使用這個(gè)API時(shí)更具安全感!心同此理,當(dāng)你把一個(gè)函數(shù)聲明為public時(shí),請(qǐng)謹(jǐn)慎地定義它的入?yún)ⅰ?/p>
如果把上述案例中獲取兩種幣種之間的匯率函數(shù):
public static double getRateOf(Currency src, Currency tgt) {
return rates[src.ID][tgt.ID];
}
定義為
public static double getRateOf(int src, int tgt) {
return rates[src][tgt];
}
雖然函數(shù)實(shí)現(xiàn)簡(jiǎn)單了一些,但可想而知,這個(gè)API會(huì)讓使用者很忌憚!數(shù)組越界異??隙ㄊ墙?jīng)常發(fā)生。
相反通過枚舉規(guī)約了入?yún)⒌念愋秃头秶?,給用戶一些固定選項(xiàng),使用者少了很多顧慮,而我們的程序也更加安全。
所以:我們對(duì)外提供的API入?yún)㈩愋捅M量少用String、Int這種基本類型,給使用者發(fā)揮的空間越大,犯錯(cuò)的可能越大,因?yàn)槟惆扬L(fēng)險(xiǎn)暴露在不受控的用戶手里。
9. 經(jīng)常進(jìn)行封裝去重
你是否為反復(fù)地編寫類似“if (tasks != null && tasks.size() > 0)”或者“if (name != null && (!name.isEmpty()))”的代碼而心浮氣躁,其實(shí)你完全可以解救自己。
封裝一下
public class CollectionUtil {
public static boolean isEmpty(Collection collection) {
return collection == null || collection.isEmpty();
}
}
以及
public class StringUtil {
public static boolean isEmpty(String context) {
return context == null || context.isEmpty();
}
}
一切變得非常簡(jiǎn)單,心情好了,效率也就高了!
10. 化解if/else的毒素
我們的系統(tǒng)充斥著if/else的邏輯,因?yàn)樗壿嫛昂?jiǎn)單”、易用!但隨著時(shí)間推移、需求的擴(kuò)展,有一天你會(huì)發(fā)現(xiàn)自己都看不懂自己寫的if/else。
所以一開始就要學(xué)會(huì)拒絕這種邏輯的嵌套,又或者是當(dāng)你看嵌套的復(fù)雜邏輯,大膽的對(duì)它進(jìn)行重構(gòu)。
案例:輸入一個(gè)1-1000的數(shù)值N,如果N是3或者3的倍數(shù)時(shí),返回“FIZZ”;如果N是5或者5的倍數(shù)時(shí), 返回“BUZZ”;既是3的倍數(shù)又是5的倍數(shù)時(shí), 返回“FIZZBUZZ”;其他的則輸出N。
原實(shí)現(xiàn):披著對(duì)象外殼的面向過程代碼
public String say(int input) throws Exception {
if ( input < 1 || input > 1000){
throw new Exception("Invalid input");
}
if (input % 15 == 0) {
return "FIZZBUZZ";
}
if (input % 5 == 0) {
return "BUZZ";
}
if (input % 3 == 0) {
return "FIZZ";
}
return String.valueOf(input);
}
嗅一嗅其中的壞味道,如果將來需求擴(kuò)展,比如引進(jìn)7的倍數(shù)。照此邏輯,繼續(xù)添加if,問題是解決了,但總有一天你會(huì)懷疑人生!
改進(jìn)一:引入責(zé)任鏈和模板方法模式

public String say(int input) throws Exception {
if (input < 1 || input > 1000) {
throw new Exception("Invalid input");
}
DefaultParser defaultParser = new DefaultParser(null);
MultiOfThreeParser multiOfThreeParser = new MultiOfThreeParser(defaultParser);
MultiOfFiveParser multiFiveParser = new MultiOfFiveParser(multiOfThreeParser);
MultiOfFifteenParser fifteenPaser = new MultiOfFifteenParser(multiFiveParser);
return fifteenPaser.parse(input);
}
public abstract class Parser {
abstract boolean isFixedResponsibility(int inputContext);
abstract String response(int inputContext) throws Exception;
public String parse(int inputContext) throws Exception {
if (isFixedResponsibility(inputContext)) {
return response(inputContext);
}
if (nextParser != null) {
return nextParser.parse(inputContext);
}
return NULL;
}
}
public class MultiOfFifteenParser extends Parser {
public MultiOfFifteenParser(Parser nextParser) {
super(nextParser);
}
@Override
public String response(int inputContext) throws Exception {
return FLAG_FOR_MULIT_OF_FIFTEEN;
}
@Override
boolean isFixedResponsibility(int inputContext) {
return inputContext % 15 == 0;
}
}
看起來好多了,但感覺好像還有哪兒不太對(duì)勁!
改進(jìn)二:徹底穿上對(duì)象的外袍
敏銳的讀者可能還會(huì)發(fā)現(xiàn)上述改進(jìn)還存在細(xì)微的小問題,那就是say方法里面的異常分支處理。怎么還存在一個(gè)if,對(duì)于一個(gè)完美主義強(qiáng)迫癥患者而言,它的存在就是一個(gè)災(zāi)難。繼續(xù)改進(jìn)一下:

public String say(int input) throws Exception {
DefaultParser defaultParser = new DefaultParser(null);
MultiOfThreeParser multiOfThreeParser = new MultiOfThreeParser(defaultParser);
MultiOfFiveParser multiOfFiveParser = new MultiOfFiveParser(multiOfThreeParser);
MultiOfFifteenParser FifteenPaser = new MultiOfFifteenParser(multiOfFiveParser);
InvalidNumberParser invalidNumberPaser = new InvalidNumberParser(FifteenPaser);
return invalidNumberPaser.parse(input);
}
public class InvalidNumberParser extends Parser {
public InvalidNumberParser(Parser nextParser) {
super(nextParser);
}
@Override
String response(int inputContext) throws Exception {
throw new Exception("Invalid input");
}
@Override
boolean isFixedResponsibility(int inputContext){
return (inputContext < L_THRESHOLD) || (inputContext > H_THRESHOLD);
}
}
OK,Perfect!