Java how to good practice : Map in Utility Class

696 views Asked by At

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.

1

There are 1 answers

2
tgdavies On BEST ANSWER

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.