返回
修复早期错误:重构第一份工作的代码
闲谈
2023-10-01 13:12:47
在软件开发的领域中,错误和教训是前进道路上不可避免的一部分。回顾我自己的职业生涯,我发现自己第一次接触代码时犯了很多错误。
为了说明,我重构了在我第一份工作中编写的代码。这段代码是一个简单的函数,用于计算两个数字的和。
def add_numbers(a, b):
"""
This function adds two numbers together.
Args:
a (int): The first number.
b (int): The second number.
Returns:
int: The sum of the two numbers.
"""
sum = a + b
return sum
现在,这段代码可能看起来很无害,但当时的我却犯了一些严重的错误。
首先,这个函数缺乏输入验证。这意味着用户可以传递任何类型的数据,而不会引发任何错误。例如,用户可以传递一个字符串或一个列表,这将导致程序崩溃。
其次,这个函数缺乏适当的文档。虽然函数名和参数名称提供了函数功能的一些基本信息,但它们并没有完全解释函数是如何工作的。这使得其他开发者很难理解和维护这个函数。
最后,这个函数使用了硬编码的变量名。这使得代码难以维护和扩展。例如,如果需要更改求和变量的名称,则必须在代码的多个位置进行更改。
重构这段代码以解决这些问题非常简单。首先,我添加了输入验证,以确保用户只传递数字。
def add_numbers(a, b):
"""
This function adds two numbers together.
Args:
a (int): The first number.
b (int): The second number.
Returns:
int: The sum of the two numbers.
"""
if not isinstance(a, int) or not isinstance(b, int):
raise TypeError("Both arguments must be integers.")
sum = a + b
return sum
接下来,我添加了适当的文档,解释了函数的工作原理以及如何使用它。
def add_numbers(a, b):
"""
This function adds two numbers together.
Args:
a (int): The first number.
b (int): The second number.
Returns:
int: The sum of the two numbers.
"""
if not isinstance(a, int) or not isinstance(b, int):
raise TypeError("Both arguments must be integers.")
"""Calculate the sum of the two numbers."""
sum = a + b
return sum
最后,我使用更有意义的变量名。
def add_numbers(first_number, second_number):
"""
This function adds two numbers together.
Args:
first_number (int): The first number.
second_number (int): The second number.
Returns:
int: The sum of the two numbers.
"""
if not isinstance(first_number, int) or not isinstance(second_number, int):
raise TypeError("Both arguments must be integers.")
"""Calculate the sum of the two numbers."""
sum = first_number + second_number
return sum
重构后的代码现在更加健壮、可维护和可扩展。它还有助于我了解早期错误的教训,并提高了我的开发实践。