SOLID原則に基づいた設計
ソフトウェアの変更・拡張に強いコードを記述するための5つの基本原則です。
- S – 単一責任の原則(Single Responsibility): 1つのクラスは1つの役割のみを持つ。
- O – 開放閉鎖の原則(Open/Closed): 拡張に対して開いており、修正に対して閉じている。
- L – リスコフの置換原則(Liskov Substitution): 派生型はその基本型と置換可能でなければならない。
- I – インターフェース分離の原則(Interface Segregation): クライアントが使用しないメソッドへの依存を強要しない。
- D – 依存性逆転の原則(Dependency Inversion): 上位モジュールは下位モジュールに依存せず、抽象(abcモジュールなど)に依存する。
デザインパターン(Strategyパターンの実践)
Pythonのファーストクラスオブジェクト特性を活かしたStrategyパターンの例です。アルゴリズムを動的に切り替え可能にします。
Python
from abc import ABC, abstractmethod
# 抽象基底クラス (Interface)
class PaymentStrategy(ABC):
@abstractmethod
def pay(self, amount: int) -> bool:
pass
# 具体的な戦略1: クレジットカード決済
class CreditCardPayment(PaymentStrategy):
def pay(self, amount: int) -> bool:
print(f"CreditCardで {amount} 円決済しました。")
return True
# 具体的な戦略2: PayPay決済
class PayPayPayment(PaymentStrategy):
def pay(self, amount: int) -> bool:
print(f"PayPayで {amount} 円決済しました。")
return True
# コンテキスト(利用側)
class PaymentService:
def __init__(self, strategy: PaymentStrategy):
self._strategy = strategy
def execute_payment(self, amount: int):
return self._strategy.pay(amount)
レイヤードアーキテクチャの分離
関心の分離(Separation of Concerns)を適用し、フレームワークやDBの変更がビジネスロジックに影響を与えない構造を作ります。
- Presentation Layer (
api/): APIエンドポイント、リクエスト/レスポンス制御(FastAPI等)。 - Domain Layer (
domain/): ビジネスルール・エンティティ(外部依存を持たない純粋なPythonコード)。 - Infrastructure Layer (
infrastructure/): データベース操作(SQLAlchemy等)、外部APIクライアント。

コメント