原文链接: 50 Coding Laws That Would Make You A Decent Programmer.
21. 避免魔法数字 魔法数字是一个硬编码的值,可能会在稍后阶段更改,但因此很难更新。
1 2 3 4 5 # ❌ SELECT TOP 50 * FROM orders # ✅ NUM_OF_ORDERS = 50 SELECT TOP NUM_OF_ORDERS * FROM orders 22. 避免深度嵌套 1 2 3 4 5 6 7 # ❌ if x: if y: do_something() # ✅ if x and y: do_something() 23. 避免临时变量 1 2 3 4 5 # ❌ temp_result = calculate(x, y) final_result = temp_result * 2 # ✅ final_result = calculate(x, y) * 2 24. 避免使用神秘的缩写 1 2 3 4 5 6 # ❌ def calc(x, y): pass # ✅ def calculate_total_price(quantity, unit_price): pass 25. 避免硬编码Path 1 2 3 4 5 # ❌ file_path = "/path/to/file.txt" # ✅ import os file_path = os.getenv("FILE_PATH") 26. 使用使用Try…Catch…Finally语句 在编写代码时,最好也包括错误处理。这有助于加快调试过程并提高代码的复杂性,同时保持干净和可管理。
...