I have a test class with fields which contain test content. It looks like:
class Test {
public static String s1 = " ... long string ... ";
public static String s2 = " ... long string ... ";
public static String s3 = " ... long string ... ";
}
Now I would like to use these fields in a loop, so I wrote an additional array
public static String[] a = {s1, s2, s3};
This structure works fine, but is a bit ugly because everytime I add or delete a field, I have do change the array, too.
The only solution to re-structure my code without the manually manipulating of the array is to write it all in the array at once:
class Test {
public static String[] a = {" ... long string ... ", " ... long string ... ",
" ... long string ... "};
}
As you can see, this makes the code unreadable, especially when we have to deal with > 10 long strings.
What could be a better structure ?
If you want to use them in a loop, it makes me think that they are homogeneous in some way. Also the variable names (
s1,s2,s3) are meaningless as they stand. So go for array (or useArrays.asList()idiom).If each string has a different meaning and is used separately, definitely have separate variables. If you want to have best of both worlds (separate variables and a list that is easily maintainable, consider this):
And last but not least, remember about
finalkeyword.