What would be a good code structure for test fields?

I have a test class with fields containing test content. It looks like this:

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 extra array

  public static String[] a = {s1, s2, s3}; 

This structure works fine, but a little ugly, because every time I add or remove a field, I also modify the array.

The only solution to restructure my code without manually manipulating the array is to write everything 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 s> 10 long lines.

What could be a better structure?

+4
source share
3 answers

If you want to use them in a loop, it makes me think that they are somewhat homogeneous. Also, the variable names ( s1 , s2 , s3 ) are meaningless because they are worth it. So go to the array (or use Arrays.asList() idiom).

If each line has a different meaning and is used separately, there are definitely separate variables. If you want to have the best of both worlds (separate variables and a list that is easy to maintain, consider this):

 class Test { public static final String s1 = str(" ... long string ... "); public static final String s2 = str(" ... long string ... "); public static final String s3 = str(" ... long string ... "); public static final List<String> strings = new ArrayList<>(); public static String str(String s) { strings.add(s); return s; } } 

Last but not least, remember the final keyword.

+3
source

An alternative approach is to use enum , for example.

 public enum Test { S1("... long string 1..."), S2("... long string 2..."); private String value; Test(String value) { this.value = value; } public String getValue() { return value; } } 

Then you can access the instances separately or as a list, for example: -

 public static void main(String[] args) { /* Single instance */ String value1 = Test.S1.getValue(); /* All instances */ for (Test test : Test.values()) { System.out.println(test.getValue()); } } 

With this approach, you don’t have to worry about changing the array when adding or removing new values.

+1
source

Have you thought about lists? If you don't care about the order of your lines, this is a good solution. This is pretty easy to implement, and you can add or remove as many elements as you want. Wikipedia - List

0
source

Source: https://habr.com/ru/post/1445144/


All Articles