Search code examples
javastatic-classes

Should I make my class Application static?


I'm building a Java application. I have this class called Application, which contains arraylists of users objects and groups objects. Inside of the classes User and Group, some methods (such as sending a message to another user) needs to get another User object searching by email, username, or another field within the arraylist of users in the class Application. Since Application is the container class, I don't want to have instances of it inside the contained classes Users or Groups.

As I just going to have one instance of the Application class, I was thinking to make this class and its attributes static in order to be able to access the searching methods from classes User and Group, but I'm also not sure about if it's a good idea or a proper use of static classes. Do you think it's right or there's a better option? Thanks in advance

Edit* Another option is to make static the attributes ArrayList of users and groups, since they have to be the same for all possible instances of Application. Do you think that's better?


Solution

  • Using final classes that have static variables and functions is one way of doing things. But calling such a class "Application" might not be the best choice.

    Final classes allow you to access these variables and/or functions from all your other classes without creating multiple instances just to get this static data.

    But what you should consider is how "static" the data actually is. If part of the variables are not-so-static like a list of users that may grow over time, it could be better to just use for example a UserFactory that itself is static and manages a class user and an "arraylist[User] users" which you can then work with by calling UserFactory.get(), set(), update().