ソフトウェア開発では、保守可能でスケーラブルで効率的なアプリケーションを作成するには、クリーンなコードの実践を遵守することが不可欠です。この規律を奨励する 1 つのアプローチは、開発者がより適切なオブジェクト指向コードを作成できるように設計された一連のルールであるオブジェクト キャリステニクスです。
この投稿では、オブジェクト キャリステニクスの原則と、それらを適用してよりクリーンで構造化されたコードを作成する方法について説明します。実際のコード例をさらに深く掘り下げたり、これらの原則が実際のプロジェクトでどのように実装されるかを知りたい場合は、私の GitHub リポジトリで詳細を確認してください。
さらに実践的な説明については、私の GitHub リポジトリにアクセスしてください。
オブジェクト体操とは何ですか?
オブジェクト体操は、オブジェクト指向の原則に従うことを促す 9 つのルールで構成されるプログラミング演習です。ルール自体は、Jeff Bay によって著書『The ThoughtWorks Anthology』で紹介されました。目的は、これらの制約に従うことで、コードの設計と構造にさらに重点を置くことを促すことです。
9 つのルールは次のとおりです:
1. メソッドごとに 1 レベルのインデントのみ
この原則は、各メソッドのインデントは 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(); } }
このバージョンでは、ロジック ブロックごとに 1 レベルのインデントがあり、コードがクリーンになり、保守が容易になります。
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 を削除することで、各セクションが 1 つの責任を処理する、より焦点を絞ったコードを作成できます。これは「単一責任原則」と一致しており、よりクリーンで保守しやすいソフトウェアの作成に役立ちます。
3. すべてのプリミティブと文字列をラップする
オブジェクト体操における重要な実践の 1 つは、すべてのプリミティブと文字列をカスタム クラスでラップすることです。このルールは、開発者がコード内で生のプリミティブ型や文字列を直接使用することを避けることを奨励します。代わりに、それらを意味のあるオブジェクト内にカプセル化する必要があります。このアプローチにより、より表現力が豊かで理解しやすく、管理できなくなることなく複雑になってもよいコードが得られます。
プリミティブ型と文字列を直接使用する例を考えてみましょう:
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>
- 意味のあるクラス。生の int、double、および String を使用する代わりに、Quantity、Price、および ProductName クラスを作成しました。これにより、これらの各値に意味が与えられ、カスタム検証や追加の動作が可能になります。
- 検証の強化。数量と価格が常に有効な値 (非負の金額など) であることを確認する検証を追加しました。プリミティブを独自のクラスでラップすると、管理がはるかに簡単になります。
- 可読性が向上し、コードがよりわかりやすくなりました。特定のプリミティブ値が何を表すかを推測する必要はなくなりました。それぞれの値は、その意味を明確に伝えるクラスにカプセル化されます。
4. 第一級のコレクション
リストやマップなどのコレクションを使用するときは、必ずそれを専用のオブジェクトにします。これにより、コードがクリーンな状態に保たれ、コレクションに関連するロジックが確実にカプセル化されます。
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
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 中国語 Web サイトの他の関連記事を参照してください。

この記事では、Javaプロジェクト管理、自動化の構築、依存関係の解像度にMavenとGradleを使用して、アプローチと最適化戦略を比較して説明します。

この記事では、MavenやGradleなどのツールを使用して、適切なバージョン化と依存関係管理を使用して、カスタムJavaライブラリ(JARファイル)の作成と使用について説明します。

この記事では、カフェインとグアバキャッシュを使用してJavaでマルチレベルキャッシュを実装してアプリケーションのパフォーマンスを向上させています。セットアップ、統合、パフォーマンスの利点をカバーし、構成と立ち退きポリシー管理Best Pra

この記事では、キャッシュや怠zyなロードなどの高度な機能を備えたオブジェクトリレーショナルマッピングにJPAを使用することについて説明します。潜在的な落とし穴を強調しながら、パフォーマンスを最適化するためのセットアップ、エンティティマッピング、およびベストプラクティスをカバーしています。[159文字]

Javaのクラスロードには、ブートストラップ、拡張機能、およびアプリケーションクラスローダーを備えた階層システムを使用して、クラスの読み込み、リンク、および初期化が含まれます。親の委任モデルは、コアクラスが最初にロードされ、カスタムクラスのLOAに影響を与えることを保証します


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

SecLists
SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

DVWA
Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

SublimeText3 Linux 新バージョン
SublimeText3 Linux 最新バージョン

EditPlus 中国語クラック版
サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません
