lundi 14 novembre 2016

Most efficient way to remove duplicated code from multiple strategies

We have 3 types of attributes in our project: CategoryAttribute, ProductAttribute and ProductTypeAttribute. These are outside of our control as they come from autogenerated classes and may contain attribute values of different types e.g. text, number or image. Now, each attribute has its own strategy to retrieve attributeValue. For simplicity, let's assume that all 3 of them have TextStrategy, NumberStrategy and ImageStrategy.

Example strategy:

@Component
public class CategoryImageAttributeStrategy implements CategoryAttributeStrategy {

  @Override
  public boolean isApplicable(CategoryAttribute attribute) {
      return attribute.getImage() != null;
  }

  @Override
  public Object getAttributeValue(CategoryAttribute attribute) {
      //return attribute value here 
      //may be different or may be the same 
      //for ProductImageAttributeStrategy and ProductTypeImageAttributeStrategy
  }

}

While getting image value may be different for all of them, getting text value is the same and we end up with 3 classes of almost the same code and I really really really don't like duplicating code.

I thought about creating an abstract class/default interface for each strategy type e.g. DefaultTextStrategy that all 3 text strategies would inherit from and either use default code provided higher or override it with own implementation, however I'm not really satisfied with this approach as it requires to create even more classes for such a simple task.

Maybe is it even possible to combine strategies of the same type (e.g. image) into one?

I would really like to hear what more experienced folks have to say in this matter as I would like to learn and improve.

Thanks in advance for your time.

Aucun commentaire:

Enregistrer un commentaire