Is it good programming practise, when dealing with multiple classes that need the same instance of variables, to create one central one?
chatWindow.variables.username = userField.getText();
For example:
- I have a class with a set amount of variables
- I have another class that needs the same variables
- And another that needs the same variables as the first
So I have three classes that all use the same instance of variables
I only create the variable class instance using the first class (1)
I access these variables using classes (2), (3) through the class (1)
Example:
(while in classTwo()):
classOne.variableClass.VariableName = false;
EDIT: In basic form, my question is if it is OK to make a central ‘variable class’ and use other classes to access the same isntance of it through a main class.
I know my question is hard to understand but Im sure there is another, easier way. I tried passing the same instance of the first class through the constructor of the second and third classes but my solution some how seemed simpler.
This smells like feature envy… Sounds like something’s wrong with your model when doing that.
If there’s a group of variables that need to be changed in multiple classes, it probably should become an object (probably even an entity). But you should consider that if you need to change these values in other classes, you might need to put some logic in that same class (to do validation checks and such).
Having an extra class just to keep variables is usually considered a code smell, called anemic domain. However there are cases that do call for it, and it might be a matter of taste anyway. In that case, your class is nothing but a glorified struct.