用 100% code coverage 讓自己設計品質好的軟體
前言 很多敘述都是說 100% code coverage 雖然可以達成,但是會花非常多時間,所以往往 project 的 code coverage 都設定在 80-90% 左右。 但這前提是 source code 非常亂的情況下,才是 true。 現在我習慣讓新 projects 達到 100% code coverage,並不會多花時間,反而減少了許多 bugs,而且整體上程式碼也變得非常好讀,甚至讓任何新人進來看都看得懂。 我用一個簡化的 python 例子來描述怎麼做到這件事。 100% 不合理的案例 現代化的軟體通常少不了與外部軟體的整合,所以我們可以設計一個簡單化的 application: 用 REST API 取得某個使用者的發文 把 raw data 轉成 application 內部 data 用一些邏輯去搜尋發文 就會寫出下面這樣的程式碼,看似簡單: # complex_find.py from dataclasses import dataclass import requests @dataclass(frozen=True) class Post: id: int title: str body: str def find_posts_with_keyword(user_id: int, keyword: str) -> list[Post]: # Get a list of posts with REST API base_url = "https://jsonplaceholder.typicode.com/posts" params: dict[str, int] = {"userId": user_id} response = requests.get(base_url, params) try: response.raise_for_status() except requests.HTTPError as e: raise RuntimeError(f"Failed to call API with params: {params}") fr...