個々のモジュールを変更する理由がたったひとつだけになるように、ソフトウェアシステムの構造がそれを使う組織の社会的構造に大きな影響を受けるようにする。
モジュールはたったひとつのアクターに対して責務を負うべきである。
Before
class Order:
def __init__(self) -> None:
self.items = []
self.quantities = []
self.prices = []
self.status = 'open'
def add_item(self, name: str, quantity: int, price: int) -> None:
self.items.append(name)
self.quantities.append(quantity)
self.prices.append(price)
def total_price(self) -> int:
total = 0
for i in range(len(self.prices)):
total += self.quantities[i] * self.prices[i]
return total
def pay(self, payment_type: str, security_code: str) -> None:
if payment_type == 'debit':
print('Proccessing debit payment type')
print(f'Verifying security code: {security_code}')
self.status = 'paid'
elif payment_type == 'credit':
print('Processing credit payment type')
print(f'Verifying security code: {security_code}')
self.status = 'paid'
else:
raise Exception(f'Unknown payment type: {payment_type}')
order = Order()
order.add_item('Keyboard', 1, 50)
order.add_item('SSD', 1, 150)
order.add_item('USB cable', 2, 5)
print(order.total_price())
order.pay('debit', '0372846')
After
class Order:
def __init__(self) -> None:
self.items = []
self.quantities = []
self.prices = []
self.status = 'open'
def add_item(self, name: str, quantity: int, price: int) -> None:
self.items.append(name)
self.quantities.append(quantity)
self.prices.append(price)
def total_price(self) -> int:
total = 0
for i in range(len(self.prices)):
total += self.quantities[i] * self.prices[i]
return total
class PaymentProcessor:
def pay_debit(self, order: Order, security_code: str) -> None:
print('Processing debit payment type')
print(f'Verifying security code: {security_code}')
order.status = 'paid'
def pay_credit(self, order: Order, security_code: str) -> None:
print('Processing credit payment type')
print(f'Verifying security code: {security_code}')
order.status = 'paid'
order = Order()
order.add_item('Keyboard', 1, 50)
order.add_item('SSD', 1, 150)
order.add_item('USB cable', 2, 5)
print(order.total_price())
processor = PaymentProcessor()
processor.pay_debit(order, '0372846')