forax/write_your_own_java_framework

Why find dependencies for a list of classes instead of one class?

wlnirvana opened this issue · 2 comments

This might be just a matter of style, but I'm wondering if the logic would be clearer if findDependenciesInOrder is refactored as a call to a function that find dependencies for just one class. Something like the following:

static Set<Class<?>> findDependenciesInOrder(List<Class<?>> classes) {
  return classes.stream()
      .map(AnnotationScanner::findAllDependenciesInOrderForClass)
      .flatMap(List::stream)
      .collect(Collectors.toCollection(LinkedHashSet::new));
}

static List<Class<?>> findAllDependenciesInOrderForClass(Class<?> clazz) {
  var set = new LinkedHashSet<Class<?>>();
  var visited = new HashSet<Class<?>>();

  if (isAProviderClass(clazz)) {
    visited.add(clazz);
    for (var dependency : dependencies(clazz)) {
      addDependenciesFirst(dependency, set, visited);
    }
    set.add(clazz);
  }

  return new ArrayList<>(set);
}
forax commented

If several classes have the same set of dependencies, you will visit the dependecies (and the dependencies of dependencies) several times, the set of visited classes has to be shared between the calls of findAllDependenciesInOrderForClass

That makes sense. Thanks.