# 代码简洁之道

#### 目的

1. 增加代码易读性，方便后期维护和升级

#### 问题

**变量**

1. 状态：1，2，3？ **坏:**

   ```php
   // What the heck is 4 for?
   if ($user->access & 4) {
       // ...
   }
   ```

   **好:**

   ```php
   class User
   {
       const ACCESS_READ = 1;
       const ACCESS_CREATE = 2;
       const ACCESS_UPDATE = 4;
       const ACCESS_DELETE = 8;
   }

   if ($user->access & User::ACCESS_UPDATE) {
       // do edit ...
   }
   ```
2. true false ? => type: charge nocharge
3. 资源的统一：表的名字，redis资源
4. 变量定义了不使用(冗余代码)
5. 三元表达式

```
$num = 0;
if ($data)
{
        $num = 1;
}
```

推荐：

```
$num = $data ? 1 : 0;
```

1. 定义了就使用

```
$data  = [1, 2, 3];
// 此处200行代码 
// 对$data处理
```

推荐

```
$data  = [1, 2, 3];
// 对$data处理
```

**函数**

1. 函数应该只做一件事
2. if else a. 改写成方法 b. 提前return c. 根据返回结果归类情况 **坏:**

   ```php
   function isShopOpen($day): bool
   {
       if ($day) {
           if (is_string($day)) {
               $day = strtolower($day);
               if ($day === 'friday') {
                   return true;
               } elseif ($day === 'saturday') {
                   return true;
               } elseif ($day === 'sunday') {
                   return true;
               } else {
                   return false;
               }
           } else {
               return false;
           }
       } else {
           return false;
       }
   }
   ```

   **好:**

   ```php
   function isShopOpen(string $day): bool
   {
       if (empty($day)) {
           return false;
       }

       $openingDays = [
           'friday', 'saturday', 'sunday'
       ];

       return in_array(strtolower($day), $openingDays, true);
   }
   ```
3. 代码太长 拆分成方法
4. array函数来精简代码：比如：array\_column等
5. 不要用flag作为函数的参数 flag就是在告诉大家，这个方法里处理很多事。前面刚说过，一个函数应当只做一件事。 把不同flag的代码拆分到多个函数里。 **坏:**

```php
function createFile(string $name, bool $temp = false): void
{
    if ($temp) {
        touch('./temp/'.$name);
    } else {
        touch($name);
    }
}
```

**好:**

````
```php
function createFile(string $name): void
{
    touch($name);
}

function createTempFile(string $name): void
{
    touch('./temp/'.$name);
}
```
````

**类**

1. 符合MVC的结构，Controller层不要有数据库操作

**冗余代码**

![image.png | left | 787x538](https://cdn.yuque.com/yuque/0/2018/png/103176/1528264205887-170c1ffe-694b-42a0-b8db-b203cac78814.png)

#### 更多

<https://github.com/php-cpm/clean-code-php>

#### 背景

重构前：装机盒子和装机APP => 8000+代码 重构后：装机APP => 2000+

#### 目的

1. 增加代码易读性，方便后期维护和升级

#### 问题

**变量**

1. 状态：1，2，3？ **坏:**

   ```php
   // What the heck is 4 for?
   if ($user->access & 4) {
       // ...
   }
   ```

   **好:**

   ```php
   class User
   {
       const ACCESS_READ = 1;
       const ACCESS_CREATE = 2;
       const ACCESS_UPDATE = 4;
       const ACCESS_DELETE = 8;
   }

   if ($user->access & User::ACCESS_UPDATE) {
       // do edit ...
   }
   ```
2. true false ? => type: charge nocharge
3. 资源的统一：表的名字，redis资源
4. 变量定义了不使用(冗余代码)
5. 三元表达式

```
$num = 0;
if ($data)
{
        $num = 1;
}
```

推荐：

```
$num = $data ? 1 : 0;
```

1. 定义了就使用

```
$data  = [1, 2, 3];
// 此处200行代码 
// 对$data处理
```

推荐

```
$data  = [1, 2, 3];
// 对$data处理
```

**函数**

1. 函数应该只做一件事
2. if else a. 改写成方法 b. 提前return c. 根据返回结果归类情况 **坏:**

   ```php
   function isShopOpen($day): bool
   {
       if ($day) {
           if (is_string($day)) {
               $day = strtolower($day);
               if ($day === 'friday') {
                   return true;
               } elseif ($day === 'saturday') {
                   return true;
               } elseif ($day === 'sunday') {
                   return true;
               } else {
                   return false;
               }
           } else {
               return false;
           }
       } else {
           return false;
       }
   }
   ```

   **好:**

   ```php
   function isShopOpen(string $day): bool
   {
       if (empty($day)) {
           return false;
       }

       $openingDays = [
           'friday', 'saturday', 'sunday'
       ];

       return in_array(strtolower($day), $openingDays, true);
   }
   ```
3. 代码太长 拆分成方法
4. array函数来精简代码：比如：array\_column等
5. 不要用flag作为函数的参数 flag就是在告诉大家，这个方法里处理很多事。前面刚说过，一个函数应当只做一件事。 把不同flag的代码拆分到多个函数里。 **坏:**

```php
function createFile(string $name, bool $temp = false): void
{
    if ($temp) {
        touch('./temp/'.$name);
    } else {
        touch($name);
    }
}
```

**好:**

````
```php
function createFile(string $name): void
{
    touch($name);
}

function createTempFile(string $name): void
{
    touch('./temp/'.$name);
}
```
````

**类**

1. 符合MVC的结构，Controller层不要有数据库操作

**冗余代码**

![image.png | left | 787x538](https://cdn.yuque.com/yuque/0/2018/png/103176/1528264205887-170c1ffe-694b-42a0-b8db-b203cac78814.png)

#### 更多

<https://github.com/php-cpm/clean-code-php>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://bing.gitbook.io/phper/notes/bian-ma/dai-ma-jian-jie-zhi-dao.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
