Reputation: 35776
I have an extremeley small and simple class but it is giving me some problems in how best to deal with it.
It has a constructor and a single get method.
The purpose is to store an array of values and return them when asked via the get method.
Additionally, the array of values might be passed as a comma separate string to the constructor. And this is where i cant decide how to handle things.
Upvotes: 3
Views: 106
Reputation: 247
In Effective Java by Joshua Bloch one can read that you should be as lazy as possible with operations and only do things when they are really needed, such as initializing variables etc.
So following that suggestion I would do something like this:
public class Example {
private String string;
private String[] array;
public Example(String string){
this.string = string;
}
public Example(String[] array){
this.array = array;
}
public String[] getValues(){
if(this.array == null){
//Split the string, trim the values
//create a new array and assign it to the array-variable
this.string = null; //no need to keep it any longer
}
return this.array;
}
}
Upvotes: 1
Reputation: 7796
- Should the constructor split the string and trim element before storing the property
- Should the constructor simply store the property and each time the getter is called, the property should be split
- Should the getter check the property and if its a string, split it and then store the value for future calls to getter not have to ...
I'll address each of these individually.
property.split(",")[4]
is something specificIn conclusion, #1 seems like the best solution to me.
Upvotes: 1
Reputation: 55619
On the assumption that you're going to call get
at least once, the first option would be preferable.
The second option has the disadvantage that you may need to split many times, which can take quite a performance toll if you're calling get
a lot.
The third option has the disadvantage that you'll likely need to have either 2 variables (a string and an array), only one of which will be used at a time, or have the type be an Object
, which would then be either a string or an array. Neither of these options are particularly good design.
If you're often not calling get
at least once, or if you need access to the original string, the third option might make sense (at least from a performance point of view, the first option is still a better design), but I'd be fairly concerned about your design if this is the case.
Upvotes: 2
Reputation: 709
It is you who should decide if you ever need an original string. If you don't it is logical choice to have job done in the constructor.
Upvotes: 0
Reputation: 6667
Do it in the constructor. That is only going to be called once. If you do it in the getter you'll have to do the split many times.
Upvotes: 5