Clean Code 讀書筆記九

來源:互聯網
上載者:User

標籤: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();    }}
  • 用命名常量代替魔法數字
    不多說,代碼中出現某個數字,如21,你知道什麼意思嗎?
    這樣 CommonConstants.AVERAGE_AGE=21,使用更好。

  • 不要再判斷中寫一堆&& ||的判斷
    看看下邊那個更易於理解

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代替

  • Don’t Inherit Constants
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 讀書筆記九

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.