vendredi 2 octobre 2020

Implementing a state pattern

I have an object that based on it's properties, will perform different operations in it's service layer.

Let's say it's a customer with the following states: Registered, RegisteredWithoutContactOnFile, and NoRegistration.

These states are based on properties set on the object. So it would be something like the following:

public class Customer
{
        public Registration Registration {get; set;}
        public string Email {get; set;}
        public int Id {get; set;}
}

Then there would be the CustomerService which does different database operations based on what is entered like such:

public class CustomerService
{
        public void RegisterCustomer(Customer customer)
        {
               if (customer.Registration != null && customer.Id == 0) //Registered without contact

               else if (customer.Registration == null && customer.Id == 0) // No registration/contact
               
               else if (customer.Registration != null && customer.Id > 0) //Registered and contact on file
}

I basically want to get rid of this if/else statement in the service layer and make it a state in my object so that I can more easily test it. Can anyone assist with how I would go about this or if I'm going about this the wrong way? I will say I am interested in the state pattern as I have been working on Finite State Machines for an AI agent but I feel like it makes sense here as well. Perhaps a strategy pattern would work? In short, I'm just trying to get the logic out of the service layer to make it more testable... any insight would be greatly appreciated!

Aucun commentaire:

Enregistrer un commentaire