Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good programming practices with centralizing variables

Tags:

java

oop

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:

  1. I have a class with a set amount of variables
  2. I have another class that needs the same variables
  3. 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.

like image 754
Andrei0427 Avatar asked Sep 07 '12 08:09

Andrei0427


People also ask

Which one is a good practice of writing variables?

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.

What is a good example of a variable name?

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);


2 Answers

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.

like image 70
Joeri Hendrickx Avatar answered Oct 20 '22 01:10

Joeri Hendrickx


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.

like image 43
Peter Lawrey Avatar answered Oct 20 '22 01:10

Peter Lawrey