Coding Blocks - Delegate all the things!

Episode Date: March 16, 2015

This week we tackle one of life's great quesitons, does Jack Bauer give high fives? Also, we go over everything you need to know about delegates, events, callbacks and closures in .NET. Big thanks to... @kappelcodesalot for being the inspiration for this episode!

Transcript
Discussion (0)
Starting point is 00:00:00 You're listening to Coding Blocks, Episode 24. Subscribe to us and leave us a review on iTunes, Stitcher, and more using your favorite podcast app. And visit us at CodingBlocks.net where you can find show notes, examples, discussion, and more. And send your feedback, questions, and rants to comments at CodingBlocks.net. And follow us on Twitter at CodingBlocks. Or head over to www.codingblocks.net where you'll find all our social links at the top of the page. And with that, welcome to the CodingBlocks podcast.
Starting point is 00:00:31 I'm Alan Underwood. I'm Joe Zach. And I'm Michael Outlaw. That happened so fast. Yeah, I decided to let mine draw out a little bit. I'm messing with you guys. I should do it in a southern accent. I should have Alan say it for me.
Starting point is 00:00:44 Wait, I don't have a southern that's a good one all right welcome to the show all right yeah so uh first off we want to start a little bit of news um so first off we want to thank you guys we got some more reviews helium filled stamp kicking bach and mackie merg we also recently discovered that uh there's other reviews that we hadn't seen because they were on international versions of itunes including one america that uh maybe compared alan to a former u.s president uh so that was uh pretty awesome and uh so we're gonna have to gather those names up and say thank you uh but we appreciate it yeah and and just so you guys know we're actually experiencing some of the woes of the stitcher reviews i don't know why but they seem to intermittently work and we got some great
Starting point is 00:01:34 ones but we can't mention them because we can't see them right now right uh also um wanted to do a quick update on our New Year's resolutions? Nah. Wait, there was outlaws. All right. Well, I was still waiting on Alan to do the course on it. Well, I've got even more depressing news. So I've been working on a roguelike in C Sharp, just like a fun little game. And I just found today this guy, the Stuff with Stuff blog that we mentioned before. He did the really cool maze thing. He just open sourced his C Sharp roguelike today.
Starting point is 00:02:09 So that's a big bummer. Are you backpedaling? Are you going to switch? I might. I mean, I'm sure his is way better than mine. So I'm going to have to find that out. But thank you, Reddit, for ruining my night. So mine, I started doing this angular uh
Starting point is 00:02:27 you know course and what i found was i was getting really frustrated because all the angular stuff out there is just like oh you want to show like i don't know some pictures of phones like they have this phone cat example and it's like man that's not real world stuff i want things that people actually deal with logins. Man, how many people use phones? Right, right. But, you know, I wanted to get a little bit deeper. So I started, you know, looking at, all right, well, we need a login system.
Starting point is 00:02:54 Okay, well, now that you have a login system, how do you log down portions of the UI? Oh, my God. And so, yeah, it was a rabbit hole, right? So I started going further and further. Come back out of the hole there, Alice. No, I don't think so. I think that this is actually valuable. So I think the course that I'm going to be putting together is actually going to be a combination of,
Starting point is 00:03:14 and this is what it really looks like. It sounds like it's going to be a full-fledged authentication permission role system, plus there might be some JavaScript and Angular sprinkled in there. You got it. It's a little bit of everything. Hey, good summary. So, yeah, I'm actually going down that way, and I've made some progress. I've actually made some decent progress.
Starting point is 00:03:33 But the real question, though, is, is it Angular 2? No, you know what? That's really frustrating, and I might switch gears, because there was big news that came out that we should discuss that we didn't even have in the show notes. That's right. Oh, I threw a bomb in there. Angular 2 is actually being built with TypeScript.
Starting point is 00:03:51 What? Yeah. We'll leave a link in the show notes for that. A little joint venture there between Microsoft and Google? I mean, seriously, if anybody out there has a Windows phone, which I had done about a year or so. All five of you. I mean, dude dude it was ridiculous you couldn't get youtube on your phone because microsoft and google were battling back
Starting point is 00:04:11 i don't think that war has stopped no it hasn't but that's what's really weird like they are literally working together on angular 2.0 and it's being built with typescript so that's really cool stuff so when they release the developer tools for that, I may actually switch over and play with that. Um, but we'll see. Yep. Uh, also, I wanted to mention that this week, uh, we are doing a book giveaway. Uh, and yes, uh, the book that we're giving away is a book that we've talked about quite a bit. It's the design patterns book, uh, the gang of four that we've heard of this one yeah so it's an older book it's in uh it's a great book and so what we're talking about doing is basically if you come by the website and leave a comment on this this episode which is www.codingblocks.net
Starting point is 00:04:56 slash episode 24 just drop a comment in there uh say something and uh one of you will uh randomly win this book now wait a minute how do i know that this book is of any kind of value right is this like you know the 18th printing of this book i think there's only uh one edition ever i think we talked about that last time right ah and just to just to be clear this thing looks pristine like this this looks like he's never read it yeah i don't think he's ever opened it so So, yes, he spent $50 and it could be yours. That's right. So, no, the book's in great shape.
Starting point is 00:05:31 So we're giving away Joe's money. Yeah. Here today on the podcast, yes. That's how much we love you guys. So how do you get the book? Just drop a comment on www.codingblocks.net slash episode 24 for a chance to win. Yeah, tell us why you want it.
Starting point is 00:05:47 What if Jack Bauer wins? Jack Bauer wins. Chloe, get on the floor. I need a port on the firewall open now. Send it over to my screen. Do you think Jack Bauer gives high fives? What? This is almost like a Chuck Norris question.
Starting point is 00:06:03 I don't think he does hey wait hey have you guys ever done that you know go to google and type in find chuck norris no uh if you do that and then you hit i'm feeling like well it used to be and i'm feeling lucky it's not there anymore um it's a it's a nice little easter egg everybody should try it when they get home all right all right so anyways find chuck norris okay so of course i gotta do this now like i can't yeah all right so let's do it you can't like throw out something like that and then just tease it all right so find chuck norris and then if you click on the first link you gotta click on the first man it's not there anymore. Oh, it's there. Yeah, yeah, yeah. Someone captured it.
Starting point is 00:06:45 All right, so I'll go ahead. You can't tell. You can't. People have to experience this, man. But then they're just going to hear us like randomly laughing, and they're not going to understand why. They could go home and do this. All right, fine. Here, I'll tell you why I'm laughing.
Starting point is 00:06:57 The suggestions. That's why I'm laughing. Well, no. I liked it even the red error message. Pretty let's just say okay fine so as alan said go to google i'm giving them instructions okay calm down spoiler alert get go go go to google find chuck norris and like Alan said click on the first link and then read from there
Starting point is 00:07:29 and you got to read the whole page there's all kinds of things like read the left half too there's some good stuff there alright so back to the lecture at hand no tangents here we got a great Twitter question from Adrian Capple who, who's at Kappel Codes a lot.
Starting point is 00:07:49 And he asked us about good examples of delegates. And what I found when I was kind of like looking for one is that... Politicians. I didn't really like any of the examples. And I also couldn't explain it very well myself. So that was kind of the kicker for the show. So, yes, we're talking about delegates today all right everything you never wanted to know i mean always wanted to know yeah oh and i think it's worth noting we're mostly talking about c sharp because what does java not have delegates yes we couldn't find them
Starting point is 00:08:25 oh this isn't javascript javascript kind of has it we'll get into that later all right so uh i guess we just want to start off with like a high level overview let's do it sure all right cool so um uh if you haven't seen um delegates before it's it is kind of hard to explain and something a lot of newbie programmers kind of stumble on and experts do. And there's a lot of reasons for that. It is complicated. There's this kind of long, weird history and evolution. So a lot of things that you kind of Google for, you end up finding just older ways of doing things.
Starting point is 00:08:59 And there's these weird words like event and delegate. And a lot of times you'll see generics in there, and it's just kind of weird. So hopefully we can kind of simplify things and focus on the simpler way of explaining this, and hopefully you guys will get something out of it. So I guess at a high level, it's just a type-safe function pointer, which really just means that you can pass methods around as parameters. I guess at a high level, it's just a type-safe function pointer,
Starting point is 00:09:28 which really just means that you can pass methods around as parameters. So I can have a function that takes in another function and does things. And what that means is that I can, at runtime, take in and execute different methods. Well, let's just say, let's put it like this. Let's say that you want to have a method that can, that does some work. And, um, if there's any kind of error, maybe you want to allow the caller to pass in their own error handler that you can, you can call, right? How's that? Yeah, I like that. Right. so this gives you the ability this is a way for for that caller to be able to pass in their method right that you can then call right and you can execute and then you can handle the kind of uh the problems that arise just like you said
Starting point is 00:10:18 so absolutely and also um delegates are a really big part of the.NET language, or the CLR and C Sharp specifically. And the reason for that is that they're really the core of.NET's strategy for closures, callbacks, and events. And they've got some really cool tie-ins and some things that we've already talked about, like strategy design pattern and observer design pattern, which you can read about in the book that we're giving away. So before we go past this, though, let's make sure that everybody actually understands when we talk about a closure. And I think we might have mentioned this in the previous episode. But a closure is when some method can actually access variables outside itself, right? So that's a big thing. So it doesn't have like its own defined scope that it can't reach outside of.
Starting point is 00:11:05 Right. And we talked about this before the show a little bit. So it doesn't have like its own defined scope that it can't reach outside of. Right. And we talked about this before the show a little bit. I think the best example, at least for this episode of a closure, uh, is just the for each, right? The,
Starting point is 00:11:13 the link for each, it takes in, you know, like a Lambda expression, which is just a delegate and it can access variables that are defined other places in that function. Right. Yeah.
Starting point is 00:11:22 And when he's talking about for each, he's not talking about actually when you say for each and then var whatever in something. He's talking about the actual link statement where you have a collection and you say dot for each. Yep, another example would be like the where or any of those dot whatever extensions that take the funky little X arrow stuff.
Starting point is 00:11:39 Those are all examples of delegates and they're all examples of things that can kind of reach out to the parent scope to draw things back in that get executed in the context of that method call there. Yep. And then when he talked about callbacks, we actually also discussed this because I wanted to know where he was when we were talking about it. a particular method, as one of the parameters that you are calling in that method, you are passing in the function that you want that method to then execute when it's done doing something. So a callback is usually, hey, after you're done doing some arbitrary chunk of code,
Starting point is 00:12:16 run this other method that I want you to run at the end of it. So that's, you see it all the time in JavaScript. And so that's great for async, right? Yep, perfect for async because when something's done with a server, whether it's succeeded, failed, whatever, you want it to run some piece of code to carry on the next step. And then the events, somebody want to take that one?
Starting point is 00:12:40 I guess not. Okay, nobody was prepared for that one. Events are kind of interesting because they allow for easy extension of classes without – or extensions of behavior without actually having the subclass. So if you've ever seen things like methods like on before save and on after save or on before render, on after render. On button click. On button click.
Starting point is 00:13:04 Yep, things like that. So those are all basically these kind of hooks where you can hook in additional behaviors and um you know do things without actually having to subclass and then that's really useful because a lot of times you don't even necessarily know all the things when you're designing these classes that you want them to do and you want people to be able to kind of extend that behavior without mucking around with your stuff. Yep.
Starting point is 00:13:28 So I just wanted to make sure we cleared up what we were talking about there. So now we can move on. Yep. And really a big part of this too is it's the real heart of link. And I think it's a key part of the kind of C-sharp's awesomeness. But delegates predate link though.
Starting point is 00:13:43 They do. They do, but they are a necessary component so there would be no link without delegates and there's no link in java so not really anyway anyway just think it's awesome we're going to dive more into this later um also i wrote down here my notes that it's expressive and dynamic functionality in a dynamic world and so what that means is it just you know it lets you kind of treat these methods you said yes in a static world this is the best world yeah well you said dynamic but you meant static yes uh expressive and dynamic functionality in a static world there we go yeah all right and what i mean by that is um you're
Starting point is 00:14:21 basically taking in a variable that points to a method. And it can be different things at different times. And so that's just really powerful and easy to read too. And the last note I had here, we actually kind of mentioned this, but it allows for easy and controlled extensions. So you can kind of add these little hooks like on before something on after something and what's really cool about that and ties into episode seven where we talked about the solid principles is um this is a great example of the open close principle where um your objects if you you know you seal them up but still have these extension points these events then you are by definition open for modification uh oh sorry open for extension but closed for modification.
Starting point is 00:15:08 So you can't change my behaviors, but you can extend them, which is really cool. Yet another way to implement the template pattern. Absolutely. All right. So let's dig into these delegates. All right. So we've already said that they were type safe function pointers,
Starting point is 00:15:30 but do we really go into like why we need that? No, not yet. So let's see. We'll be a good, well, I mentioned the example of like, if you wanted to have a handler, if you want to have like an error handler to be called, you need to be able to pass in that pointer. You need to be able to pass in that method. But without a method pointer,
Starting point is 00:15:52 without the ability to point to that method, this is a horrible explanation. This is probably the problem. Delegates are definitely hard to explain. Here's an easy one. Let's say that you have something that – and we'll see later, and I think I'll even put together an example of an addition type delegate, right?
Starting point is 00:16:12 Let's say that you have some sort of UI that has the ability to take in two numbers, and then let's say that you have three buttons that say one's add, one's multiply, and one's divide, right? So now what you do is based on whatever button click happens, you're going to pass in one of your methods. You might have three methods. One's going to be multiply numbers, another one's going to be add numbers, another one's going to be divide numbers, right? So you could then take, you might have those, and you could pass them into a method based off what the button click was, right? So you have some math class out
Starting point is 00:16:45 there that you're going to call and you're going to pass these things that have the signature of int, int with a return int, right? So now you can say, hey, they clicked add. I want to pass in my method. But the only thing it cares about is that the signature is correct, right? It has a number, a number, and it's going to return a number. So that's one way with what we're talking about is the type safety of it. And that's why it matters is because all it cares about is the signature. As long as you pass it a method in through that, the pointer is going to work. Yep. And the person who built that button, they had no clue what you're going to be using it for, right? They just had, you know, they knew that when it clicked that they needed to do something that you instructed them to do.
Starting point is 00:17:30 Well, more importantly, they didn't know how you wanted to do it. They just know what they wanted back. Right. They knew, like, hey, you're going to need to pass in a couple values here, right? Let's say in the add example, right, you're going to need to pass in a couple of integers and I'm going to expect back an integer. I don't care how you get there. Yep. And also with this example, it's a great example. I wanted to mention the kind of the other part of the definition there, which is these are type safe function pointers with a built-in iterator. And so what that means is in this button example, you know, unbeknownst to
Starting point is 00:18:02 Alan, I could take his library and add sounds to it. And so when you click that multiply, not only does it run the event that he expects, but I can also play a certain sound effect for multiplication and different one for add. And these are things that I don't have to touch his code at all, I can just kind of extend that behavior. And this built in iterator knows how to go through and call each event that it needs to call. Yeah, respond to. That's actually one of the cool things. So I'll take it one step further. So now we're kind of jumping ahead into multicast delegates there, right? It is multicast delegates.
Starting point is 00:18:32 And so that's kind of one of the cool things, right? Let's say instead of the example where I said you had three buttons, add, multiply, and divide, let's say instead you had one button, but you had checkboxes next to each one that you wanted to happen, right you had a check box next to add check box next to multiply and then one by divide what you could do then when you hit that button you click it behind the scenes it's going to say hey add the add method to my event handler now add the multiply and now add the divide and then that way when that fires off it will you will sequentially go through them in the order that they were added. I guess though – and maybe this is just my own thinking though because when I think of callbacks versus events, I typically don't think of callbacks as there being many of them, right?
Starting point is 00:19:21 Like events, I definitely think, hey there could be multiple uh handlers that are going to get uh invoked right uh so multicast delegate but in the case of a callback i'm typically thinking hey there's gonna be one method that's coming back correct so um yeah that's an important distinction it's really hard to talk about delegates without talking about events but events are really like a special type of delegate. And so I wanted to give a quick example of a delegate that isn't an event. And basically that ties into the strategy pattern. And the example I've got here is like if you wrote like a chess simulator and your chess game might take any number of different strategies.
Starting point is 00:20:00 It might be the, you know, the Bobby Fisher fisher bot or the kasper ski bot or just something that makes random moves so you know totally taking the ui out of the situation when i create this game i could pass it basically an algorithm to use and one way of doing that would be to have a you know a delegate that takes in the board and returns a move right and then i could basically pass in uh well you know a method that knows how to do that i could swap that method out of runtime based on what the player selects it sounds like we're going to apply this to like every pattern so far yeah we've already said strategy we've talked about open close i mentioned template template yep oh the mediator pattern also comes into play oh we mentioned observers
Starting point is 00:20:38 so the the key thing that everybody needs to understand is all it really is, is when we say it's a pointer, you define this delegate thing, right? And you give it a method and you say, run this. So like, you know, D1, we'll call it the delegate, right? You pass in the method add. Well, you're actually going to say D1, open, close, paren, and it's going to run that add method you gave to it. So just to clarify so that you understand so when you're passing these things in that we were talking about earlier you're literally passing the delegate it looks like a variable but really what you're doing is you're passing
Starting point is 00:21:14 a reference to that method that can just be executed so it's like variable methods that's exactly what it is so so let me be a little bit more verbose then. So let's say, going back to the calculator example that you brought up, right? So let's say that we had a delegate with a signature of int, and we'll call it an add handler, and it takes in two ints. So it returns an int, but it takes in two ints. And in your variable example, so you create some var, and we'll call it atom,
Starting point is 00:21:49 and then you would have some handler that already implements a method with this signature so you could then create a new add handler and pass in the method that implements that.
Starting point is 00:22:06 Well, I don't want to say interface, but yeah, it's a signature signature. Thank you. So if you, if you had exactly what you said, so let's think about it. Let's break it out into its pieces then in the simplest scenario, right? The very first thing that you might have is you might have an addition method. So you're going to have a public int addition, open paren, int number one, comma, int number two. A public delegate int.
Starting point is 00:22:32 No, no, no. This is the method. This is the method we're defining, right? So this is your thing that does it. And that's the signature. So it returns an int because we said public int, and then the two parameters inside were int one and int two, right? Okay.
Starting point is 00:22:45 So that's what we've got. And then going back to your delegate, take it from there, how you would set up your delegate. So then you'd say the delegate signature would be public delegate int and add handler and then in parentheses int x, int y. Yep. And then so what you did is you just lined up the two signatures of those that delegate signature now matches the method signature but the thing is so just to be clear though uh going kind of going back to joe's multicast example is there could be multiple methods that all
Starting point is 00:23:18 implement that same signature that could be uh assigned to this delegate. Correct. So your delegate would be something more generic, and then if you had a multiply... Or I should say not to the variable, not to the delegate. The whole signature is what you care about, right? Because then you could do the multiply one like we talked about earlier. You'd have public int multiply, and then int1 and int2 inside the signature. And then that way way you could pass either
Starting point is 00:23:45 addition or multiply in there it doesn't care because they have the same signature and whatever is going to execute that on the other end it doesn't care it just knows what the signatures are but it but it kind of looks weird though like if if in that variable example because then you just see like hey i created some variable and like in my example, I called it atom, right? And now I'm going to say atom and then parentheses, you know, 3, 5. Yeah, you might call a delegate something like – So it looks kind of weird because now it's a variable, but instead of accessing it like you would every other variable that you've ever used, right, instead you're going to throw some parentheses on it and, you know, do stuff. You know, you're passing values. Yep yep yep and then there's some really cool c uh c sharp compiler
Starting point is 00:24:30 tricks that enable that to happen which we're going to talk about in a little bit but there's definitely some sugary magic going on there all right so we already covered the callbacks the closures um did we hit this part here yeah i think Yeah, I think we've already talked about it being a big part of link. Yep. And I just wanted to mention there again with link, a big part of what we kind of think of as link is being basically built around anonymous methods, which are in fact delegates. When you think about that where clause example we gave, you know, you do the whole like X arrow and then you need to do something that returns true or false. What's going on there in the background is that you've basically got a method there that takes it in a
Starting point is 00:25:08 type of t and returns a true or false so it's that's all the information that you need in order to do that where clause and you don't actually see that nasty delegate where there's no handlers there there's none of that weird stuff it's just uh you know a couple crazy characters all right so um i don't think we've talked about this what are handlers my brain explodes whenever i see the word handler i never know if that's the one that does the work or like it's the one that kind of hands off the work it handles the work so it doesn't actually do it right okay yeah because the doing part of this whole thing is the event the event does something or not not the event whatever's being called does some things and then you fire off the event you
Starting point is 00:25:54 basically say hey i'm done right and then the handler is what takes over from there right so do we mention that delegates were just another class, another object, another type? We haven't gotten into that yet. Because that's kind of key here. That really would explain well what Alan's talking about. We've talked about objects inheriting from system.object
Starting point is 00:26:17 and that's what delegate is. It's another type that inherits from that. It gets translated to that on compile. i thought it actually inherited from system.object so the delegate class does but when you use that delegate keyword see it's getting pretty confusing so delegate keyword does not define a class right that just kind of uh happens in the background um and we do have a section coming up where we're going to kind of talk about like how this actually works underneath the covers um and this is such a hard thing to talk about yeah so i see where
Starting point is 00:26:50 you're going with it though but yeah with the handler basically think of your on click right your button this is probably the simplest state so when when you actually click the button that fires off an event that event is going to be click your handler is your on click method that you created that says hey when this event gets raised i now need to do something so that's what your handler is it's actually the method that is going to respond to some event i guess the point that i was trying to make though is that like there's an object type that has some list of methods to call and an order in which it plans to call them, right? And when you call that guy,
Starting point is 00:27:33 that object is the one that is responsible for delegating who to call now, right? Okay, so that's a good way of remembering who the handler is. It's the guy who has the iterator, right? It's the guy who keeps that list. That's the way I was trying to the guy who has the iterator. It's the guy who keeps that list. That's the way I was trying to think of it, yes. Okay, it's the class that keeps that list. Okay, I like that.
Starting point is 00:27:51 So let's get into events. Yeah. Those are parties or meetups. Right, there we go. Oh, sorry. Placing some parties. Wrong kind of event? Maybe.
Starting point is 00:28:04 Land parties. sorry parties wrong kind of wrong kind of event yeah maybe land parties something that our listeners could probably uh associate with better uh yeah so uh so i guess the first part is we're going to talk about multi-casting which we've already somewhat stepped on a little while ago yeah but while we're here whenever i think about events i always end up thinking about the stupid null checking. And what that means is when you've got an event, like I talked a little bit about the game I was working on, I have an event for on-player death,
Starting point is 00:28:33 and I attach stuff like play a sound, play an animation, write some text to screen, throw up the start over dialogue, that sort of stuff. And those are all things that are attached to this event. But if none of those events are attached, if we imagine those not being there, and you try to say, you know, call this on player death, then you get a null exception
Starting point is 00:28:53 because that list doesn't exist without any items in it. That's where you could use maybe of T. Maybe of T, that's right. I was actually thinking of like AOP. Yeah. What ends up happening here is because they don't use this null object pattern um that which we've talked about in other episodes is uh every time you see something like on before render or you know some sort of on event like on load there is always a stupid little like if on load is not equal to null then call on load with arguments and so it just ends up being those extra couple lines there.
Starting point is 00:29:27 Yeah. I guess that's how you know if you're dealing with a callback version as an event. Because in practice, it seems like it's always, if it's an event, you're always saying, like, if on button click is not null, then on button click. Right. You know, parentheses, parentheses parentheses semicolon right would you ever really want a callback that was nullable though well i'm not saying that you i'm not saying that you would i'm not saying that you wouldn't also do it but but i guess what i'm saying is like in practice though because you expect that that callback is is being uh provided
Starting point is 00:30:01 uh maybe not i was thinking like you know because you expect it's there then it's it's not it's it ah forget it yeah basically what what we're getting at here is even though you see an event handler defined it doesn't mean you can just call it you've you've got to check to see if there's anything in it and unfortunately the way you do that is you say hey is it null which doesn't make a lot of sense but you you pass in null as a parameter, though? You probably could. Yeah, yeah, you could. But you wouldn't typically make a practice of that.
Starting point is 00:30:32 Don't do that. You shouldn't. But most classes are nullable by default. So, yeah, you could. Right. And it's one of those things, like, a lot of times you hear it's good practice to initialize your lists in classes. And that's so people don't have to check if something's null before they wear it
Starting point is 00:30:46 or do some sort of other event on it. It's just really annoying to have those null checks everywhere, although I suppose it's safer and it shows that you're thinking defensively or some crap. You care. All right. So the observer pattern. Yeah, we mentioned that these have a role with observers, and so this kind
Starting point is 00:31:06 of ties into the multicasting as well but you can actually attach and detach these um event handlers to the events that you're calling so like on that player death you know i've got the sound system um listening for that event i have the uh the uh the text writing class class listening to that system. I've got other stuff listening to that event. And so I can attach and detach those. And when that event happens, then they can all kind of take the appropriate action based on that. And that's basically the definition of the observer pattern, which we've talked about before. Yeah, and the beauty behind that is you're not tightly coupling all those classes by doing that. You have something that raises these events,
Starting point is 00:31:46 and the only thing that these objects have to be aware of is whatever is raising that event. Yep, and so if I want to take this game into Unity and do some crazy 3D type stuff, I can do that. If I want to have it be a console game, I can do that too, and there's no sound playing or animations playing there. So it's just a good way of keeping the class that's doing doing this stuff and you know handling or not gotta watch those words that's actually throwing the on player death um event it doesn't have to know anything about what's using that right
Starting point is 00:32:15 there's a nice separation there and that's kind of your open close principle that we just described again yep um and um yeah so there's some really gross stuff there too with um event handlers when i say event handler in this case i literally mean there's a class called event handler that um that you can kind of pass these delegates into and this is very like c-sharp kind of 1.0 type stuff and it also ties into those um i'm sure you've seen those if you're doing like on button clicks where it's like uh it takes the arguments are an object and event args and you always cast the object to something and you cast the event args and you try to do something with it and for a long time that was kind of like the standard and it's all the all of those things all derived from this event handler
Starting point is 00:32:59 class and uh it's definitely an old school way of doing things and it's just gross to be doing this sort of casting and stuff. You're losing the type of safety that you get from using delegates. That's one of the strong points about it. So I'm not a big fan of this pattern, and it's definitely kind of been phased out. I don't think so. A couple things with that. I don't think we have anywhere in our notes where we talk about event handlers, do we?
Starting point is 00:33:24 Not further down, i don't think we have anywhere in our notes where we talk about event handlers do we not further down i don't think um so a couple of things that are kind of interested in the old like you mentioned in the 1.0 days you would have to define your delegate then you'd have to define your event handler and then you could you know start adding these things to them in the i don't know what version they changed this in but you can actually just define the event handler without actually defining the delegate, which is kind of interesting. So they kind of allowed you to skip a step because they're like, if you're using a handler,
Starting point is 00:33:51 you have to have a delegate out there. Well, I guess it's important to say, too, if you expect this to be multicast, then you should be doing plus equal. Yes. Don't do equal. Whatever variable is going to represent the handler, you should be plus equaling when you add additional methods into it.
Starting point is 00:34:10 Yeah, so to further that and explain why. So let's say that you have this, I don't want to call it a global thing, but let's say you have this parent event bus type thing that you've got that is raising these events and all that, right? If you have multiple classes out there that are responding to these events, if you say that, you know, this event handler equals, and then you give yours, you just blew away all the other event listeners out there, all the handlers out there. Interestingly enough, though, you can also do a minus equals. So if you have something to where like maybe you want to listen for an event until some state is reached right like in your case you're talking about your video game right like once once once your player dies there's no reason for it to be listening for
Starting point is 00:34:56 these various other events right or hey while you're on level one yeah that's a perfect example you're on level one if some something happens, then this event gets raised, you're going to respond to it with one of your handlers. If you progress to level two now, you might minus equal your level one handler. So you can minus equals, you can plus equals. You can also do an equals, but you'll blow away everything else that was set up before. So when you're doing event handlers, if you're not seeing plus equals or minus equals it's probably not right and you're probably going to see some bugs yeah but it's nice too i use it
Starting point is 00:35:30 for sound so i can turn off sound and then i just don't you know that sound system is not listening for events and that keeps you from having to say if sounds on play sound all over the place oh yeah because you just raise an event when something happens and then the sound of play if it's on yep yeah it's beautiful yep so um just to kind of recap on those event handlers it's basically just the kind of parent class for all those um anytime you see that object and event args getting passed around and that that's important later we're going to end up coming back to this a little bit all right so we gave some examples from the.NET framework um I want to talk a little bit about All right. So we gave some examples from the.NET framework. I want to talk a little bit about delegates and other languages. Yeah. So because I like JavaScript, we can talk about it
Starting point is 00:36:11 there. It's weird to actually have this discussion in C Sharp when I've been doing JavaScript so long that JavaScript just treats everything the same. It doesn't matter whether it's a string, a number, a method. It doesn't care. So delegates in JavaScript are super easy. You just pass a function in as a parameter. Or you can pass it in as a variable on an object. It doesn't matter. You can create your own object, you know, open up a new object thing, do A colon function, B colon function, a colon function b colon function c colon function and then you know whatever's
Starting point is 00:36:46 getting that can just call you know object dot c open close paren and you basically have a delegate or actually it's not even really a delegate it's just an anonymous function has no name you can't you can't call it any other way um so in that regard it's not but the fact that you could pass it you can pass the fact that you could do like whatever your variable was dot c, it's not... But the fact that you could pass it. You could pass it. The fact that you could do whatever your variable was, dot C. But it's not a... I guess it is kind of a pointer because it's pointed by reference. But yeah, I mean, it's just such a part of the language that it's...
Starting point is 00:37:17 You don't even really think about it. You take it for granted. Yeah, I mean, all the code that you do in JavaScript, you're probably doing some version of this. That's why I was kind of laughing when you were talking about one of your declarations, how to set up the delegate. And I'm like, no, you just have
Starting point is 00:37:31 whatever your variable is, colon, function, space, parentheses, parentheses. And that's because we are JavaScript monkeys now. Curly brace. Actually, speaking of JavaScriptavascript i think that basically anonymous functions are a huge part of the whole like jquery revolution this is a lot of
Starting point is 00:37:51 a lot of the first times that people really started using um you know these kind of higher order functions and um well when they started uh when jquery got really popular because you would basically do like dot selelector,.each, and then you would do something in there, and you would basically just write an anonymous function, and it would get called inside of that iterator. So it became really big, and people just take it for granted now in JavaScript.
Starting point is 00:38:15 It just kind of comes naturally. It's shocking to me that Java has not brought this in, considering how pervasive. Well, before we get into Java, I almost think that... Well, totally tangent, but I almost think the anonymous functions are a little overused in JavaScript.
Starting point is 00:38:31 Oh, totally. Totally, 100%. No question. Callback hell, quote-unquote. Yeah, it's... Way overused. You know, it's really interesting. I mean, having coded in it for so long,
Starting point is 00:38:43 you definitely just find yourself doing that all the time. I'm sure someone a lot smarter than me, though, can argue that, no, it's done exactly the amount of times needed. Yeah. And JQuery, yeah, it absolutely brought closures to the forefront. I remember when JQuery first started getting popular and, like, every single blog article that you would see in your Google Reader was about closures. Yeah. And wrapping your mind around that the first time is definitely painful yeah um now i do want to talk real quick though seeing as how we brought up other languages
Starting point is 00:39:10 with javascript like events this is where using a library really becomes important because when you start looking at how it's done uh depending on your browser you'll either be calling fire event or dispatch event like there's still we still have that separation of browsers where they all do things slightly differently so if you're not using something like jquery or you know god knows one of the other umpteen thousand like i've done dojo ext js they all have their own custom event system, but it's handled very much like what we're talking about in C sharp to where you define this event and then you can raise that event and other items or objects or components or whatever can listen on those events. And then they can respond to them with their own handlers, whether it be an anonymous function or whether it's some name function out there that's being passed around. So, I mean, all that, it's, I find that JavaScript is closer to C Sharp in that regard than what Java is, which, I mean, we started looking before the show trying to find, you know, how do they handle this? And there were some pretty long articles on how they tried to accomplish it,
Starting point is 00:40:21 but they don't actually have anything built in for it. So, and I mean, we may get blasted on this, like, you're wrong. on how they try to accomplish it, but they don't actually have anything built in for it. And, I mean, we may get blasted on this. Like, you're wrong! In Java 8.234, you know, I don't know. I used the Ask Toolbar that came with Java, and it said... Oh, God, don't get me started on that. Ask Toolbar. You know, I just got to be thinking,
Starting point is 00:40:44 what kind of the most popular first-class function or delegate or function pointer, why be in a document.onload in JavaScript? That's a great example of calling basically a variable or a method as a variable. Yep. And Java is weird on this uh on this situation so they've got this um in in the eight they've got this weird kind of single method interface implementation
Starting point is 00:41:12 that allows them to get around not having true delegates and they've got this thing called a method reference too which is just kind of weird but um you know when we were kind of like looking at this um we talked about before the show like what show, what would we do if we didn't have delegates in C Sharp? Then we Googled, what does Java have instead of delegates? It was basically the scenarios that we'd come up with to solve not having generics. It was a pitiful, sad world. Not having generics or not having delegates? Sorry, delegates.
Starting point is 00:41:42 Delegates, yeah. If C Sharp did not have them, I would just code Node.js. There's some callbacks for you. That's what I would do. So just real quick, wanted to mention that this is kind of the first part of the show. So we talked a little bit about delegates, events, and their role in C Sharp. And also we gave some examples in other languages. All right.
Starting point is 00:42:11 So with that, let's take a little breather for a minute because I think it's time that we say to everyone that has taken the time to give us a review and go out and give us a rating, how much we greatly appreciate that. And if you haven't already, we would love for you to do so so uh alan it was a codingbox.net slash uh review yeah or reviews uh okay fine you can do either check no you really you did both i did look at that yeah man i know how to set up some redirects yeah uh oh yeah and i totally on this on this slash review page i totally put some experimental stuff on there that i've never messed with before like there's click buttons to follow us on twitter and facebook and share
Starting point is 00:42:59 on linkedin man i've never coded this stuff so i was out all over the internet grabbing this it's like it might work yeah i mean we're talking about technology that's five or six years old but much like yourself i'm not a socialite how old is facebook now i don't like facebook but i've done a facebook button well you know you're. I should have made you do this. Apparently. So at any rate, yeah, there's all that kind of stuff on there. So if you would, seriously, like we love the reviews. Like, I mean, we all are IMing each other.
Starting point is 00:43:37 Dude, did you see the latest on Stitcher? So it's awesome. It gets us excited and it helps other people find it so that you are basically making the world a better programming place for you. And look at it this way. If you share the show with your friends, then it gives you something to talk about during lunch or whenever
Starting point is 00:43:54 that you can talk about how much more right you are than we were. Yeah. How wrong was Michael when he was talking about delegates? And as a measure of that appreciation, reminding you again about the giveaway. So leave a comment on episode
Starting point is 00:44:09 24 and we will send you a book. Yep. It's a first edition. So only edition. Way to belittle it. We should have mentioned before we spend some time asking reviews that the episode is not actually over yet. So this is not the end of the episode. We still have some stuff we spent some time asking reviews that the episode is not actually over yet.
Starting point is 00:44:26 So this is not the end of the episode. We still have some stuff we wanted to share. Keep going. Don't hang up yet. Hopefully you looked down and you saw that there was still half a bar left, right? They were like, oh, they're begging again. Click. All right.
Starting point is 00:44:44 Listen to how you really feel. All right, so now we want to talk about a delegate deep dive. Basically, we want to talk about how this works under the covers. So who wants to dive into that? Get it rolling, Jay-Z. I vote you, man. All right, so Michael mentioned this earlier, but basically at compile time, the C Sharp compiler goes
Starting point is 00:45:04 and it creates a subclass of this multicast delegate object that we talked about. And the multicast delegate object is kind of interesting. It's a class that, you know, we mentioned that delegates are basically function pointers with an iterator. And that iterator is what the multicast kind of refers to. That's what the multicast delegate adds over just the normal delegate class. And the delegate actually is one of the few objects that derives directly from objects. So it's not a value type.
Starting point is 00:45:33 It's not a reference type. It's a type of delegate. So it's really a core feature of the.NET framework. And these delegates have kind of four methods that we wanted to mention they only have four one is the constructor wait wait before you go there though i think it's important to note though that there's no intelligence behind this multicast iteration okay that too but the iteration it's literally um first in life i don't remember if it's LIFO or whatever, but it's sequential. It would be FIFO.
Starting point is 00:46:05 Is it FIFO? First in, first out. I think it is first in, first out, yes. So, I mean, it's literally just, hey, if you added 10, whatever order those 10 were added in is the 10 that is going to get executed in that same exact order. All right, back to four methods constructor. I was going to also add to the multicast definition, though,
Starting point is 00:46:24 that it's important to note that it's a delegate that can have more than, according to Microsoft, a delegate that can have more than one element in its invocation list. Right. And that's where the multicast kind of separates from just the delegate. So pretty much anything you're going to do is going to end up extending this multicast delegate, but there's still that kind of weird separation. So it's kind of interesting. I don't know if they've got future plans for that, or they thought maybe they would do something else and it just didn't happen.
Starting point is 00:46:57 But either way, you're going to end up extending multicast. It was the latter there, right? They originally had planned on it going one way, and then it just only ever became that one. Because it's been like that since the early days. A long time ago yeah so either which way you're doing multicast delegate whether you know it or not or like it or not yeah and so what that means is uh no no what that means is that when you write delegate um you don't even have a choice you know there's no way to specify one or the other you um you write a delegate or anonymous method and in the background the compiler will go and it will create an instance of this multicast delegate object and it's got four methods uh one is a
Starting point is 00:47:32 constructor so that kind of doesn't really count but it's got an invoke which just executes the method and it's also got a begin invoke and an end invoke which is useful in like async operations where you want to kind of kick it off and then you know call some sort of callback when it's done and so um and that wanted to call this out specifically because we're talking about like um what java guys end up having to do was basically like if you didn't have delegates how you would handle a situation where you want to take a different algorithm or a different method in this variable is you would create some sort of interface that has a method like execute. And then you would create classes called like add executor or multiply executor. And these would do your addition or subtraction going back to that example that alan gave and then you would have a method that takes in one of these classes with that uh that interface and then you would just call that very explicitly so what that ends up meaning is you
Starting point is 00:48:35 create a class for every different operation that you want to do which is a lot of typing and um that's really what's happening in the background so really this is just kind of a sugary type thing the compiler just does that you know that typing for you yeah i mean it's kind of cool it literally creates new classes for every one of them all these these targets and everything else like you never see it it's just real easy for you to do but the java people have to type it out like you know everything that the compiler is doing for you here, they literally have to write that code to make the same thing happen. Yep.
Starting point is 00:49:10 And I want to mention that there were four methods and there were three private fields. And kind of the point I'm getting there is that it's really simple. There's not a whole lot going on here. So when you think about it from this direction, for me at least, it kind of makes things make a lot more sense and this fields uh where the target which is basically the thing that this method is being called on or if it's static it'll be null there's the method pointer which is actually like the address of the function that's going to get called so this is like
Starting point is 00:49:39 the the real deal this is like the you know that method variable that we're talking about and then there's the invocation list which is like you, you know, that method variable that we're talking about. And then there's the invocation list, which is like, you know, what we're talking about too with the multicast delegates, the list of things that this is going to happen on. I did want to say though, like,
Starting point is 00:49:55 I guess you said something about the way Java handled it a minute ago. That kind of struck me as odd. And I guess the only thing I wanted to say to that though, is that Java, because they don't have delegates specifically or something like this, they get around it through, let's just say, creative uses of interfaces. Right.
Starting point is 00:50:15 Yeah, they've got this weird interface that can have a single method implementation, which is how they kind of get their landos in Java 8. But I'm definitely not an expert there. But even before that, even before Java 8, though, right? I mean, they still handled it as interfaces, though. Yeah, and that's the way I would do it, too. So, like, in kind of the chess example,
Starting point is 00:50:37 I would have a class called the, or I would have an interface called iChessStrategy, and then I would have a... Not if you're in Java, you wouldn't. Oh, yeah, you're right. You'd be ChessStrategy. It'd beChessStrategy. Not if you're in Java, you wouldn't. Yeah, you're right. It'd be ChessStrategyImpl. No, that would be the implementation. That would be the implementation, right.
Starting point is 00:50:51 So I would have an interface called ChessStrategy, and then I would have a class called BobbyFisherStrategy, and it would behave in some ways. It would basically implement the method we'll call execute that's defined in that interface that takes in the game board and returns some sort of move to make so i guess i guess a way to sum up that difference though would be that in okay if we if we're talking specifically c-sharp to to java right c-sharp tries to give special meanings to these, but really under the covers, they're just normal types. Whereas in Java, the developer is more exposed to the fact that,
Starting point is 00:51:32 hey, this is just a type. Yeah, they have to type it all out. It's very explicit. I didn't mean typing, but I meant they're more aware of the fact that it's an interface, the fact that it's a concrete type behind there. Whereas in C Sharp, for example, there's this abstraction that's taken away from the developer, him or herself, by use of this keyword,
Starting point is 00:51:58 and then the compiler does some magic to create this type that inherits from multicast delicate and does some magic for you. It's totally a nicety. Oh yeah. And imagine if, you know, thinking about link, like every time you did a for each or a where or a first or default, you had to define a class with the method that took in the appropriate argument and returned the appropriate, you know, return value. It's almost like having Dto's for all the internal stuff you're doing right like you create dto's for for the way that you want to transform data coming back from a call or something now you got to do that for every single you know delegate
Starting point is 00:52:34 like thing that you want to do i mean it's just a lot more verbose yeah which i say i i just didn't want it to sound like we were bashing on it no because it's just they don't have that that syntactic sugar right like they don't but my point is that like you can get a you can do it way without it you can yes you totally can it is completely possible to do away without it because there's nothing you know it's sugary going on yeah but it's that sugar that buys you link yes so the there wouldn't be link without this like you can have land was in java but they're still pretty nasty and it's basically doing that whole interface trick uh which i'm i don't know a whole lot about but it smells kind of fishy to me sorry for that derailment i I just wanted to comment on that.
Starting point is 00:53:25 Oh, yeah. Also, I wanted to tie back to earlier. Michael mentioned when you can kind of call this delegate by just adding a parentheses and the arguments afterwards. When you do that, the compiler actually sees it and it swaps that class that it created the background, and basically does a generated class dot invoke and then passes your method, which is what you do with, I think it's called method info or method information class in C Sharp where you can kind of dynamically specify and then dot invoke a method. It's basically just metadata about the method. So that's the last part of the sugar there.
Starting point is 00:54:04 And the last part of the sugar there. And the last part. No, go ahead. I wanted to mention we kind of tied. This might be the only episode where we said we would get to something and we actually kind of got to it. So pat on the back, guys. All right. And with that, we'll be wrapping up.
Starting point is 00:54:38 Well, we mentioned event handlers and how I disliked them. And what I wanted to kind of tie back there was the event handler is basically a class that returns void and or it specifies a method that returns void and takes in an object for sender and event args e. And so a lot of the kind of legacy.net stuff you'll see, it's got these events like on button click or on whatever and you don't see the word delegate anywhere and it's because these are all deriving from this event handler situation and what happened is around.net 3.5 when they added anonymous methods and generics they created these two classes called funk and action and these are amazing and um well i know we're going to end up talking about these again in the future but basically the difference about to get funky about to get funky these both are heavily genericized methods in fact there's not any classes there's not a whole lot to them other than their generics in fact and so what i mean by that is that funk takes in as simplest case uh you know a type and a result right so you that'll be specified input type and a return
Starting point is 00:55:36 there you go thank you right yeah at its simplest right and so what that means is i can say that my class is a funk and um the the input type is a string and the output is integer and i can have a method that you know converts between them well let's not say cloud let's say let's just say like you were talking within a method and you had some variable and that variable was a funk of right and so like the where example and link that takes in a funk so you you know you do your little x arrow, and what's happening in the background is this is getting cast to this func T result. And the T in this example is going to be whatever the type of that collection is. And the result in the where example is always going to be a Boolean.
Starting point is 00:56:21 So in order to fulfill that promise in that signature, you say, I'm taking in some sort of item in this list, and I'm returning true or false, which basically meets that kind of where criteria. Okay, so let me maybe be too verbose. So going back to our calculator example that we did from earlier when we were talking specifically about the delegates, if we were to imagine this, if we were to reimagine this as just some variable inside of
Starting point is 00:56:49 your method, right? Then let's say that you had your add variable, okay? And the type of it is func and then in your alligators, int comma int int comma, int. All right. So the first two ints are inputs and the last int you're saying is the return type. Okay. So, so funk, int, int, int, and then my variable name add, right. And then, and then I'm going to say equals. And then in parentheses, I'll say X comma Y, because I'm going to pass those in too. And then my – Equals then, greater than. Yeah, my goes to.
Starting point is 00:57:31 And then in there I could have curly braces to say return x plus y. Yep. Right? And that's a simple example of using func of t in line as a variable, right? And now that I have this add method, or let me re-say that, now that I have this add variable and I've declared it as a func of T,
Starting point is 00:57:55 I could then later say something like a console.writeline add and then in parentheses 3, 5, and it would return, I would see it right out the number eight yep yep totally and so going to back to what he said though in the where clause like in the link example dot where if you ever mouse over that in visual studio and you're not aware of what funk of t is it's confusing yeah it looks terrible yeah you'll have no idea what you're looking at but the important part is whatever's on the left side of your of your lambda so like he said x and then
Starting point is 00:58:33 you have your equal and then greater than x is your input right so basically your funk of t is now you know open bracket or uh open alligator uh let's say five. And then, uh, let's do a comma too. So you're going to get the same type thing that you're talking about. And, and now essentially whatever's on the far right side of that parameter list inside your, your, uh, alligators, that's always your return type. So if you look at it, all the inputs are on the left of that equals and greater than, and whatever's on the right hand side is what gets returned out and it's it and it only makes sense if you actually understand what funk of t is which you know you guys just explained really well so the next time you look in there and you see this big nasty long thing on your
Starting point is 00:59:21 intellisense and it's like this is it you now know oh you're intelli nonsense yeah i can't i can't help but think like anytime we talk about funk of tea though i can't help but think of george clinton and the parliament funkadelic oh very nice so so did we mention though that like what if so so in the funk of tea you were passing in um you're saying here's the two inputs and an output but if you didn't need an output then that's where action of t would come in and i don't know that we really gave action of t as much uh conversation as funk of t right well we haven't got there yet okay well i'm sorry but i'm gonna skip ahead but it's basically like the same similar concept, except without the results. So, you know,
Starting point is 01:00:05 in your, you know, that ad example that I gave, if you weren't expecting back a result, uh, maybe you wanted to say like print ad as the, as the variable, right?
Starting point is 01:00:17 And so you'd have action of, uh, action and the alligators, you know, it comma int, and then the variable name print add, which is a horrible name, and then equals,
Starting point is 01:00:30 and then in the curly braces, or in the parentheses again, x comma y, and then the goes to, and then the curly braces, then it would actually do your console.writeline x plus y in there. Yeah, and so the only difference between func and action
Starting point is 01:00:47 is that func returns something. And then the specific reason we wanted to call this out in reference to delegates, and aside from its interaction with Link, is how this is so much better than the old school event handlers. So in.NET 1.0, there was event handler, right? And it took in an object, it took in event args, and it returned void. Well, along came generics in 3.5, and suddenly someone had the right idea,
Starting point is 01:01:16 like, oh, why are we kind of tying ourselves to this object casting event args garbage? Why don't we just create this funkin action or reuse this funkin action and go ahead and create different versions of funkin action that take up to a very large number of arguments, up to 18 T's, generic types, and just use those instead. And what this bought us was completely strongly typed delegates no more casting no more event args no more event handler and and for anyone that wants to not think so highly that any time you do strongly typed then it's much better to fail at compile time than it is to fail at runtime absolutely so if you hear me complain about JavaScript.
Starting point is 01:02:06 So with that. Yeah. So the interesting thing of what they both just said is, so first the up to 18, what he means is when you open up that alligator thing after the action or the funk, that means you can do up to 18 inputs or, or 17 inputs with one return, right? Right. And what that means is that any function that you've got,
Starting point is 01:02:29 just like any regular method, anything has up to 18 arguments. That is now a representative of this funk class, right? And any action that has up to 18. So, so any method that you have that returns void and takes up to 18 arguments is now an action type you know i've never tried this but i wonder like if you're going back to
Starting point is 01:02:53 like a link type scenario if you could ever get into a scenario where you would have like say 19 or 20 do you get a compiler what does it do does it imagine it have to fail well you could still do but you can't use it as a delegate so what happened is like if you tried to do something where you pass it in like uh you know a four each or something like that um or you know some sort of generic expression you had 18 or more arguments and it just wouldn't work because it doesn't represent a delegate at that point it's just its own class well i was thinking like where like i would think it would fail yeah compile time yeah so like if you think about that for each it takes in now i want to do some experimenting right yeah you could yeah you could definitely
Starting point is 01:03:34 see it um i think someone did online there's a blog post we could probably link to but uh what this means is uh in practical when i say that you know any method you have uh that's under 18 arguments uh can be treated as a delegate so that say that any method you have that's under 18 arguments can be treated as a delegate. So that means that any of these link expressions, as long as you match the right number of arguments, or right type of generic, I guess you call them arguments, then all of a sudden you have embodied a delegate. And you don't have to use this delegate keyword anywhere. You don't have to set up any sort of handlers. You got it for free. You're already an instance of funk or action as long as you stay under 18 arguments. Well, hold on. You still have handlers, but you
Starting point is 01:04:17 don't have to assign any delegate things to them. You can just say handler plus equal and then you're, you're a funk of T or whatever it is, right? You still need the handler. Well, like in the link expression, you don't specify a handler, right? You just kind of pop your method in there. And if you've ever seen like, you know, you can pass a method group in there. So you can actually pass a method name. And the reason that works is because whatever method you specified,
Starting point is 01:04:39 as long as it's under 18 arguments, can act as a delegate without having to be explicitly called that or typed that. So you're talking about more lines with the link, not necessarily event handlers. Right, yeah. Events are kind of separate. Okay, okay. I'm with you now. So what I was saying is if you are using event handlers in your code, you can actually do a plus equals and then just give it that lambda. Right. Which is the func of T or whatever.
Starting point is 01:05:09 So that's what I was saying. What you were talking about is if you're using it elsewhere, like in a for each or whatever. Right. Then, okay. Yeah. So imagine a case where you've got like a list of state names, right? And you say states dot select and you do X arrow x dot lowercase right so what you're doing is you're getting a lowercase list of states back well that lowercase method is defined in the c sharp framework and it takes in a string and it returns a string and because of that it's acting as a
Starting point is 01:05:41 delegate for func t t result where t is a string and the result is also a string yep so these funk and actions really like open things up and uh pretty much killed event handlers yeah they they well no not event handlers sorry the event handler class so that's the one with the object in the event args okay okay i guess like even just you know as we're talking here just doing some quick uh googling to see like uh you know if there are other problems there's definitely some you know issues around like link to sequel but it's actually kind of interesting because i'm not finding much for like if i tried to do something with link that had they would try to take in too many and now i want to like i want to try to do but let's be clear if you're
Starting point is 01:06:25 doing more than 20 arguments yeah or 18 they used to they actually upped the number i think when they originally came out it was like seven or something and then uh a later version came out and went up to 18 people i guess what i was thinking of is like is there some magic that happens behind the scenes to like break that up for you well he was saying there were hard to find classes yeah yeah i know that i know that there's the hard to find classes but what i'm saying is like let's i guess i don't even know like how i could write this example because i was trying to think of something like where maybe it was happening a little bit more dynamically that um yeah where where where all those values might get passed in but then at at runtime, would it like break that up?
Starting point is 01:07:05 I don't know. I'm thinking out loud. And that's what, if I was writing the compiler in theory, though, because of the compiler is smart enough to do this in tactic sugar. Why wouldn't you just say, Hey,
Starting point is 01:07:15 what had the longest argument list, you know, and then I'll just create a class that has that, right? Like, I don't know. Yeah. That kind of makes sense.
Starting point is 01:07:24 I don't know. Hmm. of makes sense i don't know hmm you know i was thinking the only kind of dynamic argument example i can think of is params but really that just comes in as an array yeah it's an array whatever the last yes that wouldn't work here but but i mean you see where i was going with that though right yep but i don't know i'll have to think about that because i can't even i'm trying to think about like how i could even write an example to see like what because i'm guessing that there has to be some kind of error, but I've just never ran into it because like you said, if you're trying to pass in that many, then you have a problem. Right. Because you're never going to maintain it anyways.
Starting point is 01:07:57 That's never going to make it through code review. Sounds like you need a builder pattern at that point. So before we get into the next section um i thought about these while uh while we were talking about all this stuff so when would you suggest using things like event handlers so here's a perfect example of what i'm getting at you can go crazy with this stuff just like in the design patterns and i think joe jokingly said this in one of our design patterns uh podcast was you know um you know when somebody picked up the design patterns but because all of a sudden you just start seeing all these patterns show up everywhere in code right factory factories
Starting point is 01:08:36 yeah yeah so so here's the thing with events which so i i heard an example somebody said something like let's say that you had an order system, right? And then somebody placed an order. Okay, there's certain things that have to happen after an order is placed. Like you're going to allocate some inventory. You're going to send an email out to the customer. You're going to, I don't know what else, right? But would you go crazy with events knowing that the whole reason they are so important is because it allows you to decouple your code? Really, that's the most important part of event handling is you can respond to something that is – if somebody shouts out there, fire.
Starting point is 01:09:21 Okay, somebody's going to go put out that fire. That's basically what happens in your code. When event is raised something responds to it so would you do this in something like an order system you brought up your video game earlier when the player dies you respond to that event that seems like that's a perfect example of when you would use it you know i actually um i've kind of got away from events after my experiences with video games. And the kind of funny thing about it is that although the player is very much decoupled from the sound system, there's still somebody that knows a whole lot about players and sound systems and graphics and control systems. And what I found is that these kind of event touch points just ended up being the heart of my spaghetti code. So although these things were, very separate, I'm also tying them together.
Starting point is 01:10:12 So these things that have no knowledge of each other suddenly are all combined. And so my problem there is that I started feeling like I was abusing these events to reach all over my code base rather than going through a nice, clean hierarchy. That's kind of interesting because, okay, let's take an example. And I think I brought this up earlier. Let's say that you had a UI that had, I don't know, 10 components that showed various different pieces of information about something. Let's say it's a person, right? Something on that person changed, like the first name.
Starting point is 01:10:47 A very elegant way of handling this is whatever the parent component is, right? The thing that has all these other components out there, these nine or ten components on the page. It is what can raise events and, you know, it's basically your event bus for the whole thing. Or maybe it has some sort of implementation of an event bus, which you might do through a singleton or something else. But it raises an event. Those nine or ten different UI components can now say, oh, wait, the first name change, I need to change my stuff, right?
Starting point is 01:11:22 That seems a lot more elegant than saying, okay, this thing knows about that object it's going to go over here and change that data then it's going to go change this and it's going to change this it seems like that's a lot more elegant than than what then the alternative you know what i'm saying so i mean i can't think of a clean way to decouple that if if you have like and let's say that you don't even know what those components are going to be maybe it's pluggable stuff right like how else would you do it yeah that's a good point i just i know that for me like when i started kind of doing the events i kept finding myself doing more and more and more
Starting point is 01:11:59 of them until i realized that i was basically just using them as glorified go-tos but i do think you're right that i was keeping things separated, but it was allowing me to kind of jump across the object graph in kind of a strange way. So it just kind of started smelling to me. But maybe that was just me kind of doing bad things. Interesting. What are your thoughts?
Starting point is 01:12:21 So we've all worked in e-commerce software. Is this something that you think you would want to do on an order system? I mean, would you want, okay, order was placed. Raise that event. Order placed. All right, now it needs to go do something with inventory. Now it needs to go send an email. Now it needs to do X, Y, and Z.
Starting point is 01:12:39 Would you do it there? Because typically the way you see it is order placed. All right, now it's going to just go to the next step and say all right deallocate some inventory now it's going to go to the next step and it's going to say all right um send out an email now it's going to go do x y z right like it's usually a sequential you know thing that you see in code whereas if you did the event thing you decouple that and then if you need to reuse that because we've all run into this before like something gets jacked up with an order somewhere and you need to send that email it's all tightly coupled to something else right so you can't go send that email now um without like writing code
Starting point is 01:13:16 to somewhat hack into it whereas if you just had something that responded to an event like hey this order was placed hey send out an email so i'm just wondering like would you ever take it to that step i've never taken events i have on ui but i've never done it so much server side type stuff yeah i could definitely see like using kind of different event queues there and kind of saying like okay order place now put it in the email queue in the inventory queue in the uh you know flash a red light queue, whatever. So, yeah, that's definitely an interesting use case there, and it kind of separates all those systems.
Starting point is 01:13:51 And so what it means is, you know, if the email system's down, then, you know, everything else kind of still keeps going until we get that back up. And by having the queue there, it kind of prevents that action from not happening, or it saves that action. You can fill it back up, right? Like, it would be fairly trivial
Starting point is 01:14:04 to do something like that at that point yeah it definitely comes in and help a lot of times with uis you know button click type stuff that's kind of like the prime examples of it but yeah e-commerce i think that works really well too i mean i think it's one of those things it's hard to think about like from from an abstract like that though because i'm thinking like as you're tired and i'm like well i mean like i i see where i see where your intent is going but then i'm like well then you have some kind of like event orchestrator you know that's managing all those events and it's like well you know then it gets like then we go into this whole other tangent of conversation
Starting point is 01:14:40 because then it's like well are you really like solving the problem that you were talking about them because then you still have like it's all, well, are you really like solving the problem that you were talking about them? Cause then you still have like, it's all tied together in that, you know, whatever that doing that orchestration versus what have you just made those each as like separate components, you know, they just ran on their own kind of schedules or, you know, whatever. I don't know. It seems like that we're getting into like a really deep kind of
Starting point is 01:15:00 conversation. Maybe, maybe not. But so, I mean, just, but I think it's helpful, right? Just because only, only from the perspective like this, kind of conversation maybe maybe not but so i mean just but i think it's helpful right just because only only from the perspective like this like you can't just schedule something because unless you do that and every part of the schedule starts setting up different states for these things i guess you could do that right but then you still have an orchestrator but what i'm saying is no i mean i was thinking like like you – the email coupling, the emailing you mentioned as an example of – like that might be one of the events. But you could totally decouple that completely away and like that could be its own little job that runs on its own.
Starting point is 01:15:35 Maybe it runs in batch and it just looks for orders in a particular state and then does it. But you're still taking it to that step of of abstracting so basically what i'm saying is typically when you look at software it's usually it does a b c d e f g right like in that order that's what we've mostly seen as programmers right and that's because that's how people think about the process when they're divining when they're designing the software hey when you do this then this needs to happen. The next step is this. And that's usually the way you see it. It's just very sequential down the code. If you break it out into an event type thing to where you have, you know, before order place,
Starting point is 01:16:16 order placed, order inventory allocated, email sent, whatever. So what I'm saying is what you're describing is the same thing as an event bus except now it's except now you're separating it out to where you have batch jobs that are going to key off some piece of data right like you're going to say okay has the order been deallocated say this is why we're getting too specific into like one kind of example though because like the thing that i don't like about what you were suggesting with putting this into, uh, wasn't suggesting, I was asking.
Starting point is 01:16:47 Okay. Well, in your example, in that example, then you still have the order of those, those event calls in the example that you gave is still within some other piece of code. Whereas what I was suggesting is,
Starting point is 01:17:03 well, what if you broke those out and they were intelligent enough on their own to say these are the things these are the orders that are in a state that i should send out this particular kind of email about and that's what i'm saying like i think like this is getting way deep into a very specific kind of use case it is it is it's very deep if you were to actually go down it, but I was just kind of curious about like... Yeah, I think you've got a valid point there with thinking about
Starting point is 01:17:29 events and kind of event queuing. You're talking about a system that basically deals with events and you're thinking of it from an architectural rather than kind of a programmatic view. Yeah, I think that's a very interesting thought. Alright. Alright. Alright. so we kind of talked about um the encapsulation uh aspect i also want to mention um uh this is kind of a it almost
Starting point is 01:17:54 seems a little bit silly but um our event calls asynchronous no yeah i'm going with no yeah it's kind of a weird thing because your call, if you think about that method being defined in the class somewhere, it kind of gets called in some different context, right? So you don't really know where that's going to happen. But yeah, the call absolutely does, unless you specifically say. Well, here's a specific example that I was thinking of. Well, not a specific example.
Starting point is 01:18:21 The specific use case that I was thinking of is that in a lot of – did you say Call of Duty? In a lot of scenarios, you can actually halt the execution of that event, right? So you can say like no need to go any further. Maybe that's on an exception as an example, right? Or whatever your use case might be. But you could spawn it off onto another thread. Yeah, same thing with kind of exceptions. You can catch it and stop the propagation.
Starting point is 01:18:49 Yeah, but the point, though, is that if you had on button click and you have five handlers, all five of those aren't happening at the same time. They're happening one after the other. And that goes back to our point about the invocation list within the multicast delegate. As Alan said, it's just going down that list in order. back to our point about the invocation list within the multicast uh delegate like you know as you as alan said it's just going down that list in order there's no special uh you know craziness happening
Starting point is 01:19:13 there's nothing magical about what it's going what it's doing it's literally walking down that list yep uh that said though um delegates do factor a lot into um likePL, the Task Parallel Library. And it's a big part of doing some of the kind of cool parallel kind of concurrency stuff that you can do in C Sharp. All right. So, wow, we talked a lot about delegates. Let's get over some resources that we liked as we got into it. Not everyone at once. You did the,
Starting point is 01:19:46 uh, CLR, uh, VSC sharp, right? Yes, absolutely. So that was a fantastic book a couple of times.
Starting point is 01:19:52 Yes. When are you giving that one away? So that one, I actually already gave away. Uh, I let someone borrow it and I forgot to get it back when I left that job. Was this at the doctors? Uh,
Starting point is 01:20:02 no, no. Apparently I'm not good with physical books, so that's why I'm giving them away. Oh, okay. But yeah, C-L-S-E-R, C-Sharp has an excellent chapter on delegates. So definitely recommend checking it out. It actually is a whole separate chapter just on methods and a separate chapter on properties and a separate chapter on fields. And it's the Bible for C-Sharp.
Starting point is 01:20:22 It is. Yeah, and we've definitely talked about this book before by it's by uh jeffrey uh richter yes i hope i pronounced that correct yep currently in its fourth edition so it is an awesome awesome book to have yeah also i wanted to mention another book c sharp in depth which did a really good job of um this is by john skee we've mentioned this one before too but it did a great job of kind of running through the history of delegates and kind of like explaining some of the ways that kind of things started
Starting point is 01:20:50 and how they ended up and that kind of helps you understand why you'll see so many different kinds of examples on the internet. One of the resources I liked whenever I was doing this, and I think Outlaw also was the Pluralsight course on C-sharp's events and delegates by Dan Wallen.
Starting point is 01:21:06 It was excellent. Waylon? Waylon Wallen. I can't remember it. He says it. Anyway, I said it both ways, so he's covered. But it was an excellent, excellent run through. He ties in some great examples.
Starting point is 01:21:19 He shows you basically the evolution of delegates within C-Sharp. So nice, nice resource. Yeah. We've also got a nice link to a MSDN, which you could find on the website. Yeah. These will all be links within the show notes. So with that,
Starting point is 01:21:34 let's wrap it up and get into the tip of the week. All right. So I had one in, and then I decided maybe I should say another one, but I'll go for the first one so i found this uh we've all used fiddles before um you know a lot of javascript fiddles that are out there but uh there's dot net fiddle dot net if that's too much dot net for you so the first the first dot net just to be clear is spelled out so d-o-t-n-e- net fiddle and then dot net as the top level domain um
Starting point is 01:22:06 great little uh site if you want to uh let's say you're on your mac and you want to write some c sharp and see it compile and run and whatever uh you can create your fiddles there uh the reason why i say i had some kind of problem earlier and i don't know if they were just doing some maintenance. I'm certainly not going to take credit for bringing them down, but I was writing, uh, a fiddle and, uh, then suddenly things stopped working. So I wasn't sure. So I had a second tip, which is really awesome, which, uh, I'll include a link to it. But to it but if you are a fan of git and if you use git and you know no matter what language you are coding in there is a github project for just for git ignore, for the one and only file,
Starting point is 01:23:06 it has suggested git ignore statements for every language, every project type that you could think of. So specific to Visual Studio, for example, there's a visualstudio.git that includes you know ignoring your debug folders your release folders your uh you know um thing various third-party plugins um you know nougat packages resharper things like that it is fantastic way to start your github or i'm sorry your get repo so uh we'll include uh we'll include links to both of those in the show notes yep and uh i wanted to to mention another podcast like doing that apparently
Starting point is 01:23:51 oh i think i jumped ahead alan there too sorry no you go ahead i was just uh doing some you were so excited about some other podcast you go ahead i was typing yeah so i want to mention the reply all podcast uh this is a great podcast and they talk about kind of like internet-y type stuff it's almost like this american life but for um more technical people and uh some of the the episodes have been about like interviewing a guy who's new to the interview and internet um spotting you might have heard of they've got a great interview with a wiki grammar enforcer who just so wait a minute they interviewed like a two-year-old because he was new to the internet like no uh someone who'd never used the internet before possible yeah you can't find that person
Starting point is 01:24:34 it's not very many uh one of my favorites is um it was the interview with the guy who i remember when uh kim kardashian broke the internet quote unquote okay well they had an interview with the guy who was in charge of getting that company's websites, web scale, so they could handle that kind of traffic when they expected it to blow up. It's just a really good show, and I think it would be good for our audience. Sounds like the opposite of a first world problem if you're trying to find someone who's not an infant and new to the internet. They actually went to a third world country. Did they really? Yeah yeah i'm fairly certain no i don't think so i don't
Starting point is 01:25:10 know actually well no never mind so i guess i'm a jerk for thinking like you whatever yeah um all right so the one that i found while i was trying to build my little course that is turning into a big course was there was this fantastic thing in the Visual Studio Library gallery or whatever. It's called Generic Unit of Work and Repositories. So if you've ever looked into repositories for separating your concerns with your data calls calls this is an excellent way of doing it so essentially you can use one of the free tools from entity framework or not from any framework i think from microsoft for generating entity files and then it'll set up your unit of work and your repository code for you and it's fairly easy to use. Do you have T4 generators? No, no, it's not a T4.
Starting point is 01:26:09 Well, you mentioned the entity tool. No, so there's a tool that you can download from Microsoft that's a Visual Studio extension. And you can just right-click a project and say, hey, create entities. And then you point it at the database and it will actually go generate all your code. It's not using a T4 template, or at least i don't know if it is because it's a it's an extension but then after that it will they've created these nice repositories and units of work that you can literally just hook up um they have iRepository asyncs they have
Starting point is 01:26:39 regular repository they have services dude it's uh it's pretty amazing the framework that this guy set up and i think his name i can't think of it right now i it was like lee long or something like that but uh i'll have to i'll have to i hope you're right otherwise i will find it real quick random name guess uh yeah go ahead and i will find him real quick. All right. So while he's doing that. Long Lee. Long Lee. Boy, you were so close.
Starting point is 01:27:10 I was reversed, right? But no, this guy put it together, and it's absolutely killer. All right. So hopefully you like the show. This episode we talked about delegates and events and a little bit about Link and how it all works underneath the hood. So hope you liked it. And, yeah. All right. So be sure to subscribe to us on iTunes, Stitcher, and more
Starting point is 01:27:31 using your favorite podcast app. And like we said before, be sure to give us a review. We do greatly appreciate that. And contact us with a question or a topic. We definitely love getting the emails about topics. Leave your name and preferred method of shout-out, website, Twitter, whatever, and we'll mention you on the podcast.
Starting point is 01:27:50 And visit us at codingblocks.net, www.codingblocks.net, where you can find the show notes, examples, discussions, and more. Send your feedback to me. This particular episode will be... Race condition. codingblocks.net slash episode 24.
Starting point is 01:28:04 Yep, and send your feedback, questions, and rants to comments at coding coding blocks.net slash episode 24 yep and send your feedback questions and rants to comments at coding blocks.net and be sure to follow us on twitter at coding box © transcript Emily Beynon

There aren't comments yet for this episode. Click on any sentence in the transcript to leave a comment.