gpt4 book ai didi

c# - 许多添加/更改方法和构造函数重载是 DDD 的结果吗?

转载 作者:太空宇宙 更新时间:2023-11-03 19:20:12 24 4
gpt4 key购买 nike

我有一个类:

    public class Person
{
public string FirstName { get; private set; }
public string LastName { get; private set; }
public string Email { get; private set; }
public string Telephone { get; private set; }
public Address Address { get; private set; }

public Person(string firstName, string lastName)
{
//do null-checks
FirstName = firstName;
LastName = lastName;
Address = new Address();
}

public void AddOrChangeEmail(string email)
{
//Check if e-mail is a valid e-mail here
Email = email;
}

public void AddOrChangeTelephone(string telephone)
{
//Check if thelephone has correct format and valid symbols
Telephone = telephone;
}

public void AddOrChangeAdress(Address address)
{
Address = address;
}

构造函数中没有的属性是可选的,即此人不需要电子邮件、地址或电话。但是,我想给类的用户一个创建对象的机会,而不必先提供所需的信息,然后再找出使用什么方法来添加信息。

问题:

  1. 创建 3 个额外的重载来为他们提供该选项是否正确?
  2. 我应该允许可选属性的公共(public) setter 并在那里进行验证吗?
  3. 如果这个人结婚并更改了姓氏,我是否需要其他方法来更改姓氏,或者我是否也应该将此 setter 公开,并且只在构造函数中要求它们?

最佳答案

  1. 没有。
  2. 公开。

假设您将在 AddOrChange 方法中包含更多代码,例如格式化逻辑或验证,那么我将执行以下操作。否则,我将完全摆脱 AddOrChange 方法:

public class Person
{
private string _email = string.empty;
private string _telephone = string.empty;
private Address _address = new Address();

public string FirstName { get; set; }
public string LastName { get; set; }
public string Email {
get { return _email }
set { AddOrChangeEmail(value); }
}
public string Telephone {
get { return _telephone;}
set { AddOrChangeTelephone(value); }
}
public Address Address {
get { return _address; }
set { AddOrChangeAddress(value); }
}

public Person(string firstName, string lastName)
{
//do null-checks
FirstName = firstName;
LastName = lastName;
}

private void AddOrChangeEmail(string email)
{
//Check if e-mail is a valid e-mail here
_email = email;
}

private void AddOrChangeTelephone(string telephone)
{
//Check if thelephone has correct format and valid symbols
_telephone = telephone;
}

private void AddOrChangeAddress(Address address)
{
_address = address;
}
}

要使用此类,您可以执行以下任一操作:

Person p = new Person("Tom", "Jones");
p.Telephone = "9995551111";

Person p = new Person("Tom", "Jones") { Telephone = "9995551111", Email="spamme@ms.com" }

关于c# - 许多添加/更改方法和构造函数重载是 DDD 的结果吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12978381/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com