【发布时间】:2019-07-04 12:22:48
【问题描述】:
我想知道是否有办法避免向方法传递太多参数,目前我正在传递 5,我认为这会使代码更难维护和更不干净。在这种情况下,方法 generic_column。 当前传递 5 个参数,但它可能传递 8 个或更多。
class BranchBuilder(object):
"""docstring forBranchBuilder."""
def __init__(self, raw):
self.raw = raw
@staticmethod
def generic_column(size, posx, distance, raw=True,
color="red", complex=True):
"""Build the column according the needed requirements."""
# creates column with arguments.
return generic_column
def builder(self):
"""Build the branch that contains all the columns."""
initial_column = self.generic_column(3, 120, 66, raw=True,
color="white", complex=False)
mid_column = self.generic_column(3, 120, 66, raw=False, color="black",
complex=False)
last_column = self.generic_column(3, 120, 66, raw=False, complex=True)
我想找到一种方法,使其更易于维护,并且任何其他必须处理前面代码的人都清楚。
【问题讨论】:
-
你看过
*args和**kwargs -
是的,但我想知道这是否会使代码更难阅读,作为替代方案,我正在考虑仅为列生成器创建一个类,但我不确定这是否太多.
-
阅读这篇文章matheus.ro/2018/01/29/clean-code-avoid-many-arguments-functions。它可能会帮助你。如果你想编写干净的代码,你应该阅读本书amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/…。例如,您可能需要将 size、posx 和 distance 分组到 Column 类
-
谢谢,这似乎是一个很棒的指南,我希望它是为 python 编写的,以便更快地了解发生了什么。
标签: python class object methods