Null Object Pattern on _base_ values

95 Views Asked by At

Let's say we have following DTO object which is representation of a record in a database:

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

So Id property is not nullable and ExpireOn is. I have a problem to implement Domain objects based on Null Object Pattern, because I don't know how to implement not nullable ExpireOn property. What are best practical ways to do this?

2

There are 2 best solutions below

0
Rok On

I came up with this solution:

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; }
}

The question is if it can get any better?

4
Ygalbel On

You can use Nullable in Ctor and check there is null or not.

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; }
}