標籤:code-monster java 方法
要點匯總:一般性問題
方法名稱應該準確表達其具體行為
比如:
Date newDate = date.add(5)//加5天?5個月?
最好使用addDaysTo 或increaseByDays 明確方法的行為。
- 使用多態 代替 switch或if else
比如:
class RequestHandler { public void handleRequest(int action) { switch(action) { case LOGIN: doLogin(); break; case LOGOUT: doLogout(); break; case QUERY: doQuery(); break; } }}
interface Command { public void execute();}class LoginCommand implements Command { public void execute() { // do what doLogin() used to do }}class RequestHandler { private Map<Integer, Command> commandMap; // injected in, or obtained from a factory public void handleRequest(int action) { Command command = commandMap.get(action); command.execute(); }}
if (shouldBeDeleted(timer)) if (timer.hasExpired() && !timer.isRecurrent())
- 避免否定性調節:
肯定性條件比否定性條件更容易理解
比如下邊那一行更易理解呢?
if (buffer.shouldCompact()) if (!buffer.shouldNotCompact())
public void pay() { for (Employee e: employees) { if (e.isPayday()) { Money pay = e.calculatePay(); e.deliverPay(pay); } }}
重構:
public void pay() { for (Employee e: employees) payIfNecessary(e);}private void payIfNecessary(Employee e) { if (e.isPayday()) calculateAndDeliverPay(e);}private void calculateAndDeliverPay(Employee e) { Money pay = e.calculatePay(); e.deliverPay(pay);}
public class MoogDiver { Gradient gradient; List < Spline > splines; public void dive(String reason) { saturateGradient(); reticulateSplines(); diveForMoog(reason); }...}
saturateGradient();reticulateSplines(); diveForMoog(reason);
三者的關係並沒有很好的突出,更好的重構是:
public class MoogDiver { Gradient gradient; List < Spline > splines; public void dive(String reason) { Gradient gradient = saturateGradient(); List < Spline > splines = reticulateSplines(gradient); diveForMoog(splines, reason); }...}
public static fianl int ....
使用enum代替
public class HourlyEmployee extends Employee { private int tenthsWorked; private double hourlyRate; public Money calculatePay() { int overTime = tenthsWorked - straightTime; return new Money( hourlyRate * (tenthsWorked + OVERTIME_RATE * overTime)); }...}
TENTHS_PER_WEEK 、OVERTIME_RATE這兩個常量來自哪裡?
public abstract class Employee implements PayrollConstants { public abstract boolean isPayday(); public abstract Money calculatePay(); public abstract void deliverPay(Money pay);}
public interface PayrollConstants { public static final int TENTHS_PER_WEEK = 400; public static final double OVERTIME_RATE = 1.5;}
這種通過繼承或實現的方式擷取常量,是對常量範圍的忽視,怪異的使用。應該用引入靜態類的方式在代碼中直接使用常量。
import static PayrollConstants.*;
名稱與命名
使用描述性名稱
名稱很重要,一個準確的名稱可以大幅度提高代碼的可讀性。
public int x() { int q = 0; int z = 0; for (int kk = 0; kk < 10; kk++) { if (l[z] == 10) { q += 10 + (l[z + 1] + l[z + 2]); z += 1; } else if (l[z] + l[z + 1] == 10) { q += 10 + l[z + 2]; z += 2; } else { q += l[z] + l[z + 1]; z += 2; } } return q;}
public int score() { int score = 0; int frame = 0; for (int frameNumber = 0; frameNumber < 10; frameNumber++) { if (isStrike(frame)) { score += 10 + nextTwoBallsForStrike(frame); frame += 1; } else if (isSpare(frame)) { score += 10 + nextBallForSpare(frame); frame += 2; } else { score += twoBallsInFrame(frame); frame += 2; } } return score;}
兩段代碼對比一下即可知道名稱的重要。
-
變數的作用範圍越大,越應該重視名稱的重要。
-
不要用名稱掩蓋了內容。
public ObjectOutputStream getOos() throws IOException { if (m_oos == null) { m_oos = new ObjectOutputStream(m_socket.getOutputStream()); } return m_oos;}
更準確的名稱應該是: createOrReturnOos
測試
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Clean Code 讀書筆記九