0

In a project, certain related classes can be grouped together in one package. But some other useful classes are not related to any other class and so cannot be put into a package with any other classes.

A StackOverflow answer I read says that it isn't a bad practice to put such classes in their own packages (just one class in a package), but somehow I feel this is not the best way to go.

So in such situations, what should be done with these unrelated classes?

closed as primarily opinion-based by Robert Harvey, user40980, user53019, gnat, Bart van Ingen Schenau Nov 7 '14 at 9:59

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.

2

Typically they should go in a util or misc package. But for example if you have a class DatabaseUtil it can go directly under db, supposing there you also have subpackages db.model, db.dao etc. for other database related classes.

I don't find it at all suitable to have these classes each in its own package (that's not what packages are designed for).

  • While there are valid uses for "util" classes, often this is a code smell that something needs to be refactored. – user22815 Nov 6 '14 at 18:13
  • @Snowman I strongly disagree; most libraries have such packages: JDK - java.util.*, Spring Core - org.springframework.util.*, Guava - com.google.common.util.*. – m3th0dman Nov 6 '14 at 19:30
  • 1
    I am not talking about packages, I am talking about classes. java.util for example contains reusable classes, not classes with static methods. The reason for util classes often is to provide useful functions on objects such as String where you are not able to modify the class and it is missing important functionality. – user22815 Nov 6 '14 at 19:33
  • There are plenty of *Utils or *s classes just with static methods in the libraries: in JDK: Objects, Collections, Executors etc.; in Spring: RefelectionUtils, ClassUtils etc. – m3th0dman Nov 6 '14 at 20:04
  • If the core classes had been thought out better, those would not be needed. They are a necessary evil because the core Java classes do not do enough. My argument is that if you are writing util classes for your own classes, take those static methods and make them instance methods of the classes on which they operate. – user22815 Nov 6 '14 at 20:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.