Search code examples
javaswingcoding-stylecode-cleanup

How can I simplify this module?


I have some method which looks awful(especially number of parameters). I wonder how can I make this code cleaner.

The method works with JLists and setting a new model(DefaultListModel). So it just swaps items between two JLists and deletes swapped item in list where was the item taken.

Сriticism and advice are welcome.

Call the method example:

moveToOtherJList(newOrdersModel, newOrdersJList, inProcessOrdersModel, inProcessOrdersJList);

The method:

private void moveToOtherJList(DefaultListModel firstModel, JList firstJList, DefaultListModel secondModel,  JList secondJList)
{
    int selectedIndex = firstJList.getSelectedIndex();
    secondModel.addElement(firstJList.getSelectedValue());
    secondJList.setModel(secondModel);
    firstModel.remove(selectedIndex);
}

Solution

  • I have some method which looks awful(especially number of parameters).

    Well there is no need to pass either ListModel, since you can get the ListModel from the JList.

    So I would define the method as:

    public void moveToOtherJList(JList fromJList, JList toJList)
    {
        int selectedIndex = fromJList.getSelectedIndex();
        DefaultListModel fromModel = (DefaultListModel)fromJList.getModel();
        DefaultListModel toModel = (DefaultListModel)toJList.getModel();
    
        toModel.addElement(fromJList.getSelectedValue());
        fromModel.remove(selectedIndex);
    }