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:
- Update directly by using pass-by-reference
- Using callbacks to let the caller handle how they want to deal with the update
Examples
- 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(...);
}
- 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