roundar
roundar

Reputation: 1713

Making mutable variables accessible across many, otherwise-unconnected objects

In Java, how can I make a mutable object accessible across many, otherwise-unconnected objects without either A) Creating mutable static fields/methods or B) Passing the same object down many layers, OR which of these is considered best practice for maintainability, readability, etc.?

Two cases that come up often for me in desktop applications:

User/Session data in a GUI. A user signs in at the start of an application, later I will need the user name in a JLabel inside a JPanel inside another panel inside another panel inside a JFrame. It seems ridiculous to pass my session data into the constructor of five or six layers deep, but I hate the idea of an object that holds this information in static variables being accessed all over the place.

Database access. I have one object to access a database and all sorts of objects then need to access the database. These classes are basically unrelated and need the database for different reasons so I resort to a Databases.thisOne().query("...").

Upvotes: 4

Views: 146

Answers (1)

Suresh Atta
Suresh Atta

Reputation: 122008

This question surely an objective question, this can lead a debate of language/framework feature war.

Coming to the actual question, the cases you are pointing here are valid and the counter part to that question answers only with static data. You cannot simply decline the fact that static is the only way here. They are meant to it.

Understanding Class members

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

Let me just give you an example about which you mentioned. That is session. Do you ever go through the source code of session management in containers? All the attributes and values are being stored in a static Hashmap on the server to give them access across the instances (requests,request context, etc ).

Upvotes: 3

Related Questions