user2279235
user2279235

Reputation:

OOP - Can and should events be part of the abstractions?

Imagine that I have a system of objects that are event emitters and also can listen to events in other objects. In this system these objects communicate between them mainly using events.

I want to follow good object-oriented practices an I'm interested in creating abstractions for my objects. The actual language that I would use doesn't matter that much: those abstractions could be interfaces or abstract classes for example.

These kind of abstractions define methods and properties in the object, but don't define event names. New implementations could decide to throw totally new events... It's true that you are using always the same method to throw them, but if you are creating new event names my impression is that you are in a way violating the open/closed principle: I would say that that's equivalent to adding new methods.

Would there be a way to state the possible events that an object like that can emit, in the abstraction that that object follows?

I'm interested in how this would work in languages like Java, C++, Javascript and Typescript. I'm not entirely sure as I don't know C# but I think that in that language events can be a part of the interfaces. But I am interested in how would you make events part of the abstractions in those other languages that don't support that in a straightforward way.

Upvotes: 1

Views: 120

Answers (1)

plalx
plalx

Reputation: 43718

The ability to enforce those contracts in code efficiently will differ depending on the language being used, therefore the optimal solution is not really language agnostic: there's an idiomatic way of doing things in every language.

One solution that can be implemented in probably all typed languages is to make every event an emitter and rely on composition.

That basically boils down to someObject.onSomeEvent.listen(handler) instead of someObject.listenTo('someEvent', handler).

That's the approach they used in Google Dart when refactoring the DOM Events API. Since events are now class members they can easily become part of the code contract.

There are obviously other ways, such as creating a concrete event class per event rather than using strings. The advantage of this solution is that the contract wouldn't have to change when new events are added.

Upvotes: 1

Related Questions