目录

Python Design Patterns - Anti

反模式遵循与预定义设计模式相对立的策略。 该战略包括共同问题的共同方法,这些方法可以正式化,并且通常可被视为良好的发展实践。 通常,反模式是相反的并且是不期望的。 反模式是软件开发中使用的某些模式,被认为是糟糕的编程实践。

反模式的重要特征

现在让我们看一下反模式的一些重要特征。

正确性(Correctness)

这些模式实际上会破坏您的代码并使您做错事。 以下是对此的简单说明 -

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))

可维护性(Maintainability)

如果程序易于理解和修改,则可以说是可维护的。 可以将导入模块视为可维护性的示例。

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

说明 (Explanation)

该示例包括演示在Python中创建函数的好的和坏的标准。

↑回到顶部↑
WIKI教程 @2018