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?

コード設計学習7 成熟したクラスへ成長させる設計術

Last updated at Posted at 2025-10-31

このブログについて

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

成熟したクラスへ成長させる設計術について

最初から完璧なクラスは作れません。
最初は「貧血気味」でも、責務を明確化し、自己完結的に成長させていくことが重要です。

悪いコード例

class User
{
    public string Name;
    public string Email;
}

良いコード例

class User
{
    public string Name { get; private set; }
    public string Email { get; private set; }

    public User(string name, string email)
    {
        if (string.IsNullOrWhiteSpace(email) || !email.Contains("@"))
            throw new ArgumentException("不正なメールアドレスです。");

        Name = name;
        Email = email;
    }

    public void ChangeEmail(string newEmail)
    {
        if (!newEmail.Contains("@"))
            throw new ArgumentException("不正なメールアドレスです。");

        Email = newEmail;
    }
}

クラスに「不変条件の維持」「自己防衛」のロジックを持たせると、外部からの誤使用を防ぎ、構造が強固になります。

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?