概要
SOLID原則について調査したシリーズです
今回はSingle responsibility principle(単一責任の原則)について調査してみました
※以降、単一責任の原則と記載します
本題
原則
以下の原則があります
- モジュールを変更する理由はたったひとつだけであるべきである
言葉を分解して説明
- モジュール: 一つの部品。複数のクラスや関数をまとめたもの(ファイルやフォルダ)
2つの原則を実現する
Step1: モジュールを変更する理由はたったひとつだけであるべきである
図を用いた抽象的な説明
例えば、会社でバックオフィス系の多くを一人で実施できているHogeさん
図を見るとHogeさんは多くの業務知識に依存していることがわかります
しかし、国レベルでのルール変換や会社独自のルール変換が多いため、常に各業務の知識をアップデートする必要があり、大変です
つまり、多くの要因がHogeさん(モジュール)の知識をアップデートする理由となっている状態です
そうすることで、該当の知識をアップデートする人を制限することができます
つまり、担当業務をする人の知識(モジュール)をアップデート(変更)する理由が、該当の担当範囲だけに絞れたことになります
具体例
ユーザーの処理を管理するUserクラスで考えます
単一責任の原則に反している場合
bad_example.py
class User:
def __init__(self, name, age, mail_address)
self.name = name
self.age = age
self.mail_address = mail_address
def save_user(self, db_session)
db_session.save_user({"name": name, "age": age, "mail_address": mail_address})
def send_mail(self, sender, send_mail_address, text)
context = _create_context(text)
sender.send(from=self.mail_address, destination=send_mail_address, context)
def _create_context(self, base_text)
# メールの文章を作る処理
return context
user = User(name="tom", age=16, mail_address="tom@hoge.com")
user.save_user(db_session=db)
user.send_mail(sender=mail_serveice, text="初めましてトムです")
- データベース処理の内容を変更しようとすると、save_userを修正する必要あり
- メール処理も同様。メールの文章を作る処理とかを修正したいとなるとプライベート関数を修正する必要あり
単一責任の原則に適応できている場合
database.py
class UserDatabase:
def save_user(user)
email.py
class EmailService:
def send_mail(user, text)
def _create_context(base_text)
# メールの文章を作る処理
return context
good_example.py
class User:
def __init__(self, name, age, mail_address)
self.name = name
self.age = age
self.mail_address = mail_address
user = User(name="tom", age=16, mail_address="tom@hoge.com")
db = UserDatabase()
db.save_user(user)
mail_service = EmailService()
mail_service.send_mail(user, "初めましてトムです")
- 上記のように役割を分ける
- データベースモジュールを変更したい理由はユーザー情報を保存する理由だけ
- メール送信モジュールを変更したい理由はメール送信を処理を変更したい理由だけ