首页 > 后端开发 > php教程 > YAGNI(你不需要它)

YAGNI(你不需要它)

DDD
发布: 2024-12-03 20:39:12
原创
314 人浏览过

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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板