# Early Retrurn Pattern 如有錯誤歡迎糾正,小弟正在學習中 ## 提早返回(early return) 用於簡化代碼邏輯和提高可讀性的技術。這種技術涉及在滿足特定條件時,立即從函數中返回結果,從而避免不必要的嵌套和複雜性。 你絕對不會想在程式碼看到波動拳 ![image](https://hackmd.io/_uploads/S1YQ5II90.png) [Linux Code style指南](https://www.kernel.org/doc/html/v4.10/process/coding-style.html)中講到縮排超過三行就應該重整程式 ![image](https://hackmd.io/_uploads/BkhaqL8cA.png) ### 特性 - 減少嵌套層數:通過提前返回結果,減少了對 if 語句的嵌套,使代碼更簡潔。 - 提高可讀性:清晰地顯示函數的主要邏輯,容易理解和維護。 - 簡化錯誤處理:更容易處理特殊情況和錯誤,並在遇到問題時快速返回。 透過以下簡單的例子就可以看出差異了,當價格與折扣不符合時直接return,相較於條件達成又做複合式判斷好閱讀 early return ``` python def calculate_discount(price: float, discount: float) -> float: if price <= 0: return 0 if discount < 0: return price return price * (1 - discount) ``` 未使用early return ``` python def calculate_discount(price: float, discount: float) -> float: if price > 0: if discount >= 0: return price * (1 - discount) else: return price else: return 0 ```