Full Guide to Delegation in Kotlin - Android Studio Tutorial

Sdílet
Vložit
  • čas přidán 6. 08. 2022
  • Delegation is a concept in software that allows us to delegate some work from one object to another and is commonly seen as alternative to inheritance. In this video, I'll show you how you can benefit from it in your Android project.
    ⭐ Get certificates for your future job
    ⭐ Save countless hours of time
    ⭐ 100% money back guarantee for 30 days
    ⭐ Become a professional Android developer now:
    pl-coding.com/premium-courses...
    Subscribe to my FREE newsletter for regular Android, Kotlin & Architecture advice!
    pl-coding.com/newsletter
    Join this channel to get access to perks:
    / @philipplackner
    Get the source code for this video here:
    github.com/philipplackner/Kot...
    Join my Discord server:
    / discord
    Regular programming advice on my Instagram page: / _philipplackner_
    Checkout my GitHub: github.com/philipplackner
    You like my free content? Here you can buy me a coffee:
    www.buymeacoffee.com/philippl...

Komentáře • 203

  • @PhilippLackner
    @PhilippLackner  Před rokem +91

    Quick question: How do you like having quiet background music in tutorial videos like this one? Fits well or rather distracting? Thanks!!

    • @voidpointer398
      @voidpointer398 Před rokem +9

      Yeah this is not distracting at all for me, ig this will subconsciously make the viewer to watch the complete video

    • @abada-s
      @abada-s Před rokem +20

      I don't like it, it makes me angry 😁

    • @pa1shetty
      @pa1shetty Před rokem +15

      Its fine. But sound can be reduced.

    • @rhen4610
      @rhen4610 Před rokem +2

      Music uplifts the mood but idk about those people who are easily distracted when trying to focus/learn.

    • @tibrec8
      @tibrec8 Před rokem +1

      Its awesome 😎

  • @Zeeshan-Syed
    @Zeeshan-Syed Před rokem +45

    For each and every video I see, I'm getting improved more and more. Almost all of your videos are helpful for at least one of my projects. My colleagues, CTO and managers always appreciate me with the knowledge I have which has come from you.
    I really feel so happy and lucky to have your videos when I'm learning... Of course lifetime learning is required for any software developer and you are the one major contribution for me.
    Thanks again Philipp.

    • @PhilippLackner
      @PhilippLackner  Před rokem +4

      Thanks so much for the nice comment Zeeshan, really happy my content helps you! 🙏

    • @itsjeffo
      @itsjeffo Před rokem

      Don't forget the credits. :)

  • @acercow
    @acercow Před 10 měsíci +2

    When I search some confusions about android on the CZcams, it will always recommend Philipp's tutorials, you always know what confuses me~~

  • @viniciuscoscia
    @viniciuscoscia Před rokem

    Man, you are the best...
    I'm starting a new project in my current job, and I'm going to apply this new knowledge here. Thanks a lot.

  • @spicyunicornmilkfarmer
    @spicyunicornmilkfarmer Před rokem +3

    Super cool video. I feel like after several smaller projects, I'm starting to get better at visualizing separation of concerns across different object types, and how we can link them together.

  • @stanleykou5643
    @stanleykou5643 Před rokem +1

    Super excellent way of using delegation!

  • @Guilo583
    @Guilo583 Před rokem

    Thanks for Video. I keep improving by watching your tutorials

  • @GK-rc3fd
    @GK-rc3fd Před rokem

    Best explainer I have ever seen. Thanks @Philipp

  • @prageeth4855
    @prageeth4855 Před rokem

    Watching all your videos like a TV series 😅😋 Keepem coming!! 👍

  • @FlorianMeyer1983
    @FlorianMeyer1983 Před rokem

    Nice follow-up to your short from last week :)

  • @DerCheckerzeigts
    @DerCheckerzeigts Před rokem

    Thanks for the video. Never knew how to actually use delegates :)

  • @ketanchaurasiya2514
    @ketanchaurasiya2514 Před rokem

    Really amazing, I learnt a lot and am still learning and your videos are the major part of it , It really helped me a lot and I'm able to grab multiple offers , Really Thank you ,you are one of the best mentor.

  • @ma.fouani
    @ma.fouani Před rokem

    great stuff! thank you for your great effort

  • @HakikatArayan
    @HakikatArayan Před rokem

    Hello Philipp! I've recently discovered your channel and started learning from your videos. I appreciate that you're teaching actual stuff/skills that are needed to land a job instead of showing only the basics and putting all the important bits behind a paywall. You are awesome.
    Can I ask for a favor though? It's about how you record your audio. As you might have noticed, your mic is picking up a lot of mouth noise. There are ways to eliminate it. For starters, turn down your mic's gain/sensitivity till there's no background noise. Then, turn it down a bit more while speaking so that it picks up your voice but hardly any mouth noises. It's not a problem if the audio level is low, you can amplify it in post production. Talking loudly is important and it helps; as this is how we have conversations in real life. We don't put our ears against the speaking person's mouth, right? There is long enough distance between us and he/she talks loudly enough so that we don't here those noises at all. Oh, drinking some water before speaking also helps. Make sure you're hydrated!
    Why is this important? Well, maybe not important to the majority but when it comes to unwanted sounds, I'm a bit more sensitive than others, I can't help it. I was watching someone else's android programming tutorials before yours, and I had to extract the audio from each video, open them up in audacity, painstakingly delete all the breathing sounds and those INFURIATING swallows, then merge the clean audio with the video track into a file that's much better for my sanity. Otherwise it was driving me so crazy that I wanted to bang my head against the keyboard.
    Anyways, I appreciate the work you're doing again and if you can do as I asked, you'll be even more awesome. Cheers.

  • @armandoavila4615
    @armandoavila4615 Před rokem

    Thank you, Philipp! ❤️

  • @burakkarabekir2863
    @burakkarabekir2863 Před rokem

    Thanks for this wonderful content. You are doing your work well 👏

  • @austinealagi
    @austinealagi Před rokem

    You are a life saver thanks for this.

  • @RRRazzzaRRR
    @RRRazzzaRRR Před rokem

    You are a wizard))))
    FANTASTIC

  • @NeerajGupta-of9fy
    @NeerajGupta-of9fy Před rokem +1

    Thanks ,Philipp for this video. For my last three project's I have created BaseActivity, Basefragment for common code base. Now after I am trying to convert my base code through delegation.

  • @joseangelsanchez4753
    @joseangelsanchez4753 Před rokem

    Great video! Really useful. If I understood correctly, then this Kotlin delegation works exactly the same as the delegation in Swift (?). This will be really useful to make some implementation similar, since I feel Swift and Kotlin already look quite similar!

  • @MaffinMr
    @MaffinMr Před rokem

    Nice explanation, thank you

  • @xandrviking1113
    @xandrviking1113 Před rokem

    Very cool video. So multiple inheritance in Kotlin , yahooo 😀😇

  • @anudeepreddygopu8500
    @anudeepreddygopu8500 Před rokem

    I immediately subscribed just after wathcing this one video. :)

  • @hinocenciopaulo
    @hinocenciopaulo Před 2 měsíci

    Excellent explanation

  • @alco8864
    @alco8864 Před rokem

    This is awesome!!

  • @thils7619
    @thils7619 Před rokem

    Nice Information. Thank you.❤

  • @osisuper98
    @osisuper98 Před rokem

    Man is so good 👏🏾

  • @andreshoyo8330
    @andreshoyo8330 Před rokem

    This was very helpfull, i have a bottom sheet dialog for taking images from different sources, such as camera, gallery and own explorer.
    For camera and gallery I use contracts, and also I have to check for permissions for access the camera, all of this logic was rewritten on every fragment that makes use of that bottom sheet dialog.
    So I put all of this logic into a class and now, fragments just have to instantiate an object of this class.
    Thanks You.

  • @sakibsyed7626
    @sakibsyed7626 Před rokem

    Thanks for amazing topic

  • @jarvis2913
    @jarvis2913 Před rokem

    Very Informative thanks

  • @utkarshsharma7932
    @utkarshsharma7932 Před rokem

    Hello Philipp first of all, I really liked the video and the explanation was really good. I have been watching your videos from the very start and it has helped me alot. Have you heard about the Kotlin/js, which is getting pretty much popular these days, I guess that would be interesting to look into.

  • @syedovaiss
    @syedovaiss Před rokem

    Bro you are a gem 💎

  • @abada-s
    @abada-s Před rokem

    Impressive 🔥

  • @user-vt2ys8xu2o
    @user-vt2ys8xu2o Před měsícem

    Very good tutorial

  • @bboydarknesz
    @bboydarknesz Před rokem +3

    I am the one Base user, and now I understand why you said Base not a good practice. Actually you right with Interface, we can only add it when we need some.
    Anw, love this new video, I easily get distracted with BGM but yours so far enjoyable, maybe just carefully choose BGM so we don't distract.
    The way you zoom in out is smooth too. Keep it up! 👍🏿

  • @arthurgomes9248
    @arthurgomes9248 Před rokem

    Created today a class to handle Otp Auth with firebase. Previously, it was a method inherited using a base activity, now whe are using delegate, and its clear that the single responsability principle its achieved with delegation.

  • @sivaganeshkantamani2976
    @sivaganeshkantamani2976 Před rokem +3

    Hi Philipp,
    Excellent approach for the concept with deep links and lazy.
    How about android library development series like hosting on maven central, designing open source library with complications like self DI system, dependency management, etc. We don't have much sources out there, even official android developers have limited info regarding AAR with maven central.

  • @mustafaammar551
    @mustafaammar551 Před rokem

    VERY COOL
    YOU ARE THE BEST👍👍👍👍

  • @androidpc9656
    @androidpc9656 Před rokem

    Nice,Please post more kotlin videos

  • @tibrec8
    @tibrec8 Před rokem

    🙏 man good job

  • @ho-thtmarketingonline711

    Thanks man 👍

  • @manusarangal449
    @manusarangal449 Před 3 měsíci

    Amazing!

  • @clivejefferies
    @clivejefferies Před rokem

    I agree, base activies are an antipattern they end up being dumps for anything. Favour composition over inheritance.

  • @Usam43
    @Usam43 Před rokem

    Hey brother, background music is just fine until your voice is clear. I really love the approach and would definitely use in next work of mine. Cheers!
    Can you please discuss about annotations and it's usages in details that demonstrate how it actually work under the hood. Thank you

  • @manshalkhatri9289
    @manshalkhatri9289 Před rokem

    Helpful !

  • @ubersticks
    @ubersticks Před rokem +15

    Good video, Philipp! Question: You created interfaces, then never really used them. If this were dependency injection, then you wasted the opportunity to substitute different implementations - for example in testing. How does the use of an Interface help things? Seems like the Activity is hopelessly coupled to particular implementations...

    • @macurvello
      @macurvello Před rokem +5

      I was abou to ask smth similar. You got rid of the single resp problem but I don't see the decoupling. Can you help @Phillip?

    • @GordonChil
      @GordonChil Před rokem +6

      I think the key here is that a single class extends from multiple classes. Pretty cool trick.
      This is not something you can do in Java. (Unless you use interfaces with default implementations) but even then, you’re missing instance variables with interfaces that have default implementations.
      A lot of things clicked for me. I really enjoyed this video. I don’t do much Android development, but I do a lot in Kotlin on the jvm. I’m going to use this tomorrow in my code. I have some areas of code that could really use this design pattern.

    • @okeuwechue9238
      @okeuwechue9238 Před 2 měsíci

      I think decoupling/coupling is not the point here. He is showing us how to achieve *multiple* inheritance in a clever sophisticated way in order to achieve the goal of Single Responsibility.

  • @santoshs490
    @santoshs490 Před rokem

    Nice video.....😃.... Thanks

  • @pranaym143
    @pranaym143 Před rokem

    Although this is a cool way to implement core functionalities, it is impractical when your app has multiple activities and multiple devs working on it. Each and everyone has to remember to add these sets of lines in their code (considering these are critical functionalities like analytics, initialisers etc). If even one of them gets missed, it becomes a huge pain for both the dev and code reviewer to explain this. This is true when there are new developers in your company. Base Activity (although might look like an anti pattern) mitigates the human error part. Generally most companies have a dedicated platform team which takes care about these core functionalities of the activity, and other feature teams/pods simply inherit this base activity which is maintained by the platform team. Moreover, if let's say a new core functionality ( ex a new library) is being added, 100s of activity files needs change. Huge PR, and huge effort to review.

  • @Czarnini
    @Czarnini Před rokem +4

    BaseActivity havy user here ;)
    Thanks for wonderful video
    I get the Single Responsibility argument, but this seems very impractical to use in real life.
    For example - if I have an app that has lots of Activities and I want all of them to have AnalyticsLogger and DeepLinkHandler I have to remember to correctly override onCreate and onNewIntent in every single one of them. If I were to use inheritance I wouldn't have that problem

    • @PhilippLackner
      @PhilippLackner  Před rokem +5

      If you use a base activity though, you'll potentially end up with many more serious problems when it comes to maintenance. I was a heavy base activity user as well some time ago, but over time I saw quite some examples where the coupling was too strong and made it a pain to refactor

    • @Czarnini
      @Czarnini Před rokem +6

      @@PhilippLackner hmm, if I were to add new method to AnalyticsLogger with delgation I wolud have to refatctor every single Activity with inharitance I would have to change only BaseActivity....
      Nevertheless I love that there is a way to de facto inherit from 2 classes ;)

  • @abuiman5251
    @abuiman5251 Před rokem

    Thanks bro👍🏻

  • @miladhashemzadeh5626
    @miladhashemzadeh5626 Před rokem

    Amazing thank you a lot.❤️🙏
    Please talk about read write properties in kotlin it is so confusing for me.

  • @Nemesislh
    @Nemesislh Před rokem

    Great video Philipp! I am assuming we could use hilt (or other dependency injection framework) to provide the implementations of each delegate, right?
    I'm a heavy base activity user and all this sound really appealing!
    Keep up the good work man!

    • @PhilippLackner
      @PhilippLackner  Před rokem

      Absolutely you can, just not so easily with activities since they can't have a constructor

  • @John-qt6qk
    @John-qt6qk Před rokem

    Thanks Philips

  • @SaherAlSous-welcomes-you

    thank you!

  • @aviator1472
    @aviator1472 Před 7 měsíci

    Thanks!

  • @shrinivasmanjithaya2112

    Nice one..

  • @sameershelar2000
    @sameershelar2000 Před rokem

    Hi Philipp, Please make a sample app demonstrating the working of KMM. It can be a very simple app like showing a list from loading data from a API etc. It will help a beginner in getting starting with the KMM.

  • @brgame8
    @brgame8 Před rokem +1

    hi philip, I'm very grateful every time your video uploaded, almost your videos have impact for my code. lately I have a trouble that bothering me, can you please make video how to properly make moving view from current view to previous view with lazy column/row in compose (like change focus or some thing like one page landing page if you click a button and the view moving according its id). cause what I've done was make a calculated position and remember them every time new item loaded, and make it so laggy.
    I hope you would help me for this problem.

  • @MrFilo122
    @MrFilo122 Před rokem +2

    Great tutorial, however I think it would also be beneficial to mention that in case of normal classes where we define the constructor ourselves, we can provide the implementation of the delegate in that constructor and we don't need to create it by hand in every place. Works really great with DI and ViewModels for example.

    • @PhilippLackner
      @PhilippLackner  Před rokem

      True, in the end it's just an instance you need to delegate to

    • @st4849
      @st4849 Před rokem

      Yeah, but it's neater this way as you don't have to reference the delegate object's name. E.g. you simply type log("hello") instead of logger.log("hello")

    • @macurvello
      @macurvello Před rokem +1

      Could you elaborate? This looks useful for my use cases

    • @sanek1985t
      @sanek1985t Před rokem

      @@st4849 but explicit is better than implicit even if code will be little verbose. Without logger name later you will try to find where is my implementation?! And so on

    • @st4849
      @st4849 Před rokem

      @@sanek1985t Sure, I always thought Kotlin's strengths in general are also drawbacks for readability. There are multiple examples of this.

  • @dakopyc
    @dakopyc Před 10 měsíci

    Could you follow-up on the "property delagate" example with an example of a usage *other* than something like a lazy-getter? In other words, in what real-world cases would overridding both getter and setter with a property-delegate make for an elegant solution? Thx, Phillipp -- good stuff!

  • @mkc0321
    @mkc0321 Před rokem

    amazing

  • @mehulbisht9708
    @mehulbisht9708 Před rokem

    Didn't even realise there was any music in the background until your pinned comment mentioned it, maybe because I'm used to EDM 😅

  • @frank4pickerson
    @frank4pickerson Před rokem

    Wow! Great video! How create a unit test for MyLazy deliegate?

  • @anorov_hasan
    @anorov_hasan Před 10 měsíci

    hi philip can you also talk about packaging these classes in corresponding layer, thanks , take care

  • @khaled.noordin
    @khaled.noordin Před rokem

    Thanks

  • @ampo2004
    @ampo2004 Před rokem

    I wonder if we can use delegates in a composable screen for example to create basic functionality like a boolean to set a progress bar that is generic to each screen delegating that function etc.

  • @brunodiaz6100
    @brunodiaz6100 Před rokem

    You're my God

  • @artemhryhorov4382
    @artemhryhorov4382 Před rokem

    Hey Philipp, thanks for your video! I have a little missundestanding - why we can't just inject our AnalyticsImpl and DeepLinksHandlerImpl and use them as regular properties? This approach will have same functioanlity and performance, but keeps your activity cleaner because you don't need delegate anything to it.
    For example - if you have any constructor parameters in your Impls delegators you will have to provide them all right in activity. Like Activity : ComponentActivity, Analytics by AnalyticsImpl(some additional parameters creation)
    Really would be glad to see your answer!

    • @PhilippLackner
      @PhilippLackner  Před rokem

      An activity might not be the best example for this, but by using delegation you of course get the advantage you also get with inheritance. Here you could pass the activity as argument for a parameter of type deep link handler. Doesn't work if it's a property. You don't commonly pass around activities, but with other types of classes that's a big benefit of course

  • @veys7035
    @veys7035 Před rokem

    This is kind a workaround for single parent rule in Java and Kotlin. This rule exists for a reason and the single responsibility principle is more valid for functions. Classes can have many behaviors related to each other. But sometimes delegation can be useful for kind of irrelevant behaviors.

    • @vibovitold
      @vibovitold Před rokem

      "is a ..." (inheritance) and "has a ..." (composition, delegation) are two different things.
      disallowing multiple inheritance - which is not exclusive to Java and Kotlin, among major languages I think only C++ supports it - prohibits BEING more than one thing. which leads to many issues, eg. with colliding method signatures from multiple parents.
      there's no reason why a class cannot HAVE more than one thing though (dependency, friend).
      just like in a well-organized company - performing a single responsibility doesn't mean you can't delegate parts of this responsibility to specialized workers.

  • @theevan3867
    @theevan3867 Před rokem

    thanks

  • @EmineDvg
    @EmineDvg Před rokem

    🔥🔥🔥

  • @harshpratapsingh1638
    @harshpratapsingh1638 Před rokem

    Great explanation bro
    please make a tutorial on coroutines also🙂

  • @amrutapatil8287
    @amrutapatil8287 Před rokem

    Phillip please have a video on AOSP

  • @rafaelrodriguez3753
    @rafaelrodriguez3753 Před rokem

    sounds good, but how this looks like registering observers for a ViewModel and using dependencies from dagger within the delegate?

  • @miltonpimentel3769
    @miltonpimentel3769 Před rokem

    hello Phillipp, I would like to know which plugins, themes anyway. What are your android studio settings?

  • @evgeniivorobei69
    @evgeniivorobei69 Před rokem

    There is no problems right till the moment you need some constructor arguments, especially in platform-created classes (activity, fragment, etc)

  • @GeertBerkers
    @GeertBerkers Před rokem +1

    Thank you for this video! It helps me a lot, but is it also possible to combine Delgation with DI? I would like to pass some UseCases on the LifecycleEventObserver.

    • @GeertBerkers
      @GeertBerkers Před rokem

      class MainActivity : AppCompatActivity(),
      AnalyticsLogger by analytic,//AnalyticsLoggerImpl(),
      {
      init {
      Log.e(TAG, "MainActivity - init on $thread")
      }
      @Inject
      lateinit var analytic: AnalyticsLoggerImpl
      } for example something like this

    • @studiomacbookpro159
      @studiomacbookpro159 Před rokem

      do you have an answer, I have a usecase like you do? anyway I will workaround by use by lazy,

  • @foreverrafs
    @foreverrafs Před rokem

    I’m exploring Kotlin compiler plugins and would like to see a video on it. There doesn’t seem to be many resources on it

  • @tridevdeka5729
    @tridevdeka5729 Před rokem

    Noice!!

  • @romanpavliuk2301
    @romanpavliuk2301 Před rokem

    Thanks for a new way of writing daily basis logic. But I have a question: Is it possible to use DI for injecting AnalyticsLoggerImp instead of creating instance? Or in such cases we just need to use composition and create a delegate for a property?

    • @PhilippLackner
      @PhilippLackner  Před rokem +1

      Sure, that's possible. In the end, I directly created the AnalyticsLogger implementation here, but you can also just pass an existing instance (just not so easy for activities, since they don't really support constructors - but for anything else, sure)

    • @mateusz7389
      @mateusz7389 Před rokem

      @@PhilippLackner yes... AppComponentFactory is a pain and its works only for api 28 and above...

  • @ryszardmachmudow9175
    @ryszardmachmudow9175 Před rokem +1

    If anyone wonders why the "3" was not printed - because Philipp filtered "Hello World"

  • @haykmkrtchyan7093
    @haykmkrtchyan7093 Před rokem

    Great tutorial, but still one thing is not clear)) In analytics logger when we register lifecycle, what if I need to send specific log messages? For example StatisticsFragment opened or LoginFragment closed 😕 May I do it with another function where I'll pass that name as a parameter?

    • @PhilippLackner
      @PhilippLackner  Před rokem +1

      Pass what you need to the registerLifecycle function as well (like the activity instance as I showed)

  • @redaelmadini
    @redaelmadini Před rokem +1

    Thank you for this excellent video but, the first example (AnalytiycsLogger) related to Class Delagation given in this video is not relevant because you could simply use composition by calling: owner.lifecycle.addObserver(AnalytiycsLoggerImpl())
    # The rule is:
    Use class delegation with care. Among the three choices-inheritance, composition and class delegation-try composition first. It’s the simplest approach and solves the majority of use cases. Inheritance is necessary when you need a hierarchy of types, to create relationships between those types. Class delegation can work when those options don’t.
    # For Example:
    You cannot inherit a class when the superclass is not open, or if your new class is already extending another class. Class delegation releases you from these and other limitations. (delegation solves the need for multiple inheritance).
    # Double inheritance example form "Atomic kotlin" Book:
    - Code:
    interface Rectangle {
    fun paint(): String
    }
    class ButtonImage(
    val width: Int,
    val height: Int
    ): Rectangle {
    override fun paint() = "painting ButtonImage($width, $height)"
    }
    interface MouseManager {
    fun clicked(): Boolean
    fun hovering(): Boolean
    }
    class UserInput : MouseManager {
    override fun clicked() = true
    override fun hovering() = true
    }
    class Button(
    val width: Int,
    val height: Int,
    var image: Rectangle = ButtonImage(width, height),
    private var input: MouseManager = UserInput()
    ): Rectangle by image, MouseManager by input
    fun main() {
    val button = Button(10, 5)
    // Can upcast to both delegated types:
    val rectangle: Rectangle = button
    val mouseManager: MouseManager = button
    }
    - Explanation:
    The class Button implements two interfaces: Rectangle and MouseManager. It can’t inherit from implementations of both ButtonImage and UserInput, but it can delegate to both of them.
    Notice that the definition for image in the constructor argument list is both public and a var. This allows the client programmer to dynamically replace the ButtonImage.
    The last two lines in main() show that a Button can be upcast to both of its delegated types.
    This was the goal of multiple inheritance, so delegation effectively solves the need for multiple inheritance.

  • @brunodiaz6100
    @brunodiaz6100 Před rokem

    Philipp how can I perform unit test of activities like these? Is any way to mock this delegations?

  • @akashkumardas6521
    @akashkumardas6521 Před rokem

    This type of content should be in paid block, thank you so much. Now I can write code more better way.

  • @nipunshah1373
    @nipunshah1373 Před rokem

    This concept seems similar to Mixins !

  • @samsadch
    @samsadch Před rokem

    how to add observer for onConfigurationChanged() callback?

  • @emmanuelmtera5936
    @emmanuelmtera5936 Před rokem

    How to include native code such as rust or Go in compose?

  • @berkedel
    @berkedel Před rokem

    What are the differences between this delegation approach and injecting the dependency of the concrete class instance?

    • @PhilippLackner
      @PhilippLackner  Před rokem +1

      With delegation, the class is of the interface type and can be passed as that

  • @user-cz6te1gt8q
    @user-cz6te1gt8q Před 8 měsíci

    Why do we need delegation? Couldn't we just create instance of Impl Class and call register on it?

  • @dRaiKable
    @dRaiKable Před rokem

    What's the difference between using delegates vs initialising AnalyticsLoggerImpl() in your activity as a class variable?

    • @VivekSharma-qw5ky
      @VivekSharma-qw5ky Před rokem

      I guess there is not much difference, but the code gets short
      Official docs say: The by-clause in the supertype list for "MainActivity" indicates that "AnalyticsLoggerImpl() object" will be stored internally in objects of "MainActivity" and the compiler will generate all the methods of BaseImplementation that forward to "AnalyticsLoggerImpl() object"

  • @vikaspandey7053
    @vikaspandey7053 Před rokem

    10:00 so it is same like having the deeplinkhandler or the analytics logger injected in the activity class.

    • @PhilippLackner
      @PhilippLackner  Před rokem +2

      No it's not. Then you couldn't pass the activity as argument for a parameter of type AnalyticsLogger. One big benefit we get with inheritance which we also have with delegation

    • @vikaspandey7053
      @vikaspandey7053 Před rokem

      @@PhilippLackner yes, now i revisited analyticsLogger part, we can say it Inheritance by delegation, Can understand it is following single responsibility principal.

  • @jonrysimbolon605
    @jonrysimbolon605 Před rokem

    why i get "Heavyweight property delegation" if access delegation ?

  • @TheMikkelet
    @TheMikkelet Před rokem

    Delegates and inheritance are not sport teams, you can support both at the same time, and you can use both appropriately. One isn't superior to the other. Use the right tools for the job!

    • @vibovitold
      @vibovitold Před rokem

      it is kind of superior though. other things being equal, composition is generally better than inheritance, as it leaves more flexibility, gives better transparency, and sidesteps a lot of known problems related to inheritance (fragile base class, yo-yo problem etc.).
      in my opinion, as a rule of thumb, if inheritance hierarchy exceeds two levels (some parent, some child) - and you're not writing something like an SDK - the question should be "why", not "why not".

  • @michaberkowicz8239
    @michaberkowicz8239 Před rokem +1

  • @RaajKanchan
    @RaajKanchan Před rokem

    How much will it cost to enroll your "The Ultimate PL Course Bundle" online course. Can you convert it in Indian currency and let me know.

  • @mattgraves3709
    @mattgraves3709 Před rokem

    Thanks by MattGraves

  • @RavenGhostwisperer
    @RavenGhostwisperer Před rokem

    Having fun programming? Just "override fun" ;)

  • @jcgranda9383
    @jcgranda9383 Před rokem

    I'm a little confused with interface segregation principle, Is not the same?

    • @fabianomello9141
      @fabianomello9141 Před rokem +2

      Interface Segregation Principle: If a class implements an interface but doesn't need all of its methods, it may be a sign that this interface should be split into smaller ones. Delegation: alternative to inheritance.

  • @clamum9648
    @clamum9648 Před rokem

    Could you also do what you demo'd but instead of doing the "AnalyticsLogger by AnalyticsLoggerImpl()" inheritance, just do "AnalyticsLoggerImpl()"? I know you're supposed to program to abstractions and not concrete implementations, but would that be valid? Then there would be no delegation at all in it. I just feel like the delegation thing is kinda weak in this example, like it just seems like it's driven primarily on inheritance still. Maybe I'm missing your point though big 🐕.

    • @PhilippLackner
      @PhilippLackner  Před rokem +2

      Then you can't treat your activity as an analytics logger (like passing it as argument for a parameter of type analytics logger) which is one of the main benefits you get from inheritance