lundi 5 décembre 2022

How to avoid code duplication in Java having one line difference in methods

I have following classes:

public class A {
   private List<B> list;

   ...

   public String findCreated() {
      return list.stream()
                 .
                 .some filter operations
                 .
                 .filter(b -> b.isCreated())
                 .
                 .some mapping
   }

   public String findRegistered() {
      return list.stream()
                 .
                 .some filter operations
                 .
                 .filter(b -> b.isRegistered())
                 .
                 .some mapping
   }
}

public class B {
    private boolean created;
    private boolean registered;

    ...

    public boolean isCreated() {
        return created;
    }

    public boolean isRegistered() {
        return registered;
    }

    ...
}

I would like to refactor this code and have one find method in class A, because find methods differ by only one line. Do you know how to avoid duplicating code in this example?

Would any design pattern solve this problem?

Aucun commentaire:

Enregistrer un commentaire