Search code examples
javaarraylistjavafx-8code-duplication

Is there a way to shorten code that is duplicated because of similiar properties of objects?


I have many Checkboxes all of whom are dependant on a certain box not being ticked, if however it does get ticked the boxes must be ticked and hidden. I know people keep saying ArrayList but, I have no idea of the syntax on how to edit certain properties of the items in the ArrayList.

My code works, I just need this code to be shorter as I believe if it continues to run like this it will slow down the processes in the end, and I want to learn how this works for other objects that I have that do the same.

 public void cbxSalesSelectA() {
    boolean t = cbx_SALES_Select_All.getText().equals("Select All");
    cbx_SALESQtySold.setSelected(t);
    cbx_SALESDateSold.setSelected(t);
    cbx_SALESCustomer.setSelected(t);
    cbx_SALESDiscount.setSelected(t);
    cbx_SALESLineNumber.setSelected(t);
    cbx_SALESConsultant.setSelected(t);
    cbx_SALES_Header_Row.setSelected(t);
    if (t) {
        cbx_SALES_Select_All.setText("Deselect All");
    } else {
        cbx_SALES_Select_All.setText("Select All");
    }
}
 public void cbxLOCSelectA() {
    boolean t = cbx_LOC_Select_All.getText().equals("Select All");
    cbx_LOCHeight.setSelected(t);
    cbx_LOCWidth.setSelected(t);
    cbx_LOCDepth.setSelected(t);
    cbx_LOCWeightCap.setSelected(t);
    cbx_LOCAccessibility.setSelected(t);
    cbx_LOC_Header_Row.setSelected(t);
    if (t) {
        cbx_LOC_Select_All.setText("Deselect All");
    } else {
        cbx_LOC_Select_All.setText("Select All");
    }
}

Solution

  • I don't think you really can improve performance of your code but for readability you can do the changes of selected in a separate method. For instance

    static void allSetSelected(boolean isSelected, CheckBox... boxes ) {
        Arrays.stream(boxes).forEach(b -> b.setSelected(isSelected));
    }
    

    and use it in your code like this

    public void cbxSalesSelectA() {
        boolean t = cbx_SALES_Select_All.getText().equals("Select All");
        allSetSelected(t, cbx_SALESQtySold,
                          cbx_SALESDateSold,
                          cbx_SALESCustomer,
                          cbx_SALESDiscount,
                          cbx_SALESLineNumber,
                          cbx_SALESConsultant,
                          cbx_SALES_Header_Row)
        if (t) {
            cbx_SALES_Select_All.setText("Deselect All");
        } else {
            cbx_SALES_Select_All.setText("Select All");
        }
    }
    
    public void cbxLOCSelectA() {
        boolean t = cbx_LOC_Select_All.getText().equals("Select All");
        allSetSelected(t, cbx_LOCHeight, cbx_LOCWidth, cbx_LOCDepth, cbx_LOCWeightCap, cbx_LOCAccessibility, cbx_LOC_Header_Row);
        if (t) {
            cbx_LOC_Select_All.setText("Deselect All");
        } else {
            cbx_LOC_Select_All.setText("Select All");
        }
    }