So I have a method which instantiates a instance field String[][] myArray with values.
String[][] myArray;
public String[][] getArray() {
// CREATES, RETURNS & INSTANTIATES myArray WITH ARRAY
}
However, then I have a method called getAvg() which gets the average of a column in the array. This uses the instance field which is now instantiated with data. Trouble is, this will obviously not run if the array has not been created first. Within my program, I create the array before calling for the average and it works. But I’m wondering if this is the most elegant of methods and if this could even be bad practice.
public double getAvg() {
// CALCULATES AND RETURNS AVERAGE
}
I previously recreated the array within the getAvg() method. However, this lead me to me thinking that this would be redundant and inefficient.
So, what do you think?
Yes, this is bad practice. In general (there are exceptions, but not many), all the data a class needs should be ready by the time the constructor returns. What about renaming
getArraytoinitializeMyArray, making it private, and placing a call toinitializeMyArrayin the constructor? Then, whenever some outside code callsgetAvg(),myArraywill have been initialized.