用必须存在的属性初始化类的最佳方法

时间:2019-05-24 06:04:34

标签: c# software-design

示例类

public class Company {
    public Details Details { get; set; }
    public List<Employeee> Employees { get; set; }

    public Company() { 
    }
}

public class Details {
    public string Name { get; set; }
    public string Url { get; set; }

    public Details() {
    }
}

在代码中的某处使用...

var c = new Company();
c.Details = new Details();
c.Details.Name = "Example";
c.Details.Url = "http://example.org/";

没有细节就没有公司。

我曾经以为是

  • 更改Company构造函数以自动创建新的详细信息
  • 更改详细信息设置,以确保其不设置为空

这似乎是一个普遍的问题,我想知道是否存在处理它的标准方法,这将导致可测试的类。我不确定要搜索什么。

1 个答案:

答案 0 :(得分:2)

如果我对您的理解正确,我认为最好的方法是仅创建一个以Details作为参数的构造函数。

示例:

public class Company
{
    public Details details { get; set; }
    public List<Employeee> Employees { get; set; }

    // You can not initialize the Company
    // class witouth passing the company details
    public Company(Details details)
    {
        this.details = details;
    }
}

public class Details
{
    public string Name { get; set; }
    public string URL { get; set; }

    // You can not initialize the details
    // without a Name and URL
    public Details(string Name, string URL)
    {
        // If the validation fails, return
        if (!Validation(Name, URL)) return;

        // Inserts the parameter
        this.Name = Name;
        this.URL = URL;
    }

    private bool Validation(string Name, string URL)
    {
        // If string is empty, return false
        if (string.IsNullOrWhiteSpace(Name)) return false;
        // If string is empty, return false
        else if (string.IsNullOrWhiteSpace(URL)) return false;
        // else return true
        else return true;
    }
}
相关问题