Reputation: 11173
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?
Upvotes: 2
Views: 150
Reputation: 59233
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.
Upvotes: 1
Reputation: 17094
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.
Upvotes: 0