lundi 27 janvier 2020

Extracting private methods to separate class to allow testing

Below is a skeleton Java code that invokes following methods :

  private void applyRule1(List<Data> dl) {
    System.out.println("Apply Rule 1");
  }

  private void applyRule2(List<Data> dl) {
    System.out.println("Apply Rule 2");
  }

  private Boolean isDuplicateType(Data data, List<Data> dl) {
    Set<String> l = dl.stream().map(Data::getType).collect(Collectors.toSet());
    return l.contains(data.getType());
  }

I plan to extract the above 3 methods to a separate interface/class and change their visibility to public. The new interface will be called Rule with the implementation class called RuleImpl. I'll add a new unit test class to test each of the three methods. Is this a good design ? Is there a design pattern that I can make use of that matches the result I wish to achieve ?

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class Main {

  private class Data {

    private String name;
    private String type;

    public Data() {

    }

    public Data(String name, String type) {
      this.name = name;
      this.type = type;
    }

    public String getType() {
      return this.type;
    }

    public List<Data> getData() {
      List<Data> dl = new ArrayList<Data>();
      dl.add(new Data("name1", "type1"));
      dl.add(new Data("name2", "type2"));

      return dl;
    }

  }

  private void process() {
    List<Data> dl = new Data().getData();

    if (!this.isDuplicateType(new Data("name2", "type9"), dl)) {
      this.applyRule1(dl);
      this.applyRule2(dl);
    } else {
      System.out.println("Duplicate found");
    }

    if (!this.isDuplicateType(new Data("name2", "type2"), dl)) {
      this.applyRule1(dl);
      this.applyRule2(dl);
    } else {
      System.out.println("Duplicate found");
    }

  }

  private void applyRule1(List<Data> dl) {
    System.out.println("Apply Rule 1");
  }

  private void applyRule2(List<Data> dl) {
    System.out.println("Apply Rule 2");
  }

  private Boolean isDuplicateType(Data data, List<Data> dl) {
    Set<String> l = dl.stream().map(Data::getType).collect(Collectors.toSet());
    return l.contains(data.getType());
  }

  public static void main(String args[]) {

    Main t = new Main();
    t.process();

  }
}

Aucun commentaire:

Enregistrer un commentaire