0

Can I use a utility class like this?

public final class ProfessorDirectory {
    private static Map<String, Professor> directory = new HashMap<>();

    private ProfessorDirectory() {
        throw new IllegalStateException("Utility Class");
    }

    static void addProfessorsFromDescription(String description) {
        String regex = "(?<=\\n).*   .*(?=\\n)";
        Matcher m = Pattern.compile(regex).matcher(description);
        while (m.find()) {
            String professorName = Professor.formater(m.group(0));
            directory.put(professorName, new Professor(professorName));
        }
    }

    public static Professor get(String firstName, String lastName) {
        return directory.get(Professor.formater(firstName, lastName));
    }

}

I used this to create a library in which you can retrieve a teacher's planning.

Exemple of utilisation:

Planning professorPlanning = schedules.getPlanningOf(ProfessorDirectory.get("Jack", "Sticky"));

The ProfessorDirectory is initialized internally, and should never be initialized by the user.

ThrowsError
  • 1,169
  • 1
  • 11
  • 43
  • 1
    What will happen if two,three, or four addProfessorsFromDescription are called at the same time for the same professor? And if you add a delete method? - hint: if a map is shared, synchronize it. – aran Feb 13 '21 at 12:21
  • @aran For the moment it's never called several times because is utilized in a Singleton class. But if that happens I think I would add a Synchronized in the add method. Do you think it's a good solution ? – ThrowsError Feb 13 '21 at 12:29

1 Answers1

1

There are a few disadvantages to this approach, that is, the approach of having static data and methods.

  1. You can never have more than one ProfessorDirectory, even if you find it would be useful to have several.

  2. It is difficult to test clients of ProfessorDirectory, because they must use the real code instead of being able to mock an interface.

  3. You rule out using some useful patterns. For instance, you can't write a caching proxy that implements a ProfessorDirectory interface and wraps an arbitrary implementation of that interface.

Overall this is a bad approach.

ThrowsError
  • 1,169
  • 1
  • 11
  • 43
tgdavies
  • 10,307
  • 4
  • 35
  • 40
  • I voluntarily create this class to have just one `ProfessorDirectory` which contains all the teachers in the school. I tested this class here: https://github.com/DevLab-umontp/Librairie-Java-EDT/blob/main/src/test/java/fr/umontp/edt/RepertoireProfesseurTest.java . Why create a caching proxy with a class that only uses a Map? – ThrowsError Feb 13 '21 at 12:45
  • 4
    Your approach may be absolutely fine for your application, but I don't think it "follows good code practice within Java". – tgdavies Feb 13 '21 at 12:48