2

An object requires it be instantiated with an object upon which it can call a method to register than an event has occurred — rather than the instantiating code listening for events.

Is this an anti-pattern? If so, does it have a name?

Is there a reason to code this way?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Lee Goddard
  • 10,680
  • 4
  • 46
  • 63

2 Answers2

1

Passing an object-to-be-called into a constructor is usually used for the "constructor injection" type of dependency injection. See: https://en.wikipedia.org/wiki/Dependency_injection#Constructor_injection

When used in that way it's an excellent pattern...

But if the object being passed in is really an event listener, then it becomes a bad idea. Injecting an event listener is not "dependency injection", because an object doesn't depend on its event listeners, and so it shouldn't require any in its constructor. It would also be very bad form to restrict an event-generating object such that it could have only one listener.

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87
0

Is this an anti-pattern?

No

does it have a name?

Yes: callback function

Is there a reason to code this way?

Certainly, see: How to explain callbacks in plain english?

Note that a constructor is a method as well. There's nothing inherently different about passing a callback to a constructor versus any other method.

jaco0646
  • 15,303
  • 7
  • 59
  • 83
  • Not a callback — object A is passed to B, B has to call a specific method to fire an event on A. Tight coupling — bad. B could emit an event which A listens for — de-coupled, good. – Lee Goddard May 03 '18 at 17:19
  • Still a callback. Using an object to pass the function doesn't change the nature of the relationship. In object-oriented languages without first-class functions, passing an object may be the only way to pass a callback function. Decoupling can still be achieved by utilizing something akin to a [functional interface](https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html) (Java example). – jaco0646 May 03 '18 at 18:23
  • Oh — are you suggesting to use a callback? Or are you suggesting the pattern the Q describes *is* a callback...? – Lee Goddard May 04 '18 at 16:42
  • I'm suggesting the latter: an object can _be_ a callback. Per [Wikipedia](https://en.wikipedia.org/wiki/Callback_(computer_programming)#Implementation), "_In object-oriented programming languages without function-valued arguments, such as in Java before its 8 version, callbacks can be simulated by passing an instance of an abstract class or interface..._" – jaco0646 May 05 '18 at 18:46