重构是好还是坏?

发布于 2024-09-30 08:30:07 字数 904 浏览 1 评论 0原文

给出以下代码:

    status = row[COL_STATUS]

    if status == "idle":
        row[COL_EDITABLE] = True
        row[COL_FONTSTYLE] = pango.STYLE_NORMAL
        row[COL_WEIGHT] = pango.WEIGHT_NORMAL
    elif status == "DCed":
        row[COL_EDITABLE] = True
        row[COL_FONTSTYLE] = pango.STYLE_ITALIC
        row[COL_WEIGHT] = pango.WEIGHT_NORMAL
    else:
        row[COL_EDITABLE] = False
        row[COL_FONTSTYLE] = pango.STYLE_NORMAL
        row[COL_WEIGHT] = pango.WEIGHT_BOLD

您认为以下代码是净有益的重构吗?

    d = {"idle": (True,  pango.STYLE_NORMAL, pango.WEIGHT_NORMAL),
         "DCed": (True,  pango.STYLE_ITALIC, pango.WEIGHT_NORMAL),
         None:   (False, pango.STYLE_NORMAL, pango.WEIGHT_BOLD)}
    e,f,w = d.get(status, d[None])
    row[COL_EDITABLE] = e
    row[COL_FONTSTYLE] = f
    row[COL_WEIGHT] = w

如果有更多案例或更多行组件需要编辑怎么办?

Given the following code:

    status = row[COL_STATUS]

    if status == "idle":
        row[COL_EDITABLE] = True
        row[COL_FONTSTYLE] = pango.STYLE_NORMAL
        row[COL_WEIGHT] = pango.WEIGHT_NORMAL
    elif status == "DCed":
        row[COL_EDITABLE] = True
        row[COL_FONTSTYLE] = pango.STYLE_ITALIC
        row[COL_WEIGHT] = pango.WEIGHT_NORMAL
    else:
        row[COL_EDITABLE] = False
        row[COL_FONTSTYLE] = pango.STYLE_NORMAL
        row[COL_WEIGHT] = pango.WEIGHT_BOLD

Would the following be a net beneficial refactoring, in your opinion?

    d = {"idle": (True,  pango.STYLE_NORMAL, pango.WEIGHT_NORMAL),
         "DCed": (True,  pango.STYLE_ITALIC, pango.WEIGHT_NORMAL),
         None:   (False, pango.STYLE_NORMAL, pango.WEIGHT_BOLD)}
    e,f,w = d.get(status, d[None])
    row[COL_EDITABLE] = e
    row[COL_FONTSTYLE] = f
    row[COL_WEIGHT] = w

What if there were more cases or more row components to edit?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

转瞬即逝 2024-10-07 08:30:07

使用对象并执行类似于“用子类替换类型代码”的操作怎么样?
http://www.refactoring.com/catalog/replaceTypeCodeWithSubclasses.html

What about using objects and doing something akin to "Replace Type Code With Subclasses"?
http://www.refactoring.com/catalog/replaceTypeCodeWithSubclasses.html

巷子口的你 2024-10-07 08:30:07

你在简洁中获得的东西会失去可读性。在当前的示例中,我可以轻松分辨出什么去了哪里。在新的代码中,我必须更加努力地思考。

将其乘以接下来的一千次编辑,您将遇到一些严重的可维护性问题。

What you gain in conciseness you lose in readability. In the current example, I can easily tell what goes where. In the new code, I have to think a little harder.

Multiply that by the next thousand edits and you're going to have some serious maintainability problems on your hands.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文