A Replacement for C# Interfaces
Since I'm using C#, my programming style has changed with each new language feature.
For example, since a few years, I almost always use composition over inheritance.
Except for situations in which a given class forces clients to change behaviors by overriding members, or for solving DRY optimization problems that work around other missing language features, you won't find any single use of the keywords
override in my code.
And because I do feel better with a lot of smaller components that can be sticked together (mostly via interfaces and events), I consider the object-oriented polymorphic style of composition a failure.
For me, interfaces were not an addition to object-orientation, for me, they completely replaced inheritance.
But interfaces have their annoyances, even though they stand separate from their implementations, it's hard to work with them. For example:
- An implementation (class) must be created to implement an interface.
- All members of an interface have to be implemented.
- There are no default implementations for individual members.
But there is another way, which has almost all features of an interface, it feels like prototype based programming, and I am beginning to use it my projects.
For example the interface:
may be written as:
Now that does not look so bad, but what are the consequences?
- The default behavior for all the members can be specified.
- Individual methods can be changed.
- Methods may be chained easily (before / after).
- No separate implementation is required, the interface carries the implementation and the associated state in form of lambas and their captured variables with it.
I am not yet clear if this approach is favorable to using interfaces, but there is another trend approaching with the introduction of the async / await keyword. And this is the trend to write async methods instead of implementing objects that have state that changes over time. I am already practicing this, and though I don't know yet if it scales to large applications, I feel that stateful instances don't fit well within the async / await world. If this movement gets traction, interfaces that abstract mutable objects won't be on the winner's side of the evolutionary ladder.
Of course this sounds very much like a parallel evolution that heads in the direction of functional programming. If it is so, then so it be, but may be we are up to something entirely new that simplifies the process of abstraction and programming in general.