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?

コード設計学習5 メソッドのまとまり

Posted at

このブログについて

最近システム設計に興味を持ち、特にコード設計について学んだことをまとめます。
自分の今後の戒めも込めて。

メソッドのまとまりについて

見た目は動いているコードでも、命名が適切でないと構造が見えずバグの温床になります。
今回は「命名」に注目して、良いコードと悪いコードを比較してみます。

悪いコード例

Console.WriteLine("ユーザー情報を取得します。");
var users = db.Query("SELECT * FROM Users");
foreach (var u in users)
{
    Console.WriteLine(u.Name);
}
Console.WriteLine("完了しました。");

小さなプログラムなら動きますが、これでは再利用もテストもできません。
コードの“まとまり”を考えずに書くと、変更に弱く、理解しづらい構造になります。

良いコード例

void DisplayAllUsers()
{
    Console.WriteLine("ユーザー情報を取得します。");
    var users = GetAllUsers();
    foreach (var user in users)
    {
        Console.WriteLine(user.Name);
    }
    Console.WriteLine("完了しました。");
}

IEnumerable<User> GetAllUsers()
{
    return db.Query("SELECT * FROM Users");
}

「何をしているか」「どこを直せばいいか」が明確になり、メソッド単位でテストもしやすくなります。

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?