✍️

if文が増えてきたら考えたい、多態(ポリモーフィズム)を使った設計の考え方

に公開

今日は、多態(ポリモーフィズム)を使った設計について学んだので、
自分なりの理解と気づきを整理してみようと思います。

多態(ポリモーフィズム)とは

多態とは、
同じ型(親クラスやインターフェース)として扱っているにも関わらず、
実際の振る舞いが実装クラスごとに異なることを指します。

if文やswitch文で状態を分岐する処理が増えてくると、
条件分岐が複雑になり、可読性や変更耐性が落ちやすくなります。
そういった場面で選択肢になるのが、多態を使った設計です。

悪い例:条件分岐が増えやすいコード

実際のコードを用いて説明してみます
例として、商品の送料計算を考えてみます。

//悪い例

int priceItem = 1000;
int count = 2;
int shippingFee = 500;
int shippingFee2 = 300;

int totalMoney = priceItem * count;

if (totalMoney < 3000)
{
    totalMoney += shippingFee;
}
else if (totalMoney < 5000)
{
    // 送料なし
}
else if (totalMoney < 10000)
{
    totalMoney += shippingFee2;
}
else
{
    // 送料無料
}

一見シンプルですが、
送料区分が増えていくと else if がどんどん増え、
仕様変更にも弱くなってしまいます。

メソッドとして抽出

まずは小さな改善として、送料ロジックをメソッドに切り出します。

int GetShippingFeeForLowPrice()
{
    return 500;
}

int GetShippingFeeForMiddlePrice()
{
    return 300;
}



if (totalMoney < 3000)
{
    totalMoney += GetShippingFeeForLowPrice();
}
else if (totalMoney < 5000)
{
    // 送料なし
}
else if (totalMoney < 10000)
{
    totalMoney += GetShippingFeeForMiddlePrice();
}
else
{
    // 送料無料
}

このように送料ロジックをメソッドにすると少し可読性が上がります。
しかしまだまだ条件分岐が多く可読性がいいとは言えません。

多態を使って整理する

次に、多態を使って送料計算ロジックを整理してみます。

多態では、条件ごとの振る舞いをクラスとして分離し、
共通のインターフェースとして扱います。

//インターフェース
interface IShippingFeeRule
{
    bool IsMatch(int totalMoney);
    int GetFee();
}

・IsMatch:このルールが適用されるか
・GetFee:適用された場合の送料
という役割を持たせています。

各送料ルール

//合計3000円未満
class Under3000Rule : IShippingFeeRule
{
    public bool IsMatch(int totalMoney)
        => totalMoney < 3000;

    public int GetFee()
        => 500;
}

//合計3000円 ~ 5000円未満(送料なし)
class Under5000Rule : IShippingFeeRule
{
    public bool IsMatch(int totalMoney)
        => totalMoney >= 3000 && totalMoney < 5000;

    public int GetFee()
        => 0;
}

//合計5000円 ~ 10000円未満
class Under10000Rule : IShippingFeeRule
{
    public bool IsMatch(int totalMoney)
        => totalMoney >= 5000 && totalMoney < 10000;

    public int GetFee()
        => 300;
}

//合計10000円以上(送料無料)
class Over10000Rule : IShippingFeeRule
{
    public bool IsMatch(int totalMoney)
        => totalMoney >= 10000;

    public int GetFee()
        => 0;
}
//送料計算クラス
class ShippingFeeCalculator
{
    private readonly List<IShippingFeeRule> _rules;

    public ShippingFeeCalculator()
    {
        _rules = new List<IShippingFeeRule>
        {
            new Under3000Rule(),
            new Under5000Rule(),
            new Under10000Rule(),
            new Over10000Rule()
        };
    }

    public int Calculate(int totalMoney)
    {
        return _rules
            .First(rule => rule.IsMatch(totalMoney))
            .GetFee();
    }
}
//使う側のコード
int priceItem = 1000;
int count = 2;

int totalMoney = priceItem * count;

var calculator = new ShippingFeeCalculator();
totalMoney += calculator.Calculate(totalMoney);

利用する側は「どの条件か」を意識せず、
送料計算を一行で書けるようになりました。

なぜ多態を使うと良いのか

・条件ごとのロジックをクラスに分離できる
・新しい送料ルールはクラスを追加するだけで対応できる
・if / switch を増やさずに拡張できる
・利用側のコードがシンプルになる

しかし、やりすぎても逆に条件がわかりづらくなり可読性が落ちてしまうため使い所の見極めは
必要になりそうです。

まとめ

・多態は条件分岐が増えがちな処理に向いている

・ただし、すべてを多態にすれば良いわけではない

・場合によってはメソッド抽出だけで十分なケースもある

・「ifが増えてきたら検討する」くらいがちょうど良い

自分もまだ使いどころを探っている段階なので、
「ここはこうした方がいい」などあればぜひ教えてください 🙏

Discussion