0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PGスタイルシリーズ:共通化の妙

Posted at
1 / 8

「関数化=共通化」ではない

  • 引数のない関数
  • フラグを受け取り関数内で分岐している関数

これらは関数化の効果を半減させているかもしれない!


共通化より部品化

  • 小さい部品の組み合わせで大きな部品を作る
  • 最も大きな部品がイベントハンドラやリクエストハンドラ、main関数

分岐への対処

  • 同じ条件分岐がたくさん現れたら作りのまずさを疑うべき
  • フラグによる分岐はなるべく最も大きな部品の根元で解決する

関数内での分岐

  • せいぜい1~2個の分岐で済ませる
     (それ以上になるときは更に関数を分離できないか、と考える)

※2個の独立した分岐があったとして、組み合わせは4つ。3個だと・・・?
 →分岐は怖い!


具体例:メニュー操作

void OnMenuClick(MenuKind kind)
{
    switch (kind)
    {
        case MenuKind.Add:
            // 何かの処理・・・
            DbOperation(kind);
            break;
        case MenuKind.Edit:
            // 何かの処理・・・
            DbOperation(kind);
            break;
        case MenuKind.Delete:
            // 何かの処理・・・
            DbOperation(kind);
            break;
        default:
            throw new NotImplementedException();
    }
}

void DbOperation(MenuKind kind)
{
    switch (kind)
    {
        ...
    }
}

具体例:メニュー操作、改善

void OnMenuClick(MenuKind kind)
{
    switch (kind)
    {
        case MenuKind.Add:
            // 何かの処理・・・
            InsertDb();
            break;
        case MenuKind.Edit:
            // 何かの処理・・・
            UpdateDb();
            break;
        case MenuKind.Delete:
            // 何かの処理・・・
            DeleteDb();
            break;
        default:
            throw new NotImplementedException();
    }
}

void InsertDb()
{
    ...
}
...

心がけ(コツ)

感覚的な話ではあるが・・・

  • 部品化が目的の関数に処理の流れを持ち込まない
  • 処理の流れは根元の関数に書く
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?