【问题标题】:Null Object Pattern on _base_ values_base_ 值上的空对象模式
【发布时间】:2020-04-20 11:03:11
【问题描述】:

假设我们有以下 DTO 对象,它表示数据库中的记录:

public class UserDto
{
  public int Id { get; set; }  
  public DateTime? ExpireOn { get; set; }
}

所以Id 属性不能为空,ExpireOn 是。我在基于空对象模式实现域对象时遇到问题,因为我不知道如何实现不可为空的ExpireOn 属性。执行此操作的最佳实用方法是什么?

【问题讨论】:

  • 你能进化一下你有什么问题吗?
  • 在实体用户的域对象表示中,我不想拥有可以为空的属性ExpireOn

标签: c# null-object-pattern


【解决方案1】:

我想出了这个解决方案:

public abstract class ExpirationTimeBase
{
    public static ExpirationTimeBase NoExpiration = new NoExpirationTime();
    public abstract bool IsExpired(DateTime now);
}
public class ExpirationTime : NoExpirationTime
{
    public ExpirationTime(DateTime time) => Time = time;
    public DateTime Time { get; }
    public override bool IsExpired(DateTime now) => this.Time < now;
}

public class NoExpirationTime : ExpirationTimeBase
{
    public override bool IsExpired(DateTime now) => false;
}

public class User
{
    public User(string id, ExpirationTimeBase expireOn)
    {
        Id = id ?? throw new ArgumentNullException(nameof(id));
        ExpireOn = expireOn ?? throw new ArgumentNullException(nameof(expireOn));
    }

    public string Id { get; set; }
    public ExpirationTimeBase ExpireOn { get; set; }
}

问题是它是否可以变得更好?

【讨论】:

    【解决方案2】:

    您可以在 Tor 中使用 Nullable 并检查是否为空。

    public class User
    {
        public User(int? id, Datetime? expireOn)
        {
            if(id == null)
            {
               throw new ArgumentNullException(nameof(id));
            }
    
            if(expireOn == null)
            {
               throw new ArgumentNullException(nameof(expireOn));
            }
    
            Id = id.Value
            ExpireOn = expireOn.Value;
        }
    
        public int Id { get; set; }
        public Datetime ExpireOn { get; set; }
    }
    

    【讨论】:

    • 但是我怎么知道用户是否有过期时间?
    • 你能解释一下吗?空过期是不是一个有效值?
    • 用户没有过期时间是有效的。您可以将 is 表示为 null 值,但 Null Object Pattern 禁止 null 值。
    • 您可以使用default(datetime) 作为空日期。现在是 1970 年 1 月 1 日或 1900 年 1 月 1 日。如果用户有这个过期值,意味着他没有过期日期。
    猜你喜欢
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    相关资源
    最近更新 更多