反模式遵循与预定义设计模式相对立的策略.该战略包括共同问题的共同方法,这些方法可以正式化,并且通常可被视为良好的发展实践.通常,反模式是相反的并且是不期望的.反模式是软件开发中使用的某些模式,被认为是糟糕的编程实践.
反模式的重要特征
现在让我们来看看看看反模式的一些重要特征.
正确性
这些模式确实会破坏你的代码并让你做错事.下面是这个的简单说明;
class Rectangle(object):def __init__(self, width, height):self._width = widthself._height = heightr = Rectangle(5, 6)# direct access of protected memberprint("Width: {:d}".format(r._width))
可维护性
如果一个程序可以维护的话根据要求易于理解和修改.导入模块可以视为可维护性的一个例子.
import mathx = math.ceil(y)# orimport multiprocessing as mppool = mp.pool(8)
反模式示例
以下示例有助于演示反模式 :
#Baddef 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 rres = filter_for_foo(["bar","foo","faz"])if res is not None: #continue processing pass#Gooddef 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 rtry: res = filter_for_foo(["bar","foo","faz"]) #continue processingexcept SomeException: i = 0while i < 10: do_something() #we forget to increment i
解释
示例包括演示在Python中创建函数的好坏标准.