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:
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.
Minimize the variable's scope A good practice to increase the readability of variables is to keep them in the smallest scope. The middle and middleItem variables are declared at the beginning of the function body.
The following are examples of valid variable names: age, gender, x25, age_of_hh_head. The following are examples of invalid variable names: age_ (ends with an underscore);
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.
It is best practice to use dependency injection and pass all the resources you need rather than having classes find what they want.
Using global variables is simpler to start with, but as your application grows and you want to use unit tests, these are a real pain as it becomes more difficult to manage and maintain these.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With