samedi 4 avril 2020

Design Pattern when base class supports new method overload

The base class (in the base lib, not owned by me), has upgraded its code and add a new method support additional use cases-

Existing method signature in base class-

public void Alert(string someAlertString);

With the new release, the base class is supporting a list of AlertObject (at some point the base class might depricate the string alert)

public void Alert(List<Alert> alertObj);

On my side of the code, I have the alert in multiple places, like this -

base.Alert("This is a warning message.")

I want to update all these alert statements to use an AlertObject (and I want to add category only to the new alerts, old alerts should have only messages):

public class Alert {
   public string message {get;set;}
   public string category {get;set;}
}

One way to do this is to define a helper class which takes the existing string and return a List of AlertObject -

public static class AlertHelper {
   public static List<Alert> getNewAlert(string msg, string category="Not Defined") {
      Alert a = new Alert();
      a.message = msg;
      a.category = category;
      return List<Alert>() { a };
   }
}

Then I can replace all the instance of my Alert with -

base.Alert(AlertHelper.getNewAlert("This is a warning message."))

The one problem I see here is that as the Alert class (in a separate lib) keeps adding properties to support more detailed alerts, I need to keep updating my helper class, and potentially all the places where I call helper class.

The way I have written it works, but I feel tomorrow if I add a new alert which takes new property called 'description', then I have two options-

1) Provide constructor overload and add a new constructor that in the description -

public static List<Alert> getNewAlert(string msg, string des, string category="Not Defined")

2) Update the existing constructor.

I was wondering if there is a better way to design this.

Aucun commentaire:

Enregistrer un commentaire