Python-design-patterns-anti

提供:Dev Guides
移動先:案内検索

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で関数を作成するための良い標準と悪い標準のデモが含まれています。