Rumah > Java > javaTutorial > teks badan

Memahami Object Calisthenics: Writing Cleaner Code

Linda Hamilton
Lepaskan: 2024-10-13 06:08:30
asal
424 orang telah melayarinya

Understanding Object Calisthenics: Writing Cleaner Code

Dalam pembangunan perisian, mematuhi amalan kod bersih adalah penting untuk mencipta aplikasi yang boleh diselenggara, berskala dan cekap. Satu pendekatan yang menggalakkan disiplin ini ialah Object Calisthenics, satu set peraturan yang direka untuk membimbing pembangun dalam menulis kod berorientasikan objek yang lebih baik.

Dalam siaran ini, saya akan meneroka prinsip Object Calisthenics dan cara ia boleh digunakan untuk menulis kod yang lebih bersih dan lebih berstruktur. Jika anda berminat untuk mendalami contoh kod praktikal atau mempelajari cara prinsip ini dilaksanakan dalam projek sebenar, sila semak repositori GitHub saya untuk mendapatkan butiran lanjut.

Untuk mendapatkan penjelasan yang lebih praktikal, lawati repositori GitHub saya.

Apakah Object Calisthenics?

Object Calisthenics ialah latihan pengaturcaraan yang terdiri daripada sembilan peraturan yang menggalakkan anda mematuhi prinsip berorientasikan objek. Peraturan itu sendiri telah diperkenalkan oleh Jeff Bay dalam bukunya The ThoughtWorks Anthology. Matlamatnya adalah untuk menggalakkan tumpuan yang lebih mendalam pada reka bentuk dan struktur kod anda dengan mengikut kekangan ini.

Berikut ialah 9 peraturan:

1. Hanya Satu Tahap Inden Setiap Kaedah

Prinsip ini menyatakan bahawa setiap kaedah harus mempunyai satu tahap lekukan sahaja. Dengan mengekalkan tahap lekukan yang rendah, kami boleh meningkatkan kebolehbacaan dan menjadikan kod lebih mudah untuk dikekalkan. Jika kaedah mempunyai terlalu banyak tahap lekukan, ini selalunya merupakan tanda bahawa logik di dalamnya terlalu kompleks dan perlu dipecahkan kepada bahagian yang lebih kecil.

Contoh Pelaksanaan
Berikut ialah contoh kaedah yang tidak mengikut prinsip ini:

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.");
        }
    }
}
Salin selepas log masuk

Dalam kod di atas, terdapat berbilang tahap lekukan dalam kaedah processOrder, yang menjadikannya lebih sukar untuk dibaca, terutamanya apabila logik menjadi lebih kompleks.

Sekarang, mari lihat bagaimana kita boleh mengikuti prinsip dengan memudahkan logik:

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();
    }
}
Salin selepas log masuk

Versi ini mempunyai satu tahap lekukan setiap blok logik, menjadikan kod lebih bersih dan lebih mudah diselenggara.

2. Jangan Gunakan Kata Kunci lain

dalam pengaturcaraan berorientasikan objek, penggunaan kata kunci else selalunya membawa kepada kod yang bersepah dan sukar diselenggara. Daripada bergantung pada pernyataan lain, anda boleh menstruktur kod anda menggunakan pulangan awal atau polimorfisme. Pendekatan ini meningkatkan kebolehbacaan, mengurangkan kerumitan dan menjadikan kod anda lebih mudah diselenggara.

Mari kita lihat dahulu contoh yang menggunakan kata kunci 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.");
        }
    }
}
Salin selepas log masuk

Dalam contoh ini, pernyataan else memaksa kita untuk mengendalikan kes negatif secara eksplisit, menambah kerumitan tambahan. Sekarang, mari kita refactor ini untuk mengelakkan penggunaan lain:

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.");
    }
}
Salin selepas log masuk

Dengan menghapuskan yang lain, anda menulis kod yang lebih fokus, dengan setiap bahagian mengendalikan satu tanggungjawab. Ini selaras dengan "Prinsip Tanggungjawab Tunggal" dan membantu mencipta perisian yang lebih bersih dan boleh diselenggara.

3. Balut Semua Primitif dan Rentetan

Salah satu amalan utama dalam Object Calisthenics ialah membungkus semua primitif dan rentetan dalam kelas tersuai. Peraturan ini menggalakkan pembangun untuk mengelak daripada menggunakan jenis atau rentetan primitif mentah secara langsung dalam kod mereka. Sebaliknya, mereka harus merangkumnya dalam objek yang bermakna. Pendekatan ini membawa kepada kod yang lebih ekspresif, lebih mudah difahami dan boleh berkembang dalam kerumitan tanpa menjadi tidak terurus.

Mari kita pertimbangkan contoh di mana kita menggunakan jenis dan rentetan primitif secara langsung:

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;
    }
}
Salin selepas log masuk

Dalam kod ini, int, double dan String digunakan secara langsung. Walaupun ini mungkin kelihatan mudah, ia tidak menyatakan niat setiap nilai dengan jelas dan menjadikannya lebih sukar untuk memperkenalkan tingkah laku atau kekangan baharu khusus kepada nilai tersebut kemudian.

Sekarang, mari kita memfaktorkan semula kod ini untuk membungkus primitif dan rentetan:

public class Quantity {
    private final int value;

    public Quantity(int value) {
        if (value < 1) {
            throw new IllegalArgumentException("Quantity must be greater than zero.");
        }
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

public class Price {
    private final double value;

    public Price(double value) {
        if (value <= 0) {
            throw new IllegalArgumentException("Price must be positive.");
        }
        this.value = value;
    }

    public double getValue() {
        return value;
    }
}

public class ProductName {
    private final String name;

    public ProductName(String name) {
        if (name == null || name.isEmpty()) {
            throw new IllegalArgumentException("Product name cannot be empty.");
        }
        this.name = name;
    }

    public String getValue() {
        return name;
    }
}

public class Order {
    private final Quantity quantity;
    private final Price pricePerUnit;
    private final ProductName productName;

    public Order(Quantity quantity, Price pricePerUnit, ProductName productName) {
        this.quantity = quantity;
        this.pricePerUnit = pricePerUnit;
        this.productName = productName;
    }

    public double calculateTotal() {
        return quantity.getValue() * pricePerUnit.getValue();
    }
}
Salin selepas log masuk

Perubahan Utama:

  • Kelas Bermakna, Daripada menggunakan int mentah, double dan String, kami mencipta kelas Kuantiti, Harga dan ProductName. Ini memberi makna kepada setiap nilai ini dan membenarkan pengesahan tersuai atau gelagat tambahan.
  • Pengesahan Dipertingkat, Kami menambah pengesahan untuk memastikan Kuantiti dan Harga sentiasa mempunyai nilai yang sah, seperti jumlah bukan negatif. Ini lebih mudah untuk diuruskan apabila primitif dibungkus dalam kelas mereka sendiri.
  • Kebolehbacaan yang dipertingkatkan, Kod ini lebih jelas. Anda tidak perlu lagi meneka apa yang diwakili oleh nilai primitif tertentu. Setiap nilai terkandung dalam kelas yang menyampaikan maksudnya dengan jelas.

4. Koleksi Kelas Pertama

Setiap kali anda menggunakan koleksi seperti Senarai atau Peta, jadikan ia sebagai objek khusus. Ini memastikan kod anda bersih dan memastikan logik yang berkaitan dengan koleksi dirangkumkan.

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;
    }
}
Salin selepas log masuk

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();
    }
}
Salin selepas log masuk

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();
    }
}
Salin selepas log masuk

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()
    }
}
Salin selepas log masuk

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
    }
}
Salin selepas log masuk
  • 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
    }
}
Salin selepas log masuk
  • 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
    }
}
Salin selepas log masuk

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;
    }
}
Salin selepas log masuk

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 <= balance) {
            balance -= amount;
        }
    }
}
Salin selepas log masuk

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

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:

public class BankAccount {
    private double balance;

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

    public void withdraw(double amount) {
        if (amount <= balance) {
            balance -= amount;
        }
    }

    public boolean hasSufficientFunds(double amount) {
        return amount <= balance;
    }
}
Salin selepas log masuk

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.

9. Separate UI from Business Logic

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.

Consider the following example where the UI and business logic are intertwined:

public class UserRegistration {
    public void registerUser(String username, String password) {
        // UI Logic: Validation
        if (username.isEmpty() || password.length() < 6) {
            System.out.println("Invalid username or password.");
            return;
        }

        // Business Logic: Registration
        System.out.println("User " + username + " registered successfully.");
    }
}
Salin selepas log masuk

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.

A better approach is to separate the UI from the business logic, as shown in the following example:

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() < 6) {
            System.out.println("Invalid username or password.");
            return;
        }

        User user = new User(username, password);
        userRegistration.registerUser(user);
    }
}

class User {
    private String username;
    private String password;

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }
}
Salin selepas log masuk

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.

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

Conclusion

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!

Atas ialah kandungan terperinci Memahami Object Calisthenics: Writing Cleaner Code. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!