lundi 19 septembre 2022

Replace ordered if condition with design pattern

I've a legacy class with lots of if conditions, like:

public MyType methodWithIfs() {
  if (condition1) {
    return new MyType(param1);
  }

  if (condition2) {
    return new MyType(param2);
  }
  ....
}

Every if condition returns a type of MyType.

Also there is a order in which these conditions are mentioned. Two conditions can be true but only first that matched the criteria should be executed based on order.

I was thinking of replacing these conditions with Conditional Dispatcher with Command design pattern

Since there is an order to be maintained, instead of using HashMap<Boolean, MyType>, I was thinking of using LinkedHashMap<Boolean, MyType>.

But this seems dodgy. Is there any cleaner way I can replace these conditions?

Thanks!

Aucun commentaire:

Enregistrer un commentaire