【问题标题】:Avoid too many arguments in a method避免方法中的参数过多
【发布时间】: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


【解决方案1】:

为什么不**kwargs:

def generic_column(**kwargs):
    """Build the column according the needed requirements."""
# creates column with arguments.
    return generic_column

【讨论】:

  • 当然,我知道这一点,我担心的是我一直读到应该避免有太多参数,在这种情况下,我想创建一个通用构建器,但要使其灵活需要很多参数。
  • @Zabander 编辑我的。
  • 这似乎可以工作,我唯一担心的是,如果使用 kwargs 可能不太容易让其他用户理解我的代码,但我想如果提交的密钥没有,我可以强制执行异常类型错误匹配一个验证列表,并在文档字符串中记录有效的关键参数
猜你喜欢
  • 2020-08-07
  • 2016-01-06
  • 1970-01-01
  • 2019-04-04
  • 1970-01-01
  • 1970-01-01
  • 2011-09-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多