首页 > 后端开发 > php教程 > KISS 原则(保持简单,愚蠢)

KISS 原则(保持简单,愚蠢)

Linda Hamilton
发布: 2024-12-15 02:28:08
原创
353 人浏览过

KISS Principle (Keep It Simple, Stupid)

了解接吻

KISS 提倡软件设计的简单性。复杂的系统更容易出错,更难维护,并且其他开发人员也很难理解。

现实世界的例子

1. 数据检索

// Complex (Bad)
class UserRepository {
    public function getUserWithDetails($userId) {
        return array_reduce(
            $this->db->query("SELECT * FROM users WHERE id = ?", [$userId])->fetch(),
            function($carry, $userData) {
                return array_merge(
                    $carry,
                    $this->enrichUserData(
                        $userData,
                        $this->getAdditionalData($userData['id'])
                    )
                );
            },
            []
        );
    }

    private function enrichUserData($userData, $additionalData) {
        return array_map(
            function($data) use ($userData) {
                return $this->transformData($data, $userData);
            },
            $additionalData
        );
    }
}

// Simple (Good)
class UserRepository {
    public function getUserWithDetails($userId) {
        $user = $this->db->query("SELECT * FROM users WHERE id = ?", [$userId])->fetch();
        if (!$user) {
            return null;
        }

        $user['address'] = $this->getAddress($userId);
        $user['orders'] = $this->getRecentOrders($userId);

        return $user;
    }

    private function getAddress($userId) {
        return $this->db->query("SELECT * FROM addresses WHERE user_id = ?", [$userId])->fetch();
    }

    private function getRecentOrders($userId) {
        return $this->db->query(
            "SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC LIMIT 5",
            [$userId]
        )->fetchAll();
    }
}
登录后复制

2. 配置管理

// Complex (Bad)
class ConfigManager {
    private $config = [];

    public function get($key) {
        return array_reduce(
            explode('.', $key),
            function($carry, $segment) {
                return is_array($carry) && isset($carry[$segment]) 
                    ? $carry[$segment] 
                    : null;
            },
            $this->config
        );
    }

    public function set($key, $value) {
        $segments = explode('.', $key);
        $current = &$this->config;

        while (count($segments) > 1) {
            $segment = array_shift($segments);
            if (!isset($current[$segment]) || !is_array($current[$segment])) {
                $current[$segment] = [];
            }
            $current = &$current[$segment];
        }

        $current[array_shift($segments)] = $value;
    }
}

// Simple (Good)
class ConfigManager {
    private $config = [];

    public function get($key) {
        if (isset($this->config[$key])) {
            return $this->config[$key];
        }
        return null;
    }

    public function set($key, $value) {
        $this->config[$key] = $value;
    }
}
登录后复制

3. 日期处理

// Complex (Bad)
function getNextBusinessDay($date) {
    $timestamp = strtotime($date);
    $daysToAdd = 1;

    while (true) {
        $nextDay = strtotime("+$daysToAdd days", $timestamp);
        $dayOfWeek = date('N', $nextDay);

        if ($dayOfWeek < 6) {
            $holidays = $this->getHolidays();
            $dateString = date('Y-m-d', $nextDay);

            if (!in_array($dateString, $holidays)) {
                return $dateString;
            }
        }
        $daysToAdd++;
    }
}

// Simple (Good)
function getNextBusinessDay($date) {
    $nextDay = new DateTime($date);
    $nextDay->modify('+1 day');

    while ($this->isWeekendOrHoliday($nextDay)) {
        $nextDay->modify('+1 day');
    }

    return $nextDay->format('Y-m-d');
}

private function isWeekendOrHoliday(DateTime $date) {
    $dayOfWeek = $date->format('N');
    $isWeekend = ($dayOfWeek >= 6);
    $isHoliday = in_array($date->format('Y-m-d'), $this->holidays);

    return $isWeekend || $isHoliday;
}
登录后复制

4. 表单验证

// Complex (Bad)
function validateUserInput($data) {
    return (
        isset($data['email']) && 
        filter_var($data['email'], FILTER_VALIDATE_EMAIL) &&
        isset($data['password']) && 
        strlen($data['password']) >= 8 &&
        preg_match('/[A-Z]/', $data['password']) &&
        preg_match('/[a-z]/', $data['password']) &&
        preg_match('/[0-9]/', $data['password']) &&
        (!isset($data['phone']) || 
            (preg_match('/^\+?[1-9]\d{1,14}$/', $data['phone']))
        )
    ) ? true : false;
}

// Simple (Good)
class UserValidator {
    public function validate($data) {
        $errors = [];

        if (!$this->isValidEmail($data['email'])) {
            $errors['email'] = 'Invalid email address';
        }

        if (!$this->isValidPassword($data['password'])) {
            $errors['password'] = 'Password must be at least 8 characters with mixed case and numbers';
        }

        if (isset($data['phone']) && !$this->isValidPhone($data['phone'])) {
            $errors['phone'] = 'Invalid phone number';
        }

        return empty($errors) ? true : $errors;
    }

    private function isValidEmail($email) {
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    }

    private function isValidPassword($password) {
        if (strlen($password) < 8) {
            return false;
        }

        return preg_match('/[A-Z]/', $password) 
            && preg_match('/[a-z]/', $password) 
            && preg_match('/[0-9]/', $password);
    }

    private function isValidPhone($phone) {
        return preg_match('/^\+?[1-9]\d{1,14}$/', $phone);
    }
}
登录后复制

最佳实践

  1. 方法长度:将方法保持在 20 行以下
  2. 单一职责:每个类/方法应该做好一件事
  3. 有意义的名称:为变量和函数使用清晰的描述性名称
  4. 避免嵌套:将条件嵌套限制为最多 2-3 层
  5. 提前返回:尽早返回以避免深度嵌套
  6. 评论:好的代码应该是自文档化的

亲吻的好处

  1. 可维护性:更容易更新和修改
  2. 调试:更容易发现和修复问题
  3. 入职:新团队成员更快地理解代码
  4. 测试:更简单的代码更容易测试
  5. 性能:通常比复杂的替代方案表现更好

以上是KISS 原则(保持简单,愚蠢)的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板