Accidental Inclusion

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 SuperComponent extends JComponent implements XxxListener {
    /** @see XxxListener */
    public void xxx(final XxxEvent xxxEvent) {
      doImportantStuff();
    }
 }

Any subclasses might break the implementation:

 public class MyComponent extends SuperComponent {
    /** @see XxxListener */
    public void xxx(final XxxEvent xxxEvent) {
      doSomethingElse();
    }
 }

Note the call to doImportantStuff() never happens.

Design Rationale: [rationale]

Related AntiPatterns:

Applicable Positive Patterns:

Use private inner classes or anonymous inner classes to implement event listener methods.

Ex.

 public class SuperComponent extends JComponent {
   /**
    * Create a new super component.
    */
   public SuperComponent() {
     // ...
     xxx.addXxxListener(new SuperXxxListener());
   }

/** * Private xxx listener inner class. */ private class SuperXxxListener implements XxxListener { /** @see XxxListener */ public void xxx(final XxxEvent xxxEvent) { doImportantStuff(); } } }

or

 public class SuperComponent extends JComponent {
   /**
    * Create a new super component.
    */
   public SuperComponent() {
     // ...
     xxx.addXxxListener(new XxxListener() {
         /** @see XxxListener */
         public void xxx(final XxxEvent 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

ListDataEvent? JTable:

"Application code will not use these methods explicitly, they are used internally by JTable."


CategoryAntiPattern CategoryDevelomentAntiPattern?


EditText of this page (last edited August 14, 2010) or FindPage with title or text search