搜尋
首頁Javajava教程了解對象健身操:寫出更簡潔的程式碼

Understanding Object Calisthenics: Writing Cleaner Code

在軟體開發中,堅持乾淨的程式碼實踐對於創建可維護、可擴展和高效的應用程式至關重要。鼓勵這種紀律的一種方法是物件體操,這是一組旨在指導開發人員編寫更好的物件導向程式碼的規則。

在這篇文章中,我將探討物件健身操的原理以及如何應用它們來編寫更清晰、更結構化的程式碼。如果您有興趣深入研究實際程式碼範例或了解如何在實際專案中實現這些原則,請隨時查看我的 GitHub 儲存庫以獲取更多詳細資訊。

有關更多實踐說明,請訪問我的 GitHub 儲存庫。

什麼是物體健美操?

對象健身操是一項程式設計練習,由九個規則組成,鼓勵您遵守物件導向的原則。這些規則本身是由 Jeff Bay 在他的《The ThoughtWorks Anthology》一書中介紹的。目的是透過遵循這些約束來鼓勵更深入地關注程式碼的設計和結構。

以下是 9 條規則:

1. 每個方法只有一層縮排

這個原則規定每個方法應該只有一層縮排。透過保持較低的縮排級別,我們可以提高可讀性並使程式碼更易於維護。如果一個方法有太多級縮排,通常表示內部邏輯太複雜,需要分解成更小的部分。

實作範例
下面是不遵循這個原則的方法範例:

public class OrderService {
    public void processOrder(Order order) {
        if (order.isValid()) {
            if (order.hasStock()) {
                if (order.hasEnoughBalance()) {
                    order.ship();
                } else {
                    System.out.println("Insufficient balance.");
                }
            } else {
                System.out.println("Stock unavailable.");
            }
        } else {
            System.out.println("Invalid order.");
        }
    }
}

上面的程式碼中,processOrder 方法中存在多層縮進,這使得閱讀起來更加困難,尤其是當邏輯變得更加複雜時。

現在,讓我們看看如何透過簡化邏輯來遵循原則:

public class OrderService {
    public void processOrder(Order order) {
        if (!isOrderValid(order)) return;
        if (!hasStock(order)) return;
        if (!hasEnoughBalance(order)) return;

        shipOrder(order);
    }

    private boolean isOrderValid(Order order) {
        if (!order.isValid()) {
            System.out.println("Invalid order.");
            return false;
        }
        return true;
    }

    private boolean hasStock(Order order) {
        if (!order.hasStock()) {
            System.out.println("Stock unavailable.");
            return false;
        }
        return true;
    }

    private boolean hasEnoughBalance(Order order) {
        if (!order.hasEnoughBalance()) {
            System.out.println("Insufficient balance.");
            return false;
        }
        return true;
    }

    private void shipOrder(Order order) {
        order.ship();
    }
}

此版本每個邏輯區塊都有一級縮進,使程式碼更乾淨且更易於維護。

2.不要使用else關鍵字

在物件導向程式設計中,else關鍵字的使用常常會導致程式碼混亂且難以維護。您可以使用提前傳回或多態性來建立程式碼,而不是依賴 else 語句。這種方法增強了可讀性,降低了複雜性,並使您的程式碼更易於維護。

我們先來看一個使用 else 關鍵字的範例:

public class Order {
    public void processOrder(boolean hasStock, boolean isPaid) {
        if (hasStock && isPaid) {
            System.out.println("Order processed.");
        } else {
            System.out.println("Order cannot be processed.");
        }
    }
}

在此範例中,else 語句迫使我們明確處理否定情況,從而增加了額外的複雜性。現在,讓我們重構它以避免使用 else:

public class Order {
    public void processOrder(boolean hasStock, boolean isPaid) {
        if (!hasStock) {
            System.out.println("Order cannot be processed: out of stock.");
            return;
        }

        if (!isPaid) {
            System.out.println("Order cannot be processed: payment pending.");
            return;
        }

        System.out.println("Order processed.");
    }
}

透過消除 else,您可以編寫更有針對性的程式碼,每個部分處理一個職責。這符合“單一職責原則”,有助於創建更乾淨、更易於維護的軟體。

3. 包裹所有原語和字串

物件健身操的關鍵實踐之一是將所有基元和字串包裝在自訂類別中。此規則鼓勵開發人員避免直接在程式碼中使用原始基元類型或字串。相反,他們應該將它們封裝在有意義的物件中。這種方法使程式碼更具表現力、更易於理解,並且可以增加複雜性,但不會變得難以管理。

讓我們考慮一個直接使用原始類型和字串的範例:

public class Order {
    private int quantity;
    private double pricePerUnit;
    private String productName;

    public Order(int quantity, double pricePerUnit, String productName) {
        this.quantity = quantity;
        this.pricePerUnit = pricePerUnit;
        this.productName = productName;
    }

    public double calculateTotal() {
        return quantity * pricePerUnit;
    }
}

這段程式碼直接使用了int、double、String。雖然這看起來很簡單,但它並沒有清楚地表達每個值的意圖,並且使得以後引入特定於這些值的新行為或約束變得更加困難。

現在,讓我們重構這段程式碼來包裝原語和字串:

public class Quantity {
    private final int value;

    public Quantity(int value) {
        if (value 



<p><strong>主要變化:</strong></p>

  • 有意義的類,我們創建了 Quantity、Price 和 ProductName 類,而不是使用原始 int、double 和 String。這為每個值賦予了意義,並允許自訂驗證或其他行為。
  • 增強的驗證,我們添加了驗證以確保數量和價格始終具有有效值,例如非負金額。當基元被包裝在它們自己的類別中時,這更容易管理。
  • 提高了可讀性,程式碼更加不言自明。您不再需要猜測特定的原始值代表什麼。每個值都封裝在一個類別中,該類別清楚地傳達了其含義。

4. 一流藏品

每當您使用 List 或 Map 等集合時,請將其設為專用物件。這可以使您的程式碼保持乾淨,並確保封裝與集合相關的邏輯。

Problem: Using a Raw Collection Directly

public class Order {
    private List<string> items;

    public Order() {
        this.items = new ArrayList();
    }

    public void addItem(String item) {
        items.add(item);
    }

    public List<string> getItems() {
        return items;
    }
}
</string></string>

In this example, Order directly uses a List to manage its items. This design can lead to code that lacks clear meaning and responsibilities. It also allows external classes to manipulate the list freely, leading to potential misuse.

Solution: Using a First-Class Collection

public class Order {
    private Items items;

    public Order() {
        this.items = new Items();
    }

    public void addItem(String item) {
        items.add(item);
    }

    public List<string> getItems() {
        return items.getAll();
    }
}

class Items {
    private List<string> items;

    public Items() {
        this.items = new ArrayList();
    }

    public void add(String item) {
        items.add(item);
    }

    public List<string> getAll() {
        return new ArrayList(items); // Return a copy to prevent external modification
    }

    public int size() {
        return items.size();
    }
}
</string></string></string>

Explanation:

  • First-Class Collection, The Items class is a wrapper around the List. This pattern gives the collection its own class and behavior, making it easier to manage and encapsulate rules. For example, you can easily add validation or methods that operate on the list (e.g., size()).
  • This makes the code more meaningful and prevents misuse of raw collections, as external classes don't have direct access to the list.

Benefits of First-Class Collections:

  • Encapsulation: Collection logic is kept in one place.
  • Maintainability: Any changes to how the collection is handled can be done in the Items class.
  • Readability: Code that deals with collections is clearer and more meaningful.

6. One Dot Per Line

One Dot Per Line is an Object Calisthenics rule that encourages developers to avoid chaining multiple method calls on a single line. The principle focuses on readability, maintainability, and debugging ease by ensuring that each line in the code only contains a single method call (represented by one "dot").

The Problem with Method Chaining (Multiple Dots Per Line)
When multiple methods are chained together on one line, it can become difficult to:

  • Read: The longer the chain of method calls, the harder it is to understand what the code does.
  • Debug: If something breaks, it’s not clear which part of the chain failed.
  • Maintain: Changing a specific operation in a long chain can affect other parts of the code, leading to harder refactoring.

Example: Multiple Dots Per Line (Anti-Pattern)

public class OrderProcessor {
    public void process(Order order) {
        String city = order.getCustomer().getAddress().getCity().toUpperCase();
    }
}

In this example, we have multiple method calls chained together (getCustomer(), getAddress(), getCity(), toUpperCase()). This makes the line of code compact but harder to understand and maintain.

Solution: One Dot Per Line
By breaking down the method chain, we make the code easier to read and debug:

public class OrderProcessor {
    public void process(Order order) {
        Customer customer = order.getCustomer();  // One dot: getCustomer()
        Address address = customer.getAddress();  // One dot: getAddress()
        String city = address.getCity();          // One dot: getCity()
        String upperCaseCity = city.toUpperCase(); // One dot: toUpperCase()
    }
}

This code follows the One Dot Per Line rule by breaking down a method chain into smaller, readable pieces, ensuring that each line performs only one action. This approach increases readability, making it clear what each step does, and improves maintainability by making future changes easier to implement. Moreover, this method helps during debugging, since each operation is isolated and can be checked independently if any errors occur.

In short, the code emphasizes clarity, separation of concerns, and ease of future modifications, which are key benefits of applying Object Calisthenics rules such as One Dot Per Line.

6. Don’t Abbreviate

One of the key rules in Object Calisthenics is Don’t Abbreviate, which emphasizes clarity and maintainability by avoiding cryptic or shortened variable names. When we name variables, methods, or classes, it’s important to use full, descriptive names that accurately convey their purpose.

Example of Bad Practice (With Abbreviations):

public class EmpMgr {
    public void calcSal(Emp emp) {
        double sal = emp.getSal();
        // Salary calculation logic
    }
}
  • EmpMgr is unclear; is it Employee Manager or something else?
  • calcSal is not obvious at a glance—what kind of salary calculation does it perform?
  • emp and sal are vague and can confuse developers reading the code later.

Example of Good Practice (Without Abbreviations):

public class EmployeeManager {
    public void calculateSalary(Employee employee) {
        double salary = employee.getSalary();
        // Salary calculation logic
    }
}
  • EmployeeManager makes it clear that this class is managing employees.
  • calculateSalary is explicit, showing the method’s purpose.
  • employee and salary are self-explanatory and much more readable.

By avoiding abbreviations, we make our code more understandable and maintainable, especially for other developers (or even ourselves) who will work on it in the future.

7. Keep Entities Small

In Object Calisthenics, one of the fundamental rules is Keep Entities Small, which encourages us to break down large classes or methods into smaller, more manageable ones. Each entity (class, method, etc.) should ideally have one responsibility, making it easier to understand, maintain, and extend.

Example of Bad Practice (Large Class with Multiple Responsibilities):

public class Employee {
    private String name;
    private String address;
    private String department;

    public void updateAddress(String newAddress) {
        this.address = newAddress;
    }

    public void promote(String newDepartment) {
        this.department = newDepartment;
    }

    public void generatePaySlip() {
        // Logic for generating a payslip
    }

    public void calculateTaxes() {
        // Logic for calculating taxes
    }
}

In this example, the Employee class is doing too much. It’s handling address updates, promotions, payslip generation, and tax calculation. This makes the class harder to manage and violates the Single Responsibility Principle.

Example of Good Practice (Small Entities with Single Responsibilities):

public class Employee {
    private String name;
    private String address;
    private String department;

    public void updateAddress(String newAddress) {
        this.address = newAddress;
    }

    public void promote(String newDepartment) {
        this.department = newDepartment;
    }
}

public class PaySlipGenerator {
    public void generate(Employee employee) {
        // Logic for generating a payslip for an employee
    }
}

public class TaxCalculator {
    public double calculate(Employee employee) {
        // Logic for calculating taxes for an employee
        return 0.0;
    }
}

By breaking the class into smaller entities, we:

  • Keep the Employee class focused on core employee information.
  • Extract responsibilities like payslip generation and tax calculation into their own classes (PaySlipGenerator and TaxCalculator).

8. No Getters/Setters/Properties

The principle of avoiding getters and setters encourages encapsulation by ensuring that classes manage their own data and behavior. Instead of exposing internal state, we should focus on providing meaningful methods that perform actions relevant to the class's responsibility.

Consider the following example that uses getters and setters:

public class BankAccount {
    private double balance;

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public void deposit(double amount) {
        balance += amount;
    }

    public void withdraw(double amount) {
        if (amount 



<p>In this example, the getBalance method exposes the internal state of the BankAccount class, allowing direct access to the balance variable.</p>

<p>A better approach would be to avoid exposing the balance directly and provide methods that represent the actions that can be performed on the account:<br>
</p>

<pre class="brush:php;toolbar:false">public class BankAccount {
    private double balance;

    public void deposit(double amount) {
        balance += amount;
    }

    public void withdraw(double amount) {
        if (amount 



<p>In this revised example, the BankAccount class no longer has getters or setters. Instead, it provides methods for depositing, withdrawing, and checking if there are sufficient funds. This approach maintains the integrity of the internal state and enforces rules about how the data can be manipulated, promoting better encapsulation and adherence to the single responsibility principle.</p>

<h3>
  
  
  9. Separate UI from Business Logic
</h3>

<p>The principle of separating user interface (UI) code from business logic is essential for creating maintainable and testable applications. By keeping these concerns distinct, we can make changes to the UI without affecting the underlying business rules and vice versa.</p>

<p>Consider the following example where the UI and business logic are intertwined:<br>
</p>

<pre class="brush:php;toolbar:false">public class UserRegistration {
    public void registerUser(String username, String password) {
        // UI Logic: Validation
        if (username.isEmpty() || password.length() 



<p>In this example, the registerUser method contains both UI logic (input validation) and business logic (registration). This makes the method harder to test and maintain.</p>

<p>A better approach is to separate the UI from the business logic, as shown in the following example:<br>
</p>

<pre class="brush:php;toolbar:false">public class UserRegistration {
    public void registerUser(User user) {
        // Business Logic: Registration
        System.out.println("User " + user.getUsername() + " registered successfully.");
    }
}

public class UserRegistrationController {
    private UserRegistration userRegistration;

    public UserRegistrationController(UserRegistration userRegistration) {
        this.userRegistration = userRegistration;
    }

    public void handleRegistration(String username, String password) {
        // UI Logic: Validation
        if (username.isEmpty() || password.length() 



<p>In this improved design, the UserRegistration class contains only the business logic for registering a user. The UserRegistrationController is responsible for handling UI logic, such as input validation and user interaction. This separation makes it easier to test and maintain the business logic without being affected by changes in the UI.</p>

<p>By adhering to this principle, we enhance the maintainability and testability of our applications, making them easier to adapt to future requirements.</p>

<h3>
  
  
  Conclusion
</h3>

<p>Object Calisthenics might seem a bit strict at first, but give it a try! It's all about writing cleaner, more maintainable code that feels good to work with. So, why not challenge yourself? Start small, and before you know it, you’ll be crafting code that not only works but also shines. Happy coding!</p>


          

            
        

以上是了解對象健身操:寫出更簡潔的程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何將Maven或Gradle用於高級Java項目管理,構建自動化和依賴性解決方案?如何將Maven或Gradle用於高級Java項目管理,構建自動化和依賴性解決方案?Mar 17, 2025 pm 05:46 PM

本文討論了使用Maven和Gradle進行Java項目管理,構建自動化和依賴性解決方案,以比較其方法和優化策略。

如何使用適當的版本控制和依賴項管理創建和使用自定義Java庫(JAR文件)?如何使用適當的版本控制和依賴項管理創建和使用自定義Java庫(JAR文件)?Mar 17, 2025 pm 05:45 PM

本文使用Maven和Gradle之類的工具討論了具有適當的版本控制和依賴關係管理的自定義Java庫(JAR文件)的創建和使用。

如何使用咖啡因或Guava Cache等庫在Java應用程序中實現多層緩存?如何使用咖啡因或Guava Cache等庫在Java應用程序中實現多層緩存?Mar 17, 2025 pm 05:44 PM

本文討論了使用咖啡因和Guava緩存在Java中實施多層緩存以提高應用程序性能。它涵蓋設置,集成和績效優勢,以及配置和驅逐政策管理最佳PRA

如何將JPA(Java持久性API)用於具有高級功能(例如緩存和懶惰加載)的對象相關映射?如何將JPA(Java持久性API)用於具有高級功能(例如緩存和懶惰加載)的對象相關映射?Mar 17, 2025 pm 05:43 PM

本文討論了使用JPA進行對象相關映射,並具有高級功能,例如緩存和懶惰加載。它涵蓋了設置,實體映射和優化性能的最佳實踐,同時突出潛在的陷阱。[159個字符]

Java的類負載機制如何起作用,包括不同的類載荷及其委託模型?Java的類負載機制如何起作用,包括不同的類載荷及其委託模型?Mar 17, 2025 pm 05:35 PM

Java的類上載涉及使用帶有引導,擴展程序和應用程序類負載器的分層系統加載,鏈接和初始化類。父代授權模型確保首先加載核心類別,從而影響自定義類LOA

如何將Java的RMI(遠程方法調用)用於分佈式計算?如何將Java的RMI(遠程方法調用)用於分佈式計算?Mar 11, 2025 pm 05:53 PM

本文解釋了用於構建分佈式應用程序的Java的遠程方法調用(RMI)。 它詳細介紹了接口定義,實現,註冊表設置和客戶端調用,以解決網絡問題和安全性等挑戰。

如何使用Java的插座API進行網絡通信?如何使用Java的插座API進行網絡通信?Mar 11, 2025 pm 05:53 PM

本文詳細介紹了用於網絡通信的Java的套接字API,涵蓋了客戶服務器設置,數據處理和關鍵考慮因素,例如資源管理,錯誤處理和安全性。 它還探索了性能優化技術,我

如何在Java中創建自定義網絡協議?如何在Java中創建自定義網絡協議?Mar 11, 2025 pm 05:52 PM

本文詳細介紹了創建自定義Java網絡協議。 它涵蓋協議定義(數據結構,框架,錯誤處理,版本控制),實現(使用插座),數據序列化和最佳實踐(效率,安全性,維護

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中