In object-oriented programming, delegation refers to evaluating a member (property or method) of one object (the receiver) in the context of another original object (the sender).
Delegation is a design pattern in which an object handles a request by delegating to a helper object, called the delegate. The delegate is responsible for handling the request on behalf of the original object and making the results available to the original object.
Kotlin supports “delegation” design pattern by introducing a new keyword “by”. Using this keyword or delegation methodology, Kotlin allows the derived class to access all the implemented public methods of an interface through a specific object
Delegation should be used when:
- Any components that behave identically, but we realize were it will have some upgradation on top of it in future point of time where we do our own logical implementation and expose the results. For E.g. We can take an example of Analytics class, where instead of directly using the analytics method we can have our delegation and use the param to handle the screen views and event logging.
- Place where we feel delegate would be the better than inheritance because, it doesn’t force you to define all the methods of the super class, you can use or override only the methods that really needed. For e.g. here you can refer the code below that PaymentProcess doesn’t enforced to override the method (Kotlin), but if really needed we can override and do our implementations.
- If we want to extend the behavior of classes that we cannot or don’t want to subclass for the below reasons For E.g. here you can see in the below code snippet Payment classes (CashPayment, UPIPayment, CardPayment) are can’t be inherited.
- Restricted to share or disallowed to create a hierarchy (Class marked as final)
- Planning to expose the limited or different API methods by consuming the existing code functionality and also we may add our feature update.
- Planned to hide the serious implementation from the calling code.
Example: This will be very simple and self-explanatory code snippet, here we are having an interface IPayment for the payment and it would track the mode of payment happens, and there would be an implementation classes CashPayment, UPIPayment, CardPayment of different mode of payment (Cash, Card and UPI). There in PaymentProcess class the delegation will be happen through the interface. Also the method paymentProcess in java and processPayment in Kotlin does the payment process.
Comparatively with Java and Kotlin, In Kotlin we avoid lot of boilerplate code because of delegation using “by”, else in java we are mandatory to do the implementation of all interface method (see in this example I have used only one interface method, so if it is more than, it would be more override method in PaymentProcess.java class).
Java Style of Delegate
Kotlin Style of Delegate:
Happy Coding :-)
No comments:
Post a Comment