Last week, I showed you my new implementation for instance-level properties in Python. This week, we’ll take another look at it by implementing a few Delegated Properties and helpers to make using them just a hair nicer.
Recreating Kotlin’s Built-In Delegates
For inspiration of what Delegated Properties to create, we’ll start by recreating the ones built into Kotlin, starting with
Lazy. Continue Reading
A while back, I did a post on making instance-level properties in Python where the implementation of it required inheritance as well as messing with
__setattr__(), which are a little dangerous to mess with. Then I had another idea last night (as of the time of writing this): Use normal descriptors to delegate to “Delegated Properties” (name taken from Kotlin, the original inspiration). These Delegated Properties can be designed very simply in a way that they only have to worry about the value on one instance, instead of figuring out how to store the value per instance. Continue Reading
Recently, I posted about how you can use composition instead of inheritance, and in that article, I mentioned the Delegate Pattern. As a quick description, the pattern has you inherit from the parent interface (or, in Python, you can just implement the protocol), but all the methods either redirect to calling the method on an injected implementation of interface/protocol, possibly surrounding the call in its own code, or it completely fills the method with its own implementation.
For the most part, it is like manually implementing inheritance, except that the superclass in injectable.
Anyway, one of the more annoying parts of implementing the Delegate Pattern is having to write all of the delegated calls. So I decided to look into the possibility of of making a decorator that will do that for you for all the methods you don’t explicitly implement. Continue Reading
Quite a while back, I posted about how, despite the fact that you should prefer composition over inheritance, you can best design classes for inheritance. Now, I wish to give some examples of how you can take your code that uses inheritance and change it to use composition instead, which will often actually make your code more flexible.
The code will be in java, but the concepts can transferred to any language that is object-oriented. Some languages might have constructs that make parts of this easier, too (Kotlin’s Delegates).
One thing is important to remember, though: Even if you switch “completely” to composition, you will still have some inheritance. This inheritance will be from interfaces and interface-like classes only, though. It barely counts as inheritance, really, since all it’s doing is restricting itself to an API and not inheriting implementation details. Continue Reading
I wrote a poll to see what people what people’s preference was concerning functional composition.