![Dave Leeds](/img/default-banner.jpg)
- 27
- 149 947
Dave Leeds
เข้าร่วมเมื่อ 18 ก.ย. 2022
Applying the State Pattern in Kotlin
When our objects behave differently in different states, then it can be helpful to apply the State Pattern. Today, we'll look at code that could benefit from the State Pattern, we'll apply a traditional State Pattern from the classic Gang of Four Design Patterns book, and then we'll see how we can modernize it and reduce boilerplate by using some of Kotlin's language features.
✨ New to Kotlin? Start your journey here: typealias.com/start/
... or pick up the new Leanpub Edition for offline access and more! book.typealias.com/
🚀 Get the inside scoop on everything I'm working on - join my new email newsletter!
Sign up here: newsletter.typealias.com/
📺 Watch Episode #1 of the TypeAlias Show Livestream:
th-cam.com/users/liveS_JKbmN_A8o
📚 Chapters
00:00 Introduction
00:16 Example Code
02:16 Classic State Pattern
06:50 Modernized State Pattern in Kotlin
11:58 Wrap-up
✨ New to Kotlin? Start your journey here: typealias.com/start/
... or pick up the new Leanpub Edition for offline access and more! book.typealias.com/
🚀 Get the inside scoop on everything I'm working on - join my new email newsletter!
Sign up here: newsletter.typealias.com/
📺 Watch Episode #1 of the TypeAlias Show Livestream:
th-cam.com/users/liveS_JKbmN_A8o
📚 Chapters
00:00 Introduction
00:16 Example Code
02:16 Classic State Pattern
06:50 Modernized State Pattern in Kotlin
11:58 Wrap-up
มุมมอง: 4 003
วีดีโอ
Applying the Decorator Pattern in Kotlin
มุมมอง 4K14 วันที่ผ่านมา
The Decorator Pattern allows us to augment the behavior of an object - without the object itself knowing about it! In this video, we'll start with code that could benefit from this pattern. Then we'll apply the Decorator Pattern using the classic approach as outlined in the original Gang of Four book. Finally, we'll modernize the pattern using some of Kotlin's language features. ✨ New to Kotlin...
Applying the Strategy Pattern in Kotlin
มุมมอง 6Kหลายเดือนก่อน
The strategy pattern is one of my favorites from the original Design Patterns book. In this video, we'll see why the strategy pattern is helpful, we'll apply the pattern in Kotlin, and then we'll see how we can use some of Kotlin's language features to put a more modern spin on it. ✨ New to Kotlin? Start your journey here: typealias.com/start/ ... or pick up the new Leanpub Edition for offline ...
Coroutines: Concurrency in Kotlin
มุมมอง 9Kหลายเดือนก่อน
In this presentation, I give an overview of coroutines in Kotlin, including the basics of coroutines, how they can be used for concurrency and parallelism, and how structured concurrency helps ensure coroutines are cleaned up in response to cancellations and exceptions. The content for this presentation is largely based on chapter 20 of Kotlin: An Illustrated Guide, which you can read online he...
Kotlin Code Reuse: Composing like you're Inheriting
มุมมอง 9K2 หลายเดือนก่อน
The classic Design Patterns book introduced the principle of favoring composition over inheritance. In this video, we'll explore what the authors meant by this principle, we'll consider the characteristics that are affected by it, and we'll look at an underrated Kotlin feature that can change our perspective on it! ✨ New to Kotlin? Start your journey here: typealias.com/start/ ... or pick up th...
7 Features in Kotlin's Standard Library that You Might Have Overlooked
มุมมอง 6K2 หลายเดือนก่อน
Are you still using the Java API when you don't have to? Are you rewriting functions that are already in the standard library? In this video, I cover seven features in Kotlin's standard library that you might have missed or forgotten about. 🕙 What days and times work best for you for a livestream? forms.office.com/r/9vpuJv0PMq ✨ New to Kotlin? Start your journey here: typealias.com/start/ ... o...
Reified Type Parameters
มุมมอง 3.6K2 หลายเดือนก่อน
Learn what happens to type arguments when our Kotlin code is compiled, and how we can step around certain type erasure problems with reified type parameters. 📽️ Inline, Crossinline and Noinline video: th-cam.com/video/T9sAlxqYFYc/w-d-xo.html ✨ New to Kotlin? Start your journey here: typealias.com/start/ ... or pick up the new Leanpub Edition for offline access and more! book.typealias.com/ 🚀 Ge...
The Essence of Coroutines
มุมมอง 10K3 หลายเดือนก่อน
In Kotlin and other languages, coroutines are often seen as just async/await. But the essence of coroutines is much simpler and easier to understand. In this video, I'll boil down coroutines to their most fundamental properties.
Looking Forward to Kotlin 2.0
มุมมอง 17K3 หลายเดือนก่อน
The Kotlin 2.0 release candidates are coming along. Let's learn what 2.0 is all about, and explore some of the updates that I'm most looking forward to! K2 Compiler Performance Benchmarks: blog.jetbrains.com/kotlin/2024/04/k2-compiler-performance-benchmarks-and-how-to-measure-them-on-your-projects/ K2 Performance Metrics Project: github.com/Kotlin/k2-performance-metrics K2 Compiler Migration Gu...
Three Simple Rules for Subtypes
มุมมอง 2.4K4 หลายเดือนก่อน
Inheritance, declaration-site variance, and type projections are all based on three simple rules for subtypes. Once you understand those three rules, you can reason your way through inheritance and generic variance. In this video, we'll learn what those three rules are, and then see how they apply to a variety of Kotlin language features! ✨ New to Kotlin? Start your journey here: typealias.com/...
Inline Functions: inline, crossinline, and noinline
มุมมอง 5K4 หลายเดือนก่อน
Most of us understand the basics of what it means to inline a function, but in Kotlin, there are some nuances that affect how you can use lambdas that are passed to them. In this video, we'll cover the basics of inline functions, and then learn about those nuances - and how we can use crossinline and noinline to get the behavior that we want. ✨ New to Kotlin? Start your journey here: typealias....
Every Kind of Class in Kotlin
มุมมอง 10K5 หลายเดือนก่อน
Kotlin offers many different kinds of classes, and in this video, we're gonna look at all of them - regular classes, nested classes, inner classes, data classes, inline value classes, enum classes, sealed classes, and annotation classes! By the end of this video, you'll understand these different kinds of classes and when to consider using each one. ✨ New to Kotlin? Start your journey here: typ...
Type Projections... and why they work!
มุมมอง 3.6K5 หลายเดือนก่อน
Let's dive into the world of Kotlin's type projections! We can't always use the `in` or `out` modifiers in a generic class, but don't sweat it - we can still get the generic subtypes we want! This video shows how you can use type projections to get generic subtyping - even for types that are in library code! In less than 9 minutes, you'll learn both how you can use them and why they work. 📘 Kot...
Variance... without Generics!
มุมมอง 6K6 หลายเดือนก่อน
Did you know that you can use covariance and contravariance in Kotlin without generics? Unlock the mental model of generic variance by first understanding how variance works with regular type hierarchies! ✨ New to Kotlin? Start here: typealias.com/start/ ... or pick up the new Leanpub Edition! book.typealias.com/ 🚀 I just launched a new email newsletter! Sign up here: newsletter.typealias.com/ ...
A Tour Through Konsist with Igor Wojda
มุมมอง 2.1K10 หลายเดือนก่อน
A Tour Through Konsist with Igor Wojda
Easy SharedPreferences with Delegated Properties in Kotlin
มุมมอง 8Kปีที่แล้ว
Easy SharedPreferences with Delegated Properties in Kotlin
5 Fun Ways to Use Extension Functions in Kotlin
มุมมอง 12Kปีที่แล้ว
5 Fun Ways to Use Extension Functions in Kotlin
Peek Behind the Scenes of TypeAlias.com - Dave Leeds on Kotlin
มุมมอง 1.3Kปีที่แล้ว
Peek Behind the Scenes of TypeAlias.com - Dave Leeds on Kotlin
Thank you so much for the great talk! One of the best explanations of coroutine concepts I've seen out there!
Hey, thank you so much, Yan! I appreciate that!
Such a great explanation. Great job, Dave, as always!.
Hey Dave. Great seris 👍I think you should cover Visitory as well. I've talked about it here at GDG a while ago th-cam.com/video/i7dHrLej2bg/w-d-xo.html
Thanks for the inspiring video. I would like to see the Chain of Responsibility pattern next. I came up with a few implementation variants and would like to see your version.
Thanks, Peter! Yeah - I had played with Chain of Responsibility implementations recently, but I wasn't as happy with my ideas for it at the time, so I moved on to other patterns. I'll pull up my notes for it and see if I can look at it with a fresh perspective!
I liked it very much. I would add naming parameters in the lambda for clarification. enum class UserState( val signUp: User.(email: String) -> Unit, ....
wow that was awesome! thanks for sharing!
loving the design pattern series!
Thanks, Fabiano! I'm glad it's resonating so well with everyone!
Excellent presentation! It would be great if you could do something about context receivers and compare them with typeclasses
Thanks so much! I'll add that to my running list of video ideas!
I think your approach is much better than the standard approach; it is concise, well packed and more understandable even for beginners.
Thanks so much, Mike! I really appreciate that!
great content as usual
You’re awesome 🎉 I haven’t learned a new language this fast, ever before! You sir are great at explaining! Keep this up!!
Oh wow, that's really great to hear - really glad that you're picking it up so quickly! I'll keep at it!
Mind blown by all your design pattern videos so far. The format of these videos is really good: take a real life code scenario, refactor the code to use the pattern, followed by some crazy kotlin. And all this in about 12 minutes! Loving it!
Thanks so much, Tony! It sounds like the format is working well for everyone, so I'll keep at it!
I thought i am too good at kotlin but now 🥲
Loving your videos. Keep them coming! Personally, I would have used a sealed class/interface instead of the enum. Main reason being, you can separate each implementation in its own file (if the number of enums keeps increasing you end up with a huge file)
Thanks, Mankin! Yes, that's a good point. I think also as you start getting more distance between each enum entry, they start to feel less optimal as a choice. With the 5-parameter constructor that I had at the end of the video, they started spreading out a bit, but at least they did all fit on a single screen. But like you said, if we were to add a few more entries, it could start to become more difficult to keep up with them!
This was oddly satisfying, felt like a TLC show for developers :)
Hey, thanks Zeynep! I'm glad you enjoyed it! 🙂
Very nice. Good review of the State Pattern and how Kotlin can uniquely implement it. Thanks for posting this
Great video, can you show shortcuts toasts, like in presentation mode? TY
Thanks - I've had a lot of requests to show shortcuts lately! My keyboard shortcuts are very customized, but most people are particularly interested in how to edit with multiple carets, so I'm going to cover that at the upcoming livestream. 👍
This is AMAZING! Regarding 7:19: if we want a more flexible code structure than the rigid enum class, but we still want an exhaustible type, we can of course make the state a sealed interface or sealed class instead!
Yes, thanks Arthur! I probably should have just done that in the video - I can't think of any reason not to make the interface sealed here. 👍
awesome!!! Thanks Just need one more step -> logout and change state from AUTHENTICATED to ANONYMOUS
Yes, good thinking, Pavlo! 👍
For me personally "state" - is something that holds data & state's name is the marker aka description of action that must executed for each of them. For this particular scenario seems like state can also execute some logic (which in real life will not be as just printing some debug line) and that makes state itself a lot more complex thing that possibly requires a dependency to other classes --> a lot of business logic happening inside. I would think of something more appropriate for execution, like StateManager/StateHandler/etc that will execute business logic for each state change
Maybe the term "state" here is closer to the term "state machine" than "object state"
While working on this video, I did feel like there's a bit of irony in that these state objects hold literally no state of their own. Yes - we basically made a finite state machine, and that's the sense of the word being used here. Maybe the term "State Pattern" was more intuitive back when the GoF book was written (I was just a high school kid writing QBasic at that point), but I can definitely see how it could be a confusing term these days!
nicee
My ocd is kicking in on my code 😂
There certainly is something nice about having all that code line up like that! 🙂
A topic for future videos would be how to do state transitions (ex. from unverified to authenticated) and deal with unsupported operations (ex. anonymous can't edit a profile)
Transitions should be as simple as swapping the instance of state in the context. Unsupported operations should probably fail with IllegalStateException, a convenient way to throw it is to call the "fun error(message: Any): Nothing" function from the Kotlin standard library.
I'm currently writing C# in my day job and I wish I could end up with code similar to your final Kotlin version yet C# does not support "top level functions". Another thing to keep in mind is that in your class based version you could instantiate the same validator even tough it makes no sense since as you said they have no state at all. You most likely want to use `object` rather than `class` if you want to keep the class based approach.
Great video! but I have a question, why use objects instead of classes?
You certainly can use a class if you like! Even in the GoF Design Patterns book, they mention a lot of flexibility in how you can implement this one. If you've got states that have no instance variables of their own, you might prefer to keep them as singletons, as we're doing here, to avoid the cost of instantiating the additional objects for each user - the book points out that when we do that, the states are also very similar to flyweights from the Flyweight Pattern. For cases where that's not as important - which, these days, might be most cases - you can just instantiate a new state object each time, which would clean up the function signatures (because you wouldn't have to pass the user object for each operation).
@@typealias thanks for explaining!
Waiting for all design petters videos from you!
You want all of the design patterns in a single video? That might end up being a pretty long video! 🙂
@@typealias ofc not in single video. One design pattern per video is great
Haha, okay gotcha! I'll keep at it, then - only about 20 videos to go! 🙂 I actually might end up having to do a single round-up video for a few of the "leftover" patterns that wouldn't really warrant their own videos. Like - singleton wouldn't take too long to explain. And for some of the others, Kotlin doesn't add much. Anyway, thanks for clarifying!
@@typealias omfg this is my dream to see these videos! Thank you so much! Can't wait!
Now add another function to the interface and you didn't accomplish anything with this pattern
Well, adding another function would require us to revisit each of the state objects - I think that's what you're getting at. Even then, though, I would find it easier to manage the smaller, more focused functions that are grouped by state rather than large functions that are each trying to juggle different implementations for multiple states. (But if I'm misunderstanding your point, let me know!)
You're a gem for Kotlin learning
Really nice
Thanks A couple of "PR" comments.. :D - you ve got a bug in the end in the anonymous signup function - you are printing `email` from the receiver instead of `it`, so it will print null.. - when declaring lambdas like (String) - Unit, its better to keep the names of params, i.e. (email: String) -> Unit instead of stripping it - otherwise it becomes hard to read I would agree - thats a bit too far of a refactoring :)
Ahhh, yes you're right! Thanks for catching that. Should be printing `it` instead. 😅
I also prefer typed parameters in lambda for other developer's sanity.
Explicitly writing the lambda parameters is always an option, of course. It all depends on the team's conventions, or in case of solo projects, the developer's preferences.
@@ArthurKhazbs Absolutely, you project your rules, but here we are educating people, it seems :) and when I see such in the code: `val editProfile: (String) -> Unit` - how am I supposed to understand what would be passed here? And in this case I see at least 2 solutions - either name it `(email: String) -> Unit` or use tiny type - `value class EmailAddress(val email: String)` - then its inferred in the type what will be passed.
Thank you. My heart started to ache a bit when you used semicolons🙃It definitely looks nice when the code is complete, but I can see how hard would it be to maintain the logic when it's written in one line)
Yeah! I almost never use semicolons... In this case, at a glance it looks like it might be part of the println() statement, so it'd be easy to miss what's happening!
really like your intellij shortcut game
Ah, thanks. I'm not this fast in real life. In most videos, I end up doing a bit of post-production work to smooth things out. In the next livestream, I'm planning to cover some tips about using multiple carets, which accounts for most of that shortcut game.
@@typealias it's a cool skill to have. I love intellij IDEs but for web I have to go to Vscode but have enabled intellij keybindings there
Interesting. I expected something with delegates, though. Would that make sense?
Well, with class delegation, we unfortunately can't change out the implementation at runtime. So whatever the implementation is at the time the class is instantiated, that's what it'll be for the life of the object. (Or did you have something in mind with property delegation rather than class delegation...?)
Great video as usual!
I appreciate it, Houssam! Thanks for being at the premiere!
amazing and informative as usaul! Thanks so much Dave. You always rock me!
Excited
Thank you for the great content. I really love the way you explain things. I found you looking for coroutines information and I've looked at so many of your other videos. Great content. Keep yo the good work.
This is such a great breakdown on coroutines! Thank you!
Has anyone experienced connection issues between two Android devices using Kotlin, either with Ktor or Java's original socket, when the devices receive new IP addresses on the same local network but through different access points? Specifically, when two Android devices are connected and initially receive IP addresses from the same router and access point, the connection works fine. However, if one of the devices changes its IP address by switching to another access point within the same network, the connection gets disrupted. Has this scenario been tested with 'kotlin.rpc'?
I think default inline is just a suggestion to the compiler and cannot be enforced
Didnt expected it, but I learned few things on the way. TY!
This is art ! :-)
Dave, I've watched several videos of yours and I can tell that you are definitely the BEST Kotlin teacher on the planet. I'll buy your book. If you have a paid Kotlin and/or KMP course, I will also buy it !
Hey, thank you so much, Emmanuel - that's very kind of you to say! I haven't got any online courses just yet, but I'm planning to start working on them after I put the finishing touches on the book.
You are doing a great job, Dave! Bravo!
Great explanation. Every time I watch your videos, I learn something new about the Kotlin language.
Kotlin is great, and so is your way of delivery! I like the topic of Design Patterns, especially with your demonstrations!
Thank you so much, Sergey! I'm glad there's been so much great interest in the topic. I'll keep at it!
Low-key best Kotlin related channel I've ever found.
Hello Dave. I would like to become a Kotlin and Android Studio developer. I started with Google codelabs to start understanding the language. My issue is that I never programmed and I have no knowledge of logic. I can still continue or it will be a waste of time if I don't have a programming background. And if so, what do you recommend to start? I am 44 years old and even if it is not for the job market I want to learn for myself. Thank you very much for your time.
Hey, that sounds great! Everyone starts somewhere, and you don't need a logic background to get going. As long as you've got an excitement about programming, and as long as you're willing to take time to learn things, you'll do fine. I'm almost done authoring a book about Kotlin, and my aim was to make it accessible, even to those without a programming background. You can read it online here: typealias.com/start/ I hope that helps you get started!
Very well explained.
I can't wrap my head around about final kotlinish form
Yes, for developers who aren't already familiar with the approach, it can require some thought to figure it out. Ultimately, it's really just function composition using extension functions, where each Logger calls the previous in the chain until it gets to the underlying `consoleLogger`. So, the function created by withUniqueId() calls the function created by withThreadName(), which calls the function created by withDateTime(), which calls the function assigned to consoleLogger.