Java Best Practices – String Array Constants and Indexing

arrayjavastrings

For string constants its usual to use a class with final String values. But whats the best practice for storing string array. I want to store different categories in a constant array and everytime a category has been selected, I want to know which category it belongs to and process based on that.

Addition : To make it more clear, I have a categories A,B,C,D,E which is a constant array. Whenever a user clicks one of the items(button will have those texts) I should know which item was clicked and do processing on that.

I can define an enum(say cat) and everytime do

if clickedItem == cat.A
 ....
else if clickedItem = cat.B
 ....
else if 
 ....

or even register listeners for each item seperately.

But I wanted to know the best practice for doing handling these kind of problems.

Best Answer

I much prefer using Enums to store system wide string constants, makes it easy to create additional functionality and I think it is generally accepted best practice.

public enum Cat {
     A() {
          @Override public void execute() { 
               System.out.println("A clicked"); 
          }
     },
     B() {
          @Override public void execute() { 
               System.out.println("B Clicked"); 
          }
     };
     //template method
     public abstract void execute();
}

then you can call it like so :

String clickedItem = "A";    
Cat.valueOf(clickedItem).execute(); //will print A is clicked

or you could also the Command pattern without enums....

public interface Cat {
     void do();
}

public class CatA() implements Cat {
     void do() {//put your code here}
}
public class CatB() implements Cat {
     void do() {//put your other code here}
}

then build a Map object and populate it with Cat instances:

catMap.put("A", new CatA());
catMap.put("B", new CatB());

then you can replace your if/else if chain with:

catMap.get(clickedItem).do();
Related Topic