Python 設計模式 - 反模式



反模式遵循與預定義設計模式相反的策略。該策略包括針對常見問題的一些常見方法,這些方法可以被形式化,並且通常可以被認為是良好的開發實踐。通常,反模式是相反且不希望的。反模式是在軟體開發中使用的一些模式,被認為是不好的程式設計實踐。

反模式的重要特徵

現在讓我們看看反模式的一些重要特徵。

正確性

這些模式實際上會破壞你的程式碼並讓你做錯事。以下是對此的一個簡單說明:

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 中建立函式的良好和不良標準的演示。

廣告