【问题标题】:Should I use generic or concrete setters and getters to handle mapping entities?我应该使用通用还是具体的 setter 和 getter 来处理映射实体?
【发布时间】:2020-12-27 06:51:14
【问题描述】:

我有一个应用程序,用户可以在其中更改某些设置。用户可以更改(设置)和读取(获取)他们的设置,这是一个类似映射的结构。 我创建了一个 UserSettingsInteractor 对象,它实现了更改和读取设置的用例,在 Python 中它看起来像:

class UserSettingsInteractor:

    def __init__(self, ...): ...

    def set_foo(self, user_id: int, value): ...
    def get_foo(self, user_id: int): ...
    
    def set_bar(self, user_id: int, value): ...
    def get_bar(self, user_id: int): ...

    ...

其中的好处是现有设置foobar 是明确的。但是编写 setter 和 getter 会变得非常冗长。可以概括为:

class UserSettingsInteractor:

    def __init__(self, ...): ...

    def set(self, user_id: int, setting: str, value): ...
    def get(self, user_id: int, setting: str): ...

现在客户端代码知道设置是如何表示的,它是一个键值对。不是让代码更脆弱吗?

哪种方法更好?

【问题讨论】:

    标签: design-patterns architecture software-design clean-architecture


    【解决方案1】:

    在我看来,通用方法并没有给您带来太多额外的好处:

    • 可读性不好 - 设置名称将仅作为参数而不是函数名称出现。而且您必须在 getter/setter 中实现长 case 语句,而不是在类级别区分多个函数。
    • 相同级别的耦合 - 如果设置发生变化(例如项目的数量或名称),您仍然需要在客户端和服务端进行更改。
    • 在编译时您不会看到语义错误(我认为这就是您所说的“脆弱”的意思)。

    我能想到的使用通用方法的唯一原因是,如果出于某种原因您需要一个独立于特定设置的稳定接口,例如,如果您正在开发一个您想要重用的通用UserSettings 服务在另一个应用场景中。

    延伸阅读:Concrete vs Generic – The story of a data model

    【讨论】:

      猜你喜欢
      • 2017-10-09
      • 1970-01-01
      • 2019-05-14
      • 2014-09-03
      • 2022-01-06
      • 2012-10-05
      • 2014-02-10
      • 1970-01-01
      • 2012-05-25
      相关资源
      最近更新 更多