您使用漂亮的单词来理由不良代码
tl; dr:不要原谅不良代码。写一个干净的!
问题
- 可读性
解决方案
- 重写代码并删除注释
语境
该术语来自马丁·福勒(Martin Fowler)的书“重构:改进现有代码的设计”
示例代码
错误的
# This is a function that adds two numbers
def s(a, b):
# Now you are going to add a and b
res = a + b
# And return the result
return res
正确的
def sum(adder, anotherAdder):
return adder + anotherAdder
如果您要求Chatgpt改进此版本,它实际上会使它恶化:
def calculate_sum(number1, number2):
# Calculate the sum of two numbers
result = number1 + number2
return result
# In this improved version:
#
# The function name calculate_sum is more descriptive than sum,
# making it clear that this function calculates the sum of two numbers.
# (Wrong) it is more imperative and mistakes the 'what' with the 'how'
#
# The parameter names number1 and number2 are more meaningful
# than adder and anotherAdder, helping to indicate the purpose of each parameter.
# (wrong) They indicate type instead of role
#
# The comment # Calculate the sum of two numbers provides a clear
# and concise explanation of what the function does,
# making it easier for someone reading the code to understand its purpose.
# (wrong) in fact, it is an example of deodorant and useless comment
检测
[x]半自动
大多数评论是代码气味。
您可以删除除臭剂注释并改进代码。
例外
- 评论应仅用于描述重要的设计决策。
标签
- 评论
结论
删除您在代码中发现的任何毫无意义的评论。
关系
更多信息
免责声明
代码气味是我的opinion。
学分
我们在这里提到评论的原因是,评论通常被用作除臭剂。令人惊讶的是,您多久看一次评论的代码,并注意到该评论在那里,因为代码不好。
Martin Fowler
本文是CodesMell系列的一部分。