'''AntiPattern Name''': ''AccidentalInclusion'' '''Type''': ''API Design'' '''Problem''': Accidental inclusion of event listener methods in public APIs. '''Context''': Component classes require notification from event sources. '''Forces''': [forces] '''Supposed Solution''': Component classes implement event listener methods directly. '''Resulting Context''': Event listener methods are included in the public API of component classes. Strongly worded comments are the only way to discourage clients of the APIs from breaking the component classes' implementation ("Don't override this method!!", "Make sure if you override this method you call super.xxx() first!", etc.). Ex. public class S''''''uperComponent extends JComponent implements X''''''xxListener { /** @see X''''''xxListener */ public void xxx(final X''''''xxEvent xxxEvent) { doImportantStuff(); } } Any subclasses might break the implementation: public class M''''''yComponent extends S''''''uperComponent { /** @see X''''''xxListener */ public void xxx(final X''''''xxEvent xxxEvent) { doSomethingElse(); } } Note the call to doImportantStuff() never happens. '''Design Rationale''': [rationale] '''Related AntiPattern''''''s''': '''Applicable Positive Patterns''': Use private inner classes or anonymous inner classes to implement event listener methods. Ex. public class S''''''uperComponent extends JComponent { /** * Create a new super component. */ public S''''''uperComponent() { // ... xxx.addXxxListener(new S''''''uperXxxListener()); } /** * Private xxx listener inner class. */ private class S''''''uperXxxListener implements X''''''xxListener { /** @see X''''''xxListener */ public void xxx(final X''''''xxEvent xxxEvent) { doImportantStuff(); } } } or public class S''''''uperComponent extends JComponent { /** * Create a new super component. */ public S''''''uperComponent() { // ... xxx.addXxxListener(new X''''''xxListener() { /** @see X''''''xxListener */ public void xxx(final X''''''xxEvent xxxEvent) { doImportantStuff(); } }); } } '''AntiPatternCategory''': [classify it] '''Also Known As''': [other names] ---- '''Examples in the Literature''': ---- '''Examples in Practice''': JComboBox: "This method is public as an implementation side effect. do not call or override." ActionEvent * http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JComboBox.html#actionPerformed%28java.awt.event.ActionEvent%29 ListDataEvent * http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JComboBox.html#contentsChanged%28javax.swing.event.ListDataEvent%29 JTable: "Application code will not use these methods explicitly, they are used internally by JTable." * http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JTable.html#columnMoved%28javax.swing.event.TableColumnModelEvent%29 * http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JTable.html#tableChanged%28javax.swing.event.TableModelEvent%29 ---- CategoryAntiPattern CategoryDevelomentAntiPattern