反模式遵循与预定义的设计模式相反的策略。 该策略包含共同问题的常见方法,可以将其形式化,并且可以被普遍视为一种良好的开发实践。 通常情况下,反模式是相反的并且是不可取的。 反模式是软件开发中使用的某些模式,被认为是不好的编程实践。
反模式的重要特征
现在我们来看看反模式的一些重要特征。
正确性
这些模式从字面上破坏代码,并让你做错事。 以下是对此的简单说明 -
class Rectangle(object):
def __init__(self, width, height):
self._width = width
self._height = height
r = Rectangle(5, 6)
# direct access of protected member
print("Width: {:d}".format(r._width))
可维护性
如果程序易于理解和根据要求进行修改,则称该程序是可维护的。 导入模块可以被认为是可维护性的一个例子。
import math
x = math.ceil(y)
# or
import multiprocessing as mp
pool = mp.pool(8)
反模式示例
以下示例演示如何实现反模式 -
#Bad
def filter_for_foo(l):
r = [e for e in l if e.find("foo") != -1]
if not check_some_critical_condition(r):
return None
return r
res = filter_for_foo(["bar","foo","faz"])
if res is not None:
#continue processing
pass
#Good
def filter_for_foo(l):
r = [e for e in l if e.find("foo") != -1]
if not check_some_critical_condition(r):
raise SomeException("critical condition unmet!")
return r
try:
res = filter_for_foo(["bar","foo","faz"])
#continue processing
except SomeException:
i = 0
while i < 10:
do_something()
#we forget to increment i
说明
这个例子包括了在Python中创建函数的好的和坏的标准的演示。
上一篇:
Python并发(多线程)
下一篇:
异常处理