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?

コード設計学習3 データクラスの設計

Last updated at Posted at 2025-10-30

このブログについて

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

データクラスの設計について

単なるデータの入れ物(DTO)は、一見シンプルに見えてもロジックの無法地帯を生みやすく、バグや不整合の原因になります。
他のクラスが勝手にデータを操作し、「どこで何が変わるのか」が不透明になるためです。

悪いコード例

class UserData
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}

このようなクラスは、誰がどのタイミングで値を変えても自由です。
結果として、不整合・バグ・メンテ不能な状態を招きやすくなります。

良いコード例

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

    public void UpdateEmail(string newEmail)
    {
        if (!IsValidEmail(newEmail))
            throw new ArgumentException("無効なメールアドレスです。");
        Email = newEmail;
    }

    private bool IsValidEmail(string email)
    {
        return email.Contains("@");
    }
}

データと振る舞いを一体化させることで、データを正しく扱う責任がクラス内に閉じ込められます。
これにより、構造が守られ、変更時の破壊リスクを最小化できます。

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?