Java – Passing by value multiple times vs. Creating a public class variable

class-designjavamethods

Suppose I have a series of methods across different classes that all use the same five core variables defined in my main method. I could chain these five variables as method arguments from one method to the next, or I could simply define these five variables as public class variables and reference their path each time I want to use them.

What is considered more readable, and what is more efficient it terms of processing time? These values will not change throughout their lifespan in the program and take the form of Boolean values, multidimensional int[] arrays, and single dimensional int[] arrays.

Best Answer

In this case, I would have to say create an object that holds them - like a "Data" class, which you can then instantiate. This provides a nice single point of access to the data. But, in this case, it does take up some extra space on the heap. (I'm not sure how concerned you should be with this though, java has automatic garbage collection)

Another advantage is that now your objects have to be less in-the-know about eachother. When you use a data object to encapsulate the data, you can send that to the method so your sender doesn't know exactly what the method will use. This is an advantage, as you can easily extend the method later to use some more information from the data object. Imagine the method only uses the boolean values and single-dimensional arrays, you really want your sender to know this? I'd say, just pass the data object, and trust the method to fetch the data it needs and perform the operations)

In this way, it's also easier to extend upon this. Do you suddenly, for one class, need more data? Add it to the data-object. Do you, at some point, wish to verify that all the data is correct? Add setter methods to the data object to protect it from flawwed input.

As I don't know how your program is designed exactly, this is what I would do considering all the information you have provided, and keeping in mind the option to expand upon your implementation in unforseen ways later on.