Functions with different signatures, but the same body

Семушин Сергей :

Consider a class

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ShortcutButton extends JButton {
    public ShortcutButton(String text, KeyStroke[] keyStrokes, ActionListener actionListener) {
        super(text);
        addActionListener(actionListener);
        addShortcut(keyStrokes);
    }
    public ShortcutButton(String text, KeyStroke keyStrokes, ActionListener actionListener) {
        super(text);
        addActionListener(actionListener);
        addShortcut(keyStrokes);
    }
    public ShortcutButton(String text, String[] keyStrokes, ActionListener actionListener) {
        super(text);
        addActionListener(actionListener);
        addShortcut(keyStrokes);
    }
    public ShortcutButton(String text, String keyStrokes, ActionListener actionListener) {
        super(text);
        addActionListener(actionListener);
        addShortcut(keyStrokes);
    }

    public void addShortcuts(KeyStroke[] keyStrokes) {
        for (KeyStroke keyStroke : keyStrokes) {
            addShortcut(keyStroke);
        }
    }
    public void addShortcuts(String[] keyStrokes) {
        for (String keyStroke : keyStrokes) {
            addShortcut(keyStroke);
        }
    }
    public void addShortcut(String keyStroke) {
        addShortcut(KeyStroke.getKeyStroke(keyStroke));
    }
    public void addShortcut(KeyStroke keyStroke) {
       //some code here
    }
}

As you can see, ShortcutButton() coonstructors and addShortcuts() functions have defferent signatures, but the same body. Is there a pretty way to make this code shorter in order not to copy-paste the same code in four different functions?

Eran :

You can reduce them into two constructors if you reorder the arguments and use varargs:

public ShortcutButton(String text, ActionListener actionListener, KeyStroke... keyStrokes) {
    super(text);
    addActionListener(actionListener);
    addShortcuts(keyStrokes);
}
public ShortcutButton(String text, ActionListener actionListener, String... keyStrokes) {
    super(text);
    addActionListener(actionListener);
    addShortcuts(keyStrokes);
}

and if you have a method that converts a String[] to a KeyStroke[], you can further shorten the code:

public ShortcutButton(String text, ActionListener actionListener, KeyStroke... keyStrokes) {
    super(text);
    addActionListener(actionListener);
    addShortcuts(keyStrokes);
}
public ShortcutButton(String text, ActionListener actionListener, String... keyStrokes) {
    this(text,actionListener,getShortCuts(keyStrokes));
}

Guess you like

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