重构是好还是坏?
给出以下代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用对象并执行类似于“用子类替换类型代码”的操作怎么样?
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
你在简洁中获得的东西会失去可读性。在当前的示例中,我可以轻松分辨出什么去了哪里。在新的代码中,我必须更加努力地思考。
将其乘以接下来的一千次编辑,您将遇到一些严重的可维护性问题。
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.