> For the complete documentation index, see [llms.txt](https://go.raymondctw.dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://go.raymondctw.dev/technology/python/clean-code-in-python/xie-fa.md).

# 寫法

有些人會很喜歡用一些比較聰明簡短的方式來撰寫，但有時團隊中會有菜鳥或初學者時，就會出現滿臉問號。

聰明簡短的方式：

```python
users = [{"first_name": "Helen", "age": 39},
         {"first_name": "Buck", "age": 10},
         {"first_name": "anni", "age": 9}
        ]

users = sorted(users, key = lambda user: user["first_name"].lower())
```

上面的程式碼使用一行程式碼就完成計算，除了對新手稍微不友善外，可能還遺漏了一些檢查等過程，可以修改為以下：

```python
users = [{"first_name": "Helen", "age": 39},
         {"first_name": "Buck", "age": 10},
         {"first_name": "anni", "age": 9}
        ]

def get_user_name(users):
    """將名字轉換為小寫"""
    return users["first_name"].lower()

def get_sorted_dictionary(users):
    """檢查型態與長度，並依照first_name進行排序"""
    if not isinstance(users, dict):
        raise ValueError("Not a correct dictionary")
    if len(users) == 0:
        raise ValueError("Empty dictionary")
        
    users_by_name = sorted(users, key = get_user_name)
    return users_by_name
```

透過額外建立兩個函數，可以讓思慮更為清晰，除了增加可讀性外，亦可進行資料格式檢查，以幫助後面的debug與測試流程。

過於簡潔方式：

```python
if val: # Will work when val is not None
# 
```

建議方式：

```python
if val is not None: # Make sure only None value will be false
```
