mercredi 15 mai 2019

Dynamically find the correct method in order to not repeat the same code

The following code adds Listeners to several SWT Text elements. The only difference is the code inside the Listeners method. Is there a way to make this code less repetitive by finding the correct method to use dynamically?

In this example a FocusListener is used, but it's not relevant.

private void addFocusLostListeners() {
    nameText.addFocusListener(new FocusListener() {
        @Override
        public void focusGained(FocusEvent e) {}
        @Override
        public void focusLost(FocusEvent e) {
            myDataObject.setName(nameText.getText());
        }
    });
    ageText.addFocusListener(new FocusListener() {
        @Override
        public void focusGained(FocusEvent e) {}
        @Override
        public void focusLost(FocusEvent e) {
            myDataObject.setAge(ageText.getText());
        }
    });
    emailText.addFocusListener(new FocusListener() {
        @Override
        public void focusGained(FocusEvent e) {}
        @Override
        public void focusLost(FocusEvent e) {
            myDataObject.setEmail(emailText.getText());
        }
    });
    ...
}

Aucun commentaire:

Enregistrer un commentaire