首頁 > 後端開發 > php教程 > YAGNI(你不需要它)

YAGNI(你不需要它)

DDD
發布: 2024-12-03 20:39:12
原創
305 人瀏覽過

YAGNI (You Aren

核心原則

僅在您真正需要時才實現功能,而不是在您認為將來可能需要它們時才實現。

範例

過早抽象(不好)

// Over-engineered solution anticipating future needs
class UserService {
    private $database;
    private $cache;
    private $logger;
    private $notifications;
    private $analytics;

    public function __construct(
        DatabaseInterface $database,
        CacheInterface $cache,
        LoggerInterface $logger,
        NotificationService $notifications,
        AnalyticsService $analytics
    ) {
        $this->database = $database;
        $this->cache = $cache;
        $this->logger = $logger;
        $this->notifications = $notifications;
        $this->analytics = $analytics;
    }

    public function createUser($data) {
        $this->logger->info('Creating user');
        $user = $this->database->insert('users', $data);
        $this->cache->set('user_' . $user->id, $user);
        $this->notifications->sendWelcomeEmail($user);
        $this->analytics->trackUserCreation($user);
        return $user;
    }
}
登入後複製

實施簡單(好)

class UserService {
    private $database;

    public function __construct(DatabaseInterface $database) {
        $this->database = $database;
    }

    public function createUser($data) {
        return $this->database->insert('users', $data);
    }
}
登入後複製

真實場景

電子商務範例

// Bad: Implementing unused features
class Product {
    private $name;
    private $price;
    private $stock;
    private $weight;          // Not needed yet
    private $dimensions;      // Not needed yet
    private $shippingZones;   // Not needed yet
    private $taxCategories;   // Not needed yet
    private $customFields;    // Not needed yet

    public function calculateShipping($address) {
        // Complex shipping calculation that isn't required
    }

    public function calculateTax($country) {
        // Complex tax calculation that isn't required
    }
}

// Good: Implementing what's needed now
class Product {
    private $name;
    private $price;
    private $stock;

    public function __construct(string $name, float $price, int $stock) {
        $this->name = $name;
        $this->price = $price;
        $this->stock = $stock;
    }
}
登入後複製

常見的反模式

  1. 在需要之前建立複雜的配置系統
  2. 為未來的可擴展性創建複雜的繼承層次結構
  3. 為未來潛在的功能添加資料庫欄位
  4. 實作不需要的 API 端點
  5. 為特定問題建立通用解決方案

好處

  1. 降低程式碼庫複雜度
  2. 降低維修成本
  3. 更快的開發週期
  4. 更專注於當前需求
  5. 減少技術債

例外情況

  1. 核心架構決策
  2. 以後更改成本高昂的資料結構
  3. 安全考量
  4. 監理合規要求

以上是YAGNI(你不需要它)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板