以下のコードは、 関連性がある一部のタスクがまとまっているが、他の種類の凝集度に比べて凝集度が低い例です。
このサンプルコードでは、LogicalCohesionExampleクラス内で関連性の高いタスク(在庫管理と請求書生成)がまとめられていますが、関連性の低いタスク(通知とログ出力)も同じモジュール内に存在しています。
このような設計においては、論理的凝集が示されていますが、凝集度が他の高い凝集度タイプに比べて低いと言えます。
設計上の改善の余地があり、関連性の高いタスクを明確にまとめることが望ましいです
<?php
class LogicalCohesionExample
{
public function processOrder($order)
{
// 注文の処理
// 関連性の高いタスク: 在庫管理、請求書生成
$this->updateInventory($order);
$this->generateInvoice($order);
// 関連性の低いタスク: 通知、ログ出力
$this->sendNotification($order);
$this->logActivity($order);
}
private function updateInventory($order)
{
// 在庫の更新ロジック
}
private function generateInvoice($order)
{
// 請求書生成ロジック
}
private function sendNotification($order)
{
// 通知の送信ロジック
}
private function logActivity($order)
{
// アクティビティのログ出力ロジック
}
}
関連性の高いタスクがそれぞれのクラスに分離され、それぞれが特定の責務を持つようになりました。
各クラスは単一の責務を担当し、凝集度が高まり、コードがより明確になります。
また、新しいクラスを追加することが容易になり、コードの保守性と拡張性が向上します。
<?php
class OrderProcessor
{
private $order;
private $inventoryUpdater;
private $invoiceGenerator;
public function __construct($order, $inventoryUpdater, $invoiceGenerator)
{
$this->order = $order;
$this->inventoryUpdater = $inventoryUpdater;
$this->invoiceGenerator = $invoiceGenerator;
}
public function processOrder()
{
// 注文の処理
$this->inventoryUpdater->updateInventory($this->order);
$this->invoiceGenerator->generateInvoice($this->order);
}
}
<?php
class InventoryUpdater
{
public function updateInventory($order)
{
// 在庫の更新ロジック
}
}
<?php
class InvoiceGenerator
{
public function generateInvoice($order)
{
// 請求書生成ロジック
}
}
<?php
class NotificationSender
{
public function sendNotification($order)
{
// 通知の送信ロジック
}
}
<?php
class ActivityLogger
{
public function logActivity($order)
{
// アクティビティのログ出力ロジック
}
}