How to replace many if's statements in java?

Kazh :

I am trying to make my code "cleaner". I have many functions with a lot of if-statements. How can I replace them?

I'm using 4 differents Hashtables that's why I have those ifs. The only thing changing is the hashtable name and the jList where I add the informations.

if(n.getCategorie().getNum() == Categorie.INTERNATIONAL.getNum())
                {
                    DefaultListModel dlm = (DefaultListModel) jListInternationales.getModel();
                    dlm.addElement(n.getTitre());
                    jListInternationales.setModel(dlm);
                    NewsInter.put(""+nNews, n);
                }
                else if(n.getCategorie().getNum() == Categorie.POLITIQUE.getNum())
                {
                    DefaultListModel dlm = (DefaultListModel) jListViePolitique.getModel();
                    dlm.addElement(n.getTitre());
                    jListViePolitique.setModel(dlm);
            NewsPolitique.put(""+nNews, n);
                }
                else if(n.getCategorie().getNum() == Categorie.RAGOT.getNum())
                {
                    DefaultListModel dlm = (DefaultListModel) jListRagotsEtPotins.getModel();
                    dlm.addElement(n.getTitre());
                    jListRagotsEtPotins.setModel(dlm);
            NewsRagot.put(""+nNews, n);
                }
                else if(n.getCategorie().getNum() == Categorie.SPORT.getNum())
                {
                    DefaultListModel dlm = (DefaultListModel) jListInfosSports.getModel();
                    dlm.addElement(n.getTitre());
                    jListInfosSports.setModel(dlm);
            NewsSport.put(""+nNews, n);
                }
Karol Dowbecki :

The only difference between the if branches comes from the JList reference. Since the code is repeated you should extract it into a separate method:

private void updateList(JList list) {
  DefaultListModel dlm = (DefaultListModel) list.getModel();
  dlm.addElement(n.getTitre());
  list.setModel(dlm);
}

After that the code becomes much cleaner:

if (n.getCategorie().getNum() == Categorie.INTERNATIONAL.getNum()) {
  updateList(jListInternationales);
} else if (n.getCategorie().getNum() == Categorie.POLITIQUE.getNum()) {
  updateList(jListViePolitique);
} // etc

NewsInter.put(""+nNews, n);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=114995&siteId=1