jeudi 4 février 2021

Alternatives to pass-by-reference updates on list in Java

I have a class that has one or more input list and it needs to process and update other lists which are scoped outside of the class. What can be a good pattern to use here? I've tried the following two patterns here:

  1. Update directly by using pass-by-reference
  2. Using callbacks to let the caller handle how they want to deal with the update

Examples

  1. Using direct update
public class SomeClass {
  public void process(List<String> inputList, List<StringContainer> errorContainerList, List<String> validList) {
    for (String str : inputList) {
      if (someCondition) {
        validList.add(str);
      } else {
        errorContainerList.add(new StringContainer(str, new SomeError()));
      }
    }
  }
}

void someCaller(List<String> inputList) {
    List<String> validList = new ArrayList<>();
    List<StringContainer> errorContainerList = new ArrayList<>();

    SomeClass obj = new SomeClass();
    obj.process(inputList, errorContainerList, validList);

    // Similarly,
    validList.remove(...);
    errorContainerList.add(...);
}
  1. Using callbacks
public interface StringErrorHandler {
    void handle(String str, SomeError error);
}

public interface ValidInputHandler {
    void handle(String str);
}

public class SomeClass {
  public void process(List<String> inputList, StringErrorHandler errorHandler, ValidInputHandler validInputHandler) {
    for (String str : inputList) {
      if (someCondition) {
        validInputHandler.handle(str);
      } else {
        errorHandler.handle(str, new SomeError());
      }
    }
  }
}

void someCaller(List<String> inputList) {
    List<String> validList = new ArrayList<>();
    List<StringContainer> errorContainerList = new ArrayList<>();

    SomeClass obj = new SomeClass();
    obj.process(inputList, new StringErrorHandler() {
        
        @Override
        public void handle(String str, SomeError error) {
            errorContainerList.add(new StringContainer(str, error));
        }
    }, new ValidInputHandler() {
        
        @Override
        public void handle(String str) {
            validList.add(str);
        }
    });

    // Similarly,
    validList.remove(...);
    errorContainerList.add(...);
}

Aucun commentaire:

Enregistrer un commentaire