Full Guide to Delegation in Kotlin - Android Studio Tutorial

Поділитися
Вставка
  • Опубліковано 6 вер 2024
  • 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/...
    Subscribe to my FREE newsletter for regular Android, Kotlin & Architecture advice!
    pl-coding.com/...
    Join this channel to get access to perks:
    / @philipplackner
    Get the source code for this video here:
    github.com/phi...
    Join my Discord server:
    / discord
    Regular programming advice on my Instagram page: / _philipplackner_
    Checkout my GitHub: github.com/phi...
    You like my free content? Here you can buy me a coffee:
    www.buymeacoff...

КОМЕНТАРІ • 204

  • @PhilippLackner
    @PhilippLackner  2 роки тому +92

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

    • @voidpointer398
      @voidpointer398 2 роки тому +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 2 роки тому +20

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

    • @pa1shetty
      @pa1shetty 2 роки тому +15

      Its fine. But sound can be reduced.

    • @rhen4610
      @rhen4610 2 роки тому +2

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

    • @tibrec8
      @tibrec8 2 роки тому +1

      Its awesome 😎

  • @Zeeshan-Syed
    @Zeeshan-Syed 2 роки тому +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  2 роки тому +4

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

    • @itsjeffo
      @itsjeffo 2 роки тому

      Don't forget the credits. :)

  • @acercow
    @acercow Рік тому +2

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

  • @ubersticks
    @ubersticks 2 роки тому +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 2 роки тому +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 2 роки тому +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 4 місяці тому

      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.

  • @NeerajGupta-of9fy
    @NeerajGupta-of9fy 2 роки тому +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.

  • @bboydarknesz
    @bboydarknesz 2 роки тому +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! 👍🏿

  • @spicyunicornmilkfarmer
    @spicyunicornmilkfarmer 2 роки тому +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.

  • @arthurgomes9248
    @arthurgomes9248 Рік тому

    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.

  • @clivejefferies
    @clivejefferies 2 роки тому

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

  • @viniciuscoscia
    @viniciuscoscia 2 роки тому

    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.

  • @Czarnini
    @Czarnini 2 роки тому +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  2 роки тому +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 2 роки тому +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 ;)

  • @andreshoyo8330
    @andreshoyo8330 Рік тому

    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.

  • @redaelmadini
    @redaelmadini 2 роки тому +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.

  • @sivaganeshkantamani2976
    @sivaganeshkantamani2976 2 роки тому +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.

  • @stanleykou5643
    @stanleykou5643 2 роки тому +1

    Super excellent way of using delegation!

  • @MrFilo122
    @MrFilo122 2 роки тому +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  2 роки тому

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

    • @st4849
      @st4849 2 роки тому

      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 2 роки тому +1

      Could you elaborate? This looks useful for my use cases

    • @sanek1985t
      @sanek1985t Рік тому

      @@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 Рік тому

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

  • @pranaym143
    @pranaym143 Рік тому

    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.

  • @GeertBerkers
    @GeertBerkers 2 роки тому +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 2 роки тому

      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 Рік тому

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

  • @joseangelsanchez4753
    @joseangelsanchez4753 2 роки тому

    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!

  • @ketanchaurasiya2514
    @ketanchaurasiya2514 2 роки тому

    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.

  • @veys7035
    @veys7035 Рік тому

    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 Рік тому

      "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.

  • @Guilo583
    @Guilo583 2 роки тому

    Thanks for Video. I keep improving by watching your tutorials

  • @prageeth4855
    @prageeth4855 2 роки тому

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

  • @DerCheckerzeigts
    @DerCheckerzeigts 2 роки тому

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

  • @HakikatArayan
    @HakikatArayan 2 роки тому

    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.

  • @dakopyc
    @dakopyc Рік тому

    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!

  • @Usam43
    @Usam43 2 роки тому

    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

  • @GK-rc3fd
    @GK-rc3fd 2 роки тому

    Best explainer I have ever seen. Thanks @Philipp

  • @rafaelrodriguez3753
    @rafaelrodriguez3753 Рік тому

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

  • @artemhryhorov4382
    @artemhryhorov4382 2 роки тому

    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  2 роки тому

      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

  • @hinocenciopaulo
    @hinocenciopaulo 4 місяці тому

    Excellent explanation

  • @brgame8
    @brgame8 2 роки тому +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.

  • @mehulbisht9708
    @mehulbisht9708 2 роки тому

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

  • @FlorianMeyer1983
    @FlorianMeyer1983 2 роки тому

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

  • @utkarshsharma7932
    @utkarshsharma7932 Рік тому

    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.

  • @LazyTram911
    @LazyTram911 Рік тому

    You are a wizard))))
    FANTASTIC

  • @sohaibkhan845
    @sohaibkhan845 8 днів тому

    very well explained.

  • @ma.fouani
    @ma.fouani 2 роки тому

    great stuff! thank you for your great effort

  • @anudeepreddygopu8500
    @anudeepreddygopu8500 2 роки тому

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

  • @androidpc9656
    @androidpc9656 Рік тому

    Nice,Please post more kotlin videos

  • @armandoavila4615
    @armandoavila4615 2 роки тому

    Thank you, Philipp! ❤️

  • @xandrviking1113
    @xandrviking1113 Рік тому

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

  • @anorov_hasan
    @anorov_hasan Рік тому

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

  • @amrutapatil8287
    @amrutapatil8287 Рік тому

    Phillip please have a video on AOSP

  • @ampo2004
    @ampo2004 Рік тому

    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.

  • @evgeniivorobei69
    @evgeniivorobei69 Рік тому

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

  • @burakkarabekir2863
    @burakkarabekir2863 2 роки тому

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

  • @user-vt2ys8xu2o
    @user-vt2ys8xu2o 4 місяці тому

    Very good tutorial

  • @miladhashemzadeh5626
    @miladhashemzadeh5626 2 роки тому

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

  • @austinealagi
    @austinealagi 2 роки тому

    You are a life saver thanks for this.

  • @sameershelar2000
    @sameershelar2000 2 роки тому

    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.

  • @Nemesislh
    @Nemesislh 2 роки тому

    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  2 роки тому

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

  • @user-cz6te1gt8q
    @user-cz6te1gt8q 10 місяців тому

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

  • @MaffinMr
    @MaffinMr 2 роки тому

    Nice explanation, thank you

  • @samsadch
    @samsadch Рік тому

    how to add observer for onConfigurationChanged() callback?

  • @manusarangal449
    @manusarangal449 6 місяців тому

    Amazing!

  • @alco8864
    @alco8864 2 роки тому

    This is awesome!!

  • @frank4pickerson
    @frank4pickerson 2 роки тому

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

  • @thils7619
    @thils7619 2 роки тому

    Nice Information. Thank you.❤

  • @ho-thtmarketingonline711
    @ho-thtmarketingonline711 2 роки тому

    Thanks man 👍

  • @osisuper98
    @osisuper98 2 роки тому

    Man is so good 👏🏾

  • @romanpavliuk2301
    @romanpavliuk2301 2 роки тому

    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  2 роки тому +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 2 роки тому

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

  • @foreverrafs
    @foreverrafs 2 роки тому

    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

  • @syedovaiss
    @syedovaiss 2 роки тому

    Bro you are a gem 💎

  • @jonrysimbolon605
    @jonrysimbolon605 Рік тому

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

  • @sakibsyed7626
    @sakibsyed7626 2 роки тому

    Thanks for amazing topic

  • @manshalkhatri9289
    @manshalkhatri9289 Рік тому

    Helpful !

  • @santoshs490
    @santoshs490 2 роки тому

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

  • @haykmkrtchyan7093
    @haykmkrtchyan7093 2 роки тому

    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  2 роки тому +1

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

  • @miltonpimentel3769
    @miltonpimentel3769 2 роки тому

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

  • @aviator1472
    @aviator1472 10 місяців тому

    Thanks!

  • @abuiman5251
    @abuiman5251 Рік тому

    Thanks bro👍🏻

  • @jarvis2913
    @jarvis2913 2 роки тому

    Very Informative thanks

  • @mustafaammar551
    @mustafaammar551 2 роки тому

    VERY COOL
    YOU ARE THE BEST👍👍👍👍

  • @RaajKanchan
    @RaajKanchan 2 роки тому

    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.

  • @brunodiaz6100
    @brunodiaz6100 2 роки тому

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

  • @ryszardmachmudow9175
    @ryszardmachmudow9175 2 роки тому +1

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

  • @abada-s
    @abada-s 2 роки тому

    Impressive 🔥

  • @tibrec8
    @tibrec8 2 роки тому

    🙏 man good job

  • @berkedel
    @berkedel 2 роки тому

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

    • @PhilippLackner
      @PhilippLackner  2 роки тому +1

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

  • @dRaiKable
    @dRaiKable 2 роки тому

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

    • @VivekSharma-qw5ky
      @VivekSharma-qw5ky 2 роки тому

      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"

  • @harshpratapsingh1638
    @harshpratapsingh1638 2 роки тому

    Great explanation bro
    please make a tutorial on coroutines also🙂

  • @Talaria.School
    @Talaria.School 2 роки тому

    Thanks

  • @John-qt6qk
    @John-qt6qk 2 роки тому

    Thanks Philips

  • @shrinivasmanjithaya2112
    @shrinivasmanjithaya2112 2 роки тому

    Nice one..

  • @brunodiaz6100
    @brunodiaz6100 2 роки тому

    You're my God

  • @mkc0321
    @mkc0321 Рік тому

    amazing

  • @nipunshah1373
    @nipunshah1373 Рік тому

    This concept seems similar to Mixins !

  • @michaberkowicz8239
    @michaberkowicz8239 2 роки тому +1

  • @SaherAlSous-welcomes-you
    @SaherAlSous-welcomes-you 2 роки тому

    thank you!

  • @vikaspandey7053
    @vikaspandey7053 2 роки тому

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

    • @PhilippLackner
      @PhilippLackner  2 роки тому +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 2 роки тому

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

  • @jcgranda9383
    @jcgranda9383 2 роки тому

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

    • @fabianomello9141
      @fabianomello9141 2 роки тому +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.

  • @TheMikkelet
    @TheMikkelet Рік тому

    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 Рік тому

      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".

  • @LightDante
    @LightDante 2 роки тому

    I still cannot get when to use deligation

  • @emmanuelmtera5936
    @emmanuelmtera5936 2 роки тому

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

  • @clamum9648
    @clamum9648 2 роки тому

    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  2 роки тому +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

  • @RavenGhostwisperer
    @RavenGhostwisperer 2 роки тому

    Having fun programming? Just "override fun" ;)

  • @mattgraves3709
    @mattgraves3709 2 роки тому

    Thanks by MattGraves

  • @software231
    @software231 2 роки тому

    Need explanation with example

  • @uroskekovic4620
    @uroskekovic4620 2 роки тому

    Im trying to use delegation for showing and hiding progress bar in single activity app. My single activity app has progress bar in the app bar layout and fragments should show and hide it on demand. I created two interfaces:
    //implemented by activity:
    interface ProgressBarActivity {
    fun showProgressBar(isVisible: Boolean)
    }
    interface ProgressBarControls {
    fun showProgressBar(isVisible: Boolean, activity: Activity)
    }
    and implementation of ProgressBarControls:
    class ProgressBarControlsImpl : ProgressBarControls {
    override fun showProgressBar(isVisible: Boolean, activity: Activity) {
    if (activity is ProgressBarActivity) {
    activity.showProgressBar(isVisible)
    }
    }
    }
    Could this be done in a better way?

    • @PhilippLackner
      @PhilippLackner  2 роки тому +1

      Why do you need that, showing a progress bar is literally one line either way 😅

    • @uroskekovic4620
      @uroskekovic4620 2 роки тому

      @@PhilippLackner Overengineering 😅