反模式遵循与预定义设计模式相对立的策略.该战略包括共同问题的共同方法,这些方法可以正式化,并且通常可被视为良好的发展实践.通常,反模式是相反的并且是不期望的.反模式是软件开发中使用的某些模式,被认为是糟糕的编程实践.
现在让我们来看看看看反模式的一些重要特征.
这些模式确实会破坏你的代码并让你做错事.下面是这个的简单说明;
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中创建函数的好坏标准.