lundi 10 juillet 2023

How to implement a generic type member of a class?

I have a class CarInfo that holds information of a car and its owner. The owner can be either a known customer (i.e. we can look it up and populate a Customer class) or we only know the name of the customer (in which case we cannot populate a Customer class). I have a Blazor form that exposes the CarInfo class. How do I design this class in respect to the customer info member, which can be either Customer or just First- and last name?

public CarInfo
{
     public Guid Id { get; }
     ...
     public Customer? { get; set; }           // Either this member can be populated
     public string? FirstName { get; set; }   // or the First- and Last name members.
     public string? LastName { get; set; }
     ...
}

What is the best design to handle this? Should I break out Customer and First- and Last name into a new class, e.g. CustomerInfo and handle this polymorphism there?

public CustomerInfo
{
   public Customer? { get; private set; }
   public string? FirstName { get; private set; }
   public string? LastName { get; private set; }

   public CustomerInfo(Customer customer) => Customer = customer;
   public CustomerInfo(string firstName, string lastName)
   {
      FirstName = firstName;
      LastName = lastName;
   }
}

and use it like this?

public CarInfo
{
    public Guid Id { get; }
    ...
    public CustomerInfo { get; set; }           
    ...
}

I'm a little stuck in what best practises or patterns should be referred to here.

Aucun commentaire:

Enregistrer un commentaire