Coding Blocks - Design Patterns Part 1 – You Create Me!

Episode Date: June 7, 2014

This week we’re tackling the first section of seminal Design Patterns book: Creational Patterns. We discuss factories of factories, “bullet hell” games, pathological liars, and Allen’s lack of... voice. Big thanks to @rajsotweet for calling us out and getting us motivated to record! Points of Interest .NET Framework 4.5.2 is out! ASP vNext Awesome stats […]

Transcript
Discussion (0)
Starting point is 00:00:00 all right let's all talk at the same time let's see what the levels look like just say all right well so we're just gonna be jarboring over each other and then we'll see what happens okay yeah that's good all right all right you're listening to coding blocks episode 11 subscribe to us and leave us a review on itunes stitcher and more using your favorite podcasting app and visit us at codingblocks.net where you can find show notes, examples, discussion, articles, and other stuff. And send your feedback, questions, and rants to comments at CodingBlocks.net and follow us on Twitter at CodingBlocks and on Facebook at Facebook.com slash CodingBlocks. And with that, welcome to CodingBlocks. I'm Alan Underwood.
Starting point is 00:00:41 I'm Joe Zack. And I'm Michael Outlaw. And so the first thing we're going to start off with today is a little bit of news. First Rajso Tweet on Twitter at Rajso Tweet. Awesome name. Yes he hit us up this morning was like hey we're looking forward to the the design pattern so here we are we're recording this same night I appreciate you calling us out for that. And in other news, there was a release from Microsoft for the.NET Framework 4.5.2. I know we were all anxiously awaiting that release. No? Yeah, not so much.
Starting point is 00:01:18 No? Okay. It's fine. Fine. ASPV Next? That sounds a little bit cooler. Yeah. So I'm excited. I don't remember what it's involved in anymore.
Starting point is 00:01:30 It was deploying in the cloud or something, right? I don't even remember. Oh, and I accidentally deleted the link. So next awesome. So in, in cooler news,
Starting point is 00:01:44 then, uh, Kaspersky labs, a well-known name in the security realm they uh they put out a link a site called kaspersky-cyberstat.com and uh if you have a chance to check it out it's it's really awesome it has like real-time statistics of things that are happening on the internet so number of cyber attacks total internet users number of android phones that have been uh you know uh that are out there babies being born yep yep babies being born blog post today uh detected adware yeah it was uh it was pretty neat uh little stat there yeah and the uh the what was it the malware stuff that looked like they just basically took whatever number was
Starting point is 00:02:31 on there and just kept multiplying it by a million every second they might be a little biased yeah i'm not i'm not sure it could be just a random number generator like you know it felt like it was going up so fast uh let's see what else we got there's oh there's uh julie lerman on twitter posted uh that uh entity framework 7 was just sitting out there in the wild uh just waiting to be found um and uh she she posted a link to that on uh on twitter it was juliel.me slash github ef7 and uh it was a link to the github repo that contained it yeah pretty cool stuff uh in other in non uh technical news uh one of my favorite authors uh mark or son of it yeah that almost came out completely wrong how do you say it russinovich yes thank you there it is uh he he released his new book uh
Starting point is 00:03:36 last week rogue code so i don't know if you guys have read any of his uh the previous ones in his uh jeff aiken series um what was it trojan horse in zero day i believe were the other two um yeah so and you turned uh you turned me on to uh demon or damon oh man yeah absolutely my favorite series yeah gotta check out daniel suarez excellent which he had it he had in all fairs he had a new book that came out um a couple months ago now um shoot i can't even remember did you read that one uh i've honestly i've been bogged down with like technical books at the moment so i have it i bought it and and i had started to read it and then i got pulled aside with other books so is that influx yes yes it is thank you
Starting point is 00:04:26 all right and that's kind of like um the deal with that is basically like um kind of a techno science fiction when i say techno i mean like coding based so this is like sci-fi for coders well that's why i really like these two authors is that if you have never checked them out like both of them write things that are their storylines are have a lot of technology in them they're very technical but they're also very plausible technology and you know they both kind of approach it from a different angle like um mark uh thank you there you go he takes the approach of things that are like maybe um more current times whereas suarez takes the approach of things that are maybe more current times,
Starting point is 00:05:06 whereas Suarez takes the approach of things that are in development stages right now, and you might not be aware that the military is already using them, but they are things that are out there, but they're not as commonplace as what he might make them out in his storylines, but still the storylines are fantastic. So if these are more realistic and kind of techno-based or coding-based, does the protagonist Google every five minutes? I suppose you could.
Starting point is 00:05:33 Yeah, I mean, if it's going to be realistic, then there's got to be at least 100 searches per day. At least. I'll just wait for it to happen. Well, yeah, I'm not going to ruin anything about either of the books, but I'm just saying, like, you know, there's some awesomeness there. If you haven't already read, if you're not familiar with either author, then you should check them out.
Starting point is 00:05:55 And we'll have them in the show notes for you. Yep. And speaking of awesomeness, I actually just found this today, and my feelings are a little hurt. A friend of mine, it turns out, I knew he went to the PowerShell Summit recently, and it turns out that he spoke there, and there's a video of his presentation online. So without him knowing it, I am mentioning it on the show here. And the name of that talk is PowerShell Module Design Rules and When to Bend Them.
Starting point is 00:06:24 So definitely check that out. We'll have that link in the show notes. And in that same vein, someone else I know recently put a package up on GitHub that actually allows you to easily integrate PowerShell tasks into MSBuild. So what that lets you do is maybe you have PowerShell run code generation or something like that. Now you can schedule that as a real build task. So you can hit F5 or Shift F5 in Visual Studio, and it's going to run your task. Pretty cool.
Starting point is 00:06:56 Very nice. And one thing that I've actually been looking at using that for for ColorMine is actually signing my assemblies. So you can set up signing in Visual Studio, and it'll prop it right there in the proj file it'll link to your key and it'll sign whenever you build like release mode but the problem with that who needs signing well so there's an article on that which we're getting to uh coming up next but the deal with that is if i leave it checked into the project file, that means that if I put that code up on GitHub, I either need to have that secret key embedded in my source code, bad idea, or I need to not have that stuff in my project file.
Starting point is 00:07:36 So what I do there is basically just run a little PowerShell task and I can check that in and I can have the PowerShell basically if that thing out there. So if the key's not there, then don't even try to sign it. And the reason that signing is important is actually detailed in a blog post by yours truly on the website. We'll have a link to that. I've basically been looking at strongly naming assemblies in NuGet and the problems that you run to mainly around key storage and open source projects. So it's kind of a unique problem to open source projects in NuGet
Starting point is 00:08:06 that are strongly signed, and you should be strongly signing. So check that out. And finally, I wanted to mention a new video game that came out recently called Watch Dogs. And you've probably seen a lot of press around this, and it's kind of firmly rooted in Inf kind of infosec post prism world hacking it's an ios game new ios game that's not so much i'm sure there's a companion app with it but no nothing like that but it's kind of had some mixed reviews yeah it's it's a little
Starting point is 00:08:40 disappointing i mean i was looking forward to this one and all the reviews i've seen have basically just slammed the storyline. Which is unfortunate because the advertisements really made it look like it was going to tackle this kind of gray area, you know, what's ethical, what's not. There's a lot of issues. This is a hot topic right now, but it seems like the actual game itself just kind of glossed over it.
Starting point is 00:09:01 And isn't this game way late because they were trying to polish it up and make sure it was going to be like the best game ever yeah isn't that the story behind every game though that's true not the call of duties those things come out every november right on schedule that's right now granted they're using the same game with a few new maps but whatever so it's worth it yeah so i don't know i might pick up this game anyways hey i you know there's not much out on the next gen systems right now yeah when that steam holiday sale comes around i can get it for nine bucks and i'll add it to my collection of games i've never even bothered to install awesome all right so that's enough news um so today we're going to be talking about
Starting point is 00:09:43 design patterns specifically the creational design patterns so there's this news. So today we're going to be talking about design patterns, specifically the creational design patterns. So there's this kind of famous book, you'll see it referred to around the internet as the Gang of Four book or the GOF book, which is really unfortunate because you can't search for that in Amazon. The name of the book is actually called Design Patterns, just happens to be written by four people and the book i thought this was really interesting the book was published in 1994 right and it is still in its first edition it's never been updated standalone 1994 surely they must have made a typo in there somewhere no man this place comma come on every one of them had perfect grammatical syntax. Like, nothing was wrong. No, man.
Starting point is 00:10:28 This book is perfection. It's done. And on Amazon, this particular book has 353 reviews and four and a half stars. That's impressive. And what's weird is, you know, there have been talks of new patterns. I'm surprised that they haven't added any patterns either. Yeah. I mean, they pretty much nailed it all back when they wrote this thing. It almost feels like they were way ahead of their time when they wrote it. And it's just taken us the last 20 years to catch up to be like, what were they talking about?
Starting point is 00:10:57 Oh, that's what they meant. So we are bringing you fresh information on this podcast on some 20-year-old information. Well, what's kind of funny about this is like— Hey, but we're doing it in a new way because it's podcasting, right? That's right. Oh, wait. Podcasting isn't really that much. Yeah, I think there's probably been a few other podcasts on design patterns. But what I think is kind of funny about design patterns is like it's kind of a certain milestone or stepping stone on a developer's path.
Starting point is 00:11:23 There's like a certain point of maturity where you kind of find out about design patterns you go out and you learn you know you read the wikipedia article and next thing you know these factories start showing up in your code and it's kind of like almost like a sign of a good junior program when you see something you're like oh i see you've got uh 20 new factories checked in there in your latest pull request and did somebody just get the Gang of Four book? And so these creational patterns in particular, they're the first part of the book, so they're the classes that get joked around
Starting point is 00:11:51 the most because those are the kind of things that when people first start getting design patterns, they start putting in all the code and then they end up kind of rebelling against it a little bit. But it's kind of funny. Which is what we're going to focus on tonight with creational patterns right so why should you even bother studying design patterns um because you're in school
Starting point is 00:12:14 and you had to do it you wanted to make it great they taught you that in school hold on a second none of us learned a design pattern in school there's no way yeah man this book was in 94 um my education consists of nothing before 1970 oh really well interesting no man i can tell you i can tell you the big o notation for every single sorting method but i'm not a single design no but i mean this seriously like when we talk about schooling you have to forgive it honey he's going through puberty yeah puberty's catching back up uh i've kind of started losing my voice so uh actually we should have mentioned that though like he did do a presentation which is why he's uh yeah i did a presentation last night apparently my voice was not made for speaking that long uh which is great that you're a host of a show yeah i'm a host of a show apparently i used to it i can't take much of this
Starting point is 00:13:03 so that's why i have co-hosts so uh no i mean but that's one of the great things about what we're going to talk about today is these are things that most people don't find out about until they get into the real world of programming right i mean you don't learn about this stuff in school and generally you don't even understand the concepts at that point anyway so um i think these are the steps to becoming a better programmer so no doubt and so um you know we kind of joke around a little bit but um there there are a few reasons for um studying design patterns and i think that the main reason for me is when i see the word factory in a code base um after kind of you know snickering to myself a little bit uh i know exactly what that class does
Starting point is 00:13:46 or what it means. You know, it's got this kind of context behind it that I'm familiar with. So I know what to expect when I open that file. Same thing if I see a builder or, you know, a visitor or an adapter or something like that. These things have meaning. So it allows me to kind of shortcut reading those files
Starting point is 00:14:00 and understanding what's going on at a higher level. Yeah, I'm going to stick with you wanting to make a good grade. Yeah. All right. And I also want to mention there's a, you know, we kind of hinted at a little bit of controversy as of late around design patterns. And that's kind of like, it's almost like a little bit of a rebellion towards static languages.
Starting point is 00:14:20 And so you'll see people kind of mentioning design patterns in kind of a derogatory way and you can kind of research that on your own but a lot of times the arguments kind of focus around these design patterns focusing on deficiencies in static languages basically not being flexible enough not having the kind of like language
Starting point is 00:14:40 and runtime support that you would have in something like Ruby or JavaScript which I won't get you guys started on JavaScript. No, go for it. Only because I can't fight with you about it right now. No, this would be awesome. Let's do it. Let's hash this out right now. But so the design patterns themselves are kind of divided into three parts.
Starting point is 00:15:02 You have your creational patterns, which are your factories, builders, prototypes, and singletons. You have your structural patterns, which are your adapter, bridge, flyweight, facade, proxy, and there are several others. And then there's the behavioral patterns, observer strategy, chain of responsibility, and many others. And in future episodes, we'll be talking about a lot of these. But today, we are talking about the creational patterns. There was a quote from the Gang of Four book here that they help make a system independent of how its objects are created, composed, and represented. So, English par favor. That's fantastic Spanish there.
Starting point is 00:15:44 Par favor. Now, my dad was a a french teacher but i did not inherit the language you certainly did not no you did so uh so in english they help make it not i won't read it again uh it's just another way of of trying to uh break how to say this why'd you have to ask me in english so why should i care about creation patterns and what does it get me uh to well okay so how about it will promote composition over inheritance wow why do i care about that?
Starting point is 00:16:25 Because it's smaller, more focused classes. Hey, that's starting to sound a little bit solid there. Oh, God. Yes. No, because then if we did that, we're going to end up with classes that do nothing again. Oh. Well, that's what it's all about.
Starting point is 00:16:38 Smack, dizzle. All right. So the idea with creation patterns is that they help encapsulate away the logic of creating classes away into separate classes so that your classes can be created, composed, and represented outside of the logic that's actually using these things. And that, to me, sounds a lot like the D in solid dependency injection. So you're actually relying on these objects, but you don't know where they come from, whether they need certain configuration settings or whether they're talking to a database in the background
Starting point is 00:17:12 or just kind of mocking it out. It doesn't really matter to the code that's using these classes because they're not newing up the objects. And there's two kind of major recurring themes in creation patterns. But wouldn't Singleton kind of break what you just said? That's why everyone hates them. I set myself up. Damn it.
Starting point is 00:17:33 Boom. All right. So I guess the main patterns we're going to be talking about today are the factory methods, factories, builders, prototypes, and singletons. Thank you, Dr. Love. Yes. Yeah, one thing we should mention about these patterns, too, before we kind of dive in is that you're already doing this stuff. It's just even if you've never heard of the factory method, you've made a factory method
Starting point is 00:17:54 before. If you've never heard of factory, you've made a factory before. These are common patterns that we run into. And the kind of the point of studying them is that you get to kind of look at the pattern separate from the business logic and kind of study that independent of any particular domain. It's just a good way of breaking these projects up and avoiding some pitfalls that you can have if you implement it in a slightly different way. The first one we're going to talk about, or I'm going to attempt to talk about, are factories and factory methods. So first let's talk about basically just a simple factory.
Starting point is 00:18:31 So this is not a pattern as much as it is just a way to create objects without knowing them up in your code. So when you call a particular factory, what you'll do is you may pass in a parameter. So one of the examples I found, and it might have been on Wikipedia. No, actually, this was from a Pluralsight video on factories, was you call a simple factory and you pass in the type of car you want. And in that factory, essentially all it has is a switch statement saying, hey, if you pass me in BMW, then new up an instance of a BMW car. If you passed in a Mini Cooper, then new up an instance of the Mini Cooper and return that. So in your calling code, you're not saying new BMW, new Mini. You're going to pass in, we'll say, a string potentially.
Starting point is 00:19:19 And then there's going to be a switch case, a case switch statement in there that's just going to return you the type of object representing that. But it doesn't have to be based off of input, though. It could also be based off of configuration values. Config files. Right, for example. Setting this database connection string. Yeah, yeah. But usually not as much in the simple factory.
Starting point is 00:19:39 That's usually more in the factory patterns themselves. And we'll get into that in just a second um so moving on to the next one is the factory method uh which is this one was kind of interesting basically what you have is it's the same type concept you call a factory but inside that factory they are subclassing an abstract class and when you pass in something basically um on wikipedia the thing that we got that was it kind of spelled it out properly is you have two you have two game maze games is what they call one's a maze game and one's a magic maze game and basically what you have is you have this this make room method in them depending on which one you uh when you call this factory depending on which one you tell it you want the the method make room is going to be
Starting point is 00:20:40 overridden from the subclass and then that's what's going to return the new object. Oh, right. I remember this conversation. Okay, so this was the one. It's like if we were to take the template pattern but outside of a method and then talk about it in regards to classes. Yes.
Starting point is 00:21:01 So you basically have the base class that has a bunch of methods that you can then choose to override if you want your subclass to do something different. And then when the factory method is called to, in your example, make room, that would be an overridden room. Correct. in your example make room that would be an overridden room or an overridden method that would return back a different object. You could have a magic maze, implement those methods. You could have a corn maze,
Starting point is 00:21:36 implement those methods, ice maze, lava maze, whatever type of mazes. Whenever they make a room, they construct some sort of room that's applicable to their use case. One of the key things to note here is that I don't think we've mentioned yet, is when you call one of these factories to return something, they are returning concrete type. So the magic maze or, like you said, the corn maze. But really what you're getting back is an interface.
Starting point is 00:22:01 You basically have a type of the interface so that you know the methods available, but you don't actually know the type of the concrete class coming back. And that's the key. In any factory situation, you really don't want to know the exact type, typically speaking, of what's coming back because that allows you to loosely couple your code from what you're getting back. You just know that whatever interface that implements it has a thing called make room and you can call this and then it'll work so it allows you to decouple any kind of real knowledge from what it is as opposed to what it can just do when you call the methods yeah and just to be clear like i was only suggesting like it reminded me of a template
Starting point is 00:22:45 pattern from a different perspective but it's it's definitely not yeah i think the kind of the key there with the the factory methods and how it's kind of different from a simple factory is really when you're talking about factory methods uh you're pretty much always talking about more than one factory so you've got a factory for the maze game you've got a factory for the um corny maze game a one for the ice maze. These are all separate classes that create a different flavor of maze. Yeah, you only have one factory but multiple classes. Yep.
Starting point is 00:23:15 Yeah. And then you have the actual factory pattern, I believe is what this one is. It's so crazy because it's all over the board depending on where you look. But with this one, essentially what you have, this generally uses reflection quite a bit because it will be based off either a config or something else. But your factory, you are going to instantiate a factory, a type of factory. So you're going to have an interface for factory. So let's say I auto factory. And then you're going to have a BMW factory that extends that.
Starting point is 00:23:53 You're going to have a Dodge factory that extends that. And depending on a config value or a type that you pass in, it's going to use reflection to say, okay, now I'm going to new up this type of factory. And then we know that that I auto factory has a Cray automobile. And then that Cray automobile is going to return you whatever type it is. If it happened to new up the BMW factory, then you're going to get back a BMW 335i. If it newed up the Dodge one, you're going to get back a dodge ram because why would you buy anything else so um that is that is really the threw me off guard there does dodge make anything
Starting point is 00:24:35 else uh viper oh yeah good point um but so that's kind of what you get there is when you get into the actual factory pattern itself, you are basically implementing an interface with multiple different types of factories, and that's how it happens. And again, it uses reflection, generally speaking, based off a config value. So like in your config, you might have BMW as the factory type that you want it to instantiate. So it's going to use reflection and say, okay, create BMW factory. Or if you have a value that you're passing at the time. But again, the whole key is you are not newing up a BMW.
Starting point is 00:25:11 You're not newing up a Dodge. The factory is doing it for you, and you just know you're getting back a type of iAuto. Yeah, and we should mention, too, that if you are confused right now, then it just means you're understanding because this is confusing. If you try to Google this stuff, you're going to see a lot of articles that talk about the factory pattern but give you an example of a simple factory. And you're going to see simple factories that say they're simple factories that really look more like an abstract factory. And it's just kind of confusing. But the important thing to really get out of this is that you're already probably doing stuff like this.
Starting point is 00:25:45 And it's really the theory behind it and not so much the names that are important. Yeah, generally speaking, any time where you see that you're calling something and you're getting back an object, but you don't know what type it is, then you're probably using a factory pattern of some sort. And then there's the deep end. Yeah, the deep end here here which is abstract factory pattern and you thought you were confused before and i don't even know if i can explain this well with just words without having something to draw on well this is what we just talked about though the factor that where you have the no no no no the factory and you don't know you okay well hold on okay i know where you're going go go yeah yeah. So the one that I just did before was you basically have multiple factories that implement a particular iFactory type.
Starting point is 00:26:34 When you have abstract factories, basically now what you have are factories of factories, which are even more loosely coupled, but they are all somewhat related. And so essentially you're going to have your initial factory, and instead of having just a BMW and whatever else, you might have, oh God, I don't even know if I can explain this well. So you've got your BMW factory, and that might actually also have multiple factories that create cars. One's going to be a sedan. One's going to be an SUV. And one's going to be a truck, right?
Starting point is 00:27:17 So you're going to have those factories of factories that way and so if you somehow instantiate the bmw one and then you say all right that's going to create an suv then it's going to return you back in x5 if you did it through the dodge you're going to get a durango so your top level factory then knows to instantiate the bottom level factories based off another config file or or value that's passed in and then those factories are going to return you back in I auto of the type that you did. So again, these are all related items, but now you have factories of factories. Did that come across okay?
Starting point is 00:27:56 Yeah, I think to really understand this, though, there's a really fun read on joelonsoftware.com, and you can search for it if you need to we'll have a link to it in our show notes but this will really help you to understand how factories work and it's a um a forum entry by benji smith and it's uh his general purpose tool building factory factory factory and it'll really help explain everything you need to know about factory pattern. Yep, and that's also including comments from its detractors. So the problem, as you might have guessed it with factories,
Starting point is 00:28:36 is that it is a little bit confusing to talk about. And if you're going to read about these things, then I hope you like UML because you're going to see a lot of it. Yeah, nobody really buys hammers anymore and it gets to a point where you can be so abstracted in your code that it your code is just kind of like what we talked about with solid you're so abstracted that nothing actually does anything real anymore yeah it's uh it's a little frustrating at times and it actually i mean uh microsoft i mean if you ever look through any of their uh libraries of code they use factories everywhere, right?
Starting point is 00:29:08 Like almost everything they do is a factory of some sort of factory of another factory. So it's very common. So if you can learn to recognize factories, you'll be a lot better off in your coding days. Yeah, it's just a little frustrating when you come in and you're like, I just need to add an if statement. And you're waiting through these factories of factories returning factories so here's here's the interview question when would you know that you need to use a factory polymorphism i don't know i was going to go somewhere with that fired no instead it was just like a one-word answer.
Starting point is 00:29:45 Anytime that you know that you've already got certain types that are there and you want to add another type, it's great for the open-close principle, right? Like you just implement. So another auto, right? So now Scion is a new company. You can create it, implement the same interface, and now you're pretty much ready to roll, right? Like this thing can return it back to you
Starting point is 00:30:06 without having to go in and touch any of the underlying code. You're just adding additional classes. And then maybe a config. Yeah, one real-world example I like of factories and uses, if you ever used any of the AWS SDKs, then they've got this class here, the AWS Client Factory, the static class, and you've got this class here, the AWS client factory, the static class, and you say
Starting point is 00:30:28 create S3 client, create Dynamo client. It'll go and it'll read the settings out of your config file, the ones you've got passed in, it'll do all the stuff it needs to do to create that client for you, so you can just take that client then and do your stuff. You don't have to worry about hooking up the values,
Starting point is 00:30:44 setting your region, setting your secret ID, any of that stuff it's all taken care of you for you by this factory and that's all based off your configs so that's a perfect example of where you're not passing anything in it just knows how to new it up pretty much um so let's talk about some of the pros of having your factory classes first like i said a second ago it adheres to the open close principle uh if you ever have seen in your code anywhere like in your main program or in a flow of something that you've got where you're doing a just a ton of if else's or switch statement um this might and you're newing up objects based off these if else's then this is probably a good place to have a factory.
Starting point is 00:31:27 You can insert, and this is probably what your interview question was just a second ago. Yeah, I was thinking along the lines of if you needed to instantiate multiple different types, but they might all be based off of a common base class or based off of a common interface then that's when you would want to use the factory and then that way you have only the one place where those concrete types are being newed up rather than it being scattered throughout your code you're using the factory to do that for you right and also if you're creating these classes in multiple spots then you don't have to have this kind of complex logic around building these classes up and creating them. Like examples, if you're integrating like a PayPal client or something and you want to new up that client in multiple different spots, maybe for checkouts or refunds or whatever.
Starting point is 00:32:17 And you want to be able to say, you know, just create new PayPal client. And you don't want to have to worry about digging those settings up or making sure it's configured to go to the right endpoint or any of that stuff. You want one place to take care of that. And so that might be a good example of somewhere to use like a simple factory or something where you just want to kind of create that class somewhere away from the code that's actually using it so that the code that's using it doesn't have to worry about how to create this object. Right. And if you want to take it even a step further, so instead of just getting a PayPal client, you'd say, I have multiple payment types,
Starting point is 00:32:50 so then you'd have a factory of factories, right? You have a payment, and then depending on the type that's coming in, it would return you a credit card, a PayPal, or whatever. The whole factory of factory thing is just too much, though. It can get deep, right? Unless you're doing some serious api level development like really when's last time you created a factory a factory of factories that you know and i think
Starting point is 00:33:10 that's the point that benji smith was trying to get at but hold up i will say this though a lot of being able to do that kind of thing really comes down to good design right at so a lot of people in software don't take the time to sit down and design things up front when they're when they're thinking about it right like this is only something that you could really do in the design phase if you really sat down a greenfield application is what you're saying yes that's going to be your best bet right and you're actually going to have to spend some of the time in the true sdlc stuff which a lot of people don't do right they just start coding and then breaking things apart and that's why simple
Starting point is 00:33:45 factories are really easy to do because this whole thing where you see an if else or just a ton of switches it's easy to replace that pretty quickly but if you didn't think ahead of time doing this factory a factory thing with abstract factory pattern is going to be nearly impossible yeah i mean i'm not saying that it doesn't have its place. Yeah, yeah. But you have to plan. I'm just saying that in the real world, I don't know that I've ever actually seen anyone do it just randomly in their code.
Starting point is 00:34:17 No, it won't be random. It'll be planned. It'll be super planned. Yeah. So, at any rate, that's one of the pros. Another one is it can be used with config so anyway that's one of the pros um another one is uh it can be used with configs as we mentioned earlier again this usually relies pretty heavily on reflection um wait a minute what do you mean that's a pro so um if you are doing testing or something like
Starting point is 00:34:42 that and you just want to be able to choose a config value, right? Oh, okay. I think I see what you're saying. You're using the config as kind of like a poor man's dependency injection. That's exactly what it is. It's how you're newing up your factory. Sorry. I'm with you now.
Starting point is 00:35:03 So your factory might create you like a mock PayPal client or something like that rather than a real one that talks to the service. Okay. Correct. And it's basically how the factory itself is newed up, and that's going to determine the type of, you know, again, if you put BMW in your config, it would new up a BMW auto factory that would then return you the car. Man, if it's that easy to get one, I've got to go do that. I know, right?
Starting point is 00:35:20 The next thing is it can be used with inputs as well. So instead of having the config value, like, uh, I mentioned in the, uh, in the simple factory, you could just pass BMW into a factory method and it would call create automobile and return it for you based off the text. And that's literally going to be a switch statement. So pretty easy stuff. And then the other thing that was mentioned earlier, I don't know if it was outlaw or Joe that said it, but basically your rules for object
Starting point is 00:35:51 initialization are centralized. So at this point, all your complex logic that might've been just, you know, plopped out in the middle of one of your methods somewhere, this can now be moved to another area that's better for tidying that up because now that logic's in one place and it's not all scattered throughout your code so that's a huge plus is it just makes it a little bit easier to go in and work with your code the way you need to without having to worry about all this creation business logic and so here's some of the here's some of the cons again it uses reflection quite a a bit or can use reflection quite a bit. Yeah, I'll agree with the can part.
Starting point is 00:36:27 I would say, generally speaking, it probably does if it's anything beyond just the simple factory. If you're going past that, because the factories are based off interfaces, you're not wanting to new that up in your code. So the whole purpose is to get away from using the new keyword, right? So in order to do that, you're going to use reflection based off either a config value or a value that was passed in through a variable. And then it's going to say, okay, what was this? Okay, it was BMW. All right, now new me up a type behind the scenes of this BMW factory. You almost mean like inflection, not so much reflection.
Starting point is 00:37:13 Like it's reacting to some sort of environment or argument. Yes. So not like loading up the assembly and scouring through it like system.reflection. Yes, I agree with what you just said yes yes because because because when you were talking about with it being reflected because a lot of the factory patterns i've seen in the implementation haven't been reflection based but coincidentally there was that article that we talked about that i published uh last time on the site that was reflection of control and in it the quote factory was using uh reflection
Starting point is 00:37:47 to scour the the type assembly that's what this does but i don't think that's the norm though like that was uh just the way i implemented that particular factor but i wouldn't say that like most factories are doing something like that again anything beyond a simple factory simple factory no because you're passing it in time and usually getting out a new object. But if you're doing the true where you have factories that are based off interfaces, then at that point it is probably using... Factories that are returning an interface, you mean?
Starting point is 00:38:17 No, factories that are based off an interface. So you have I auto factory, and then you have two auto factories. You have a BMW auto factory, and then you have the Dodge auto you have a bmw auto factory and then you have the dodge auto factory based off the value that was brought in it's going to look through the assemblies for a dodge auto factory and then knew that up for you that's why i say it's based off reflection um i don't know if that clarifies anything makes it muddy or whatever so that's one of the cons it can be based off reflection we'll say can i'll stick with the can all right so uh and then what was the last thing i think that might have been it right yeah we already mentioned uh benji smith's um thing on the nobody really buys hammers anymore
Starting point is 00:38:59 this is a great read oh oh oh and then the last thing was there can be an extremely and we talked about this complexity the deep hierarchy of classes right like if you do the abstract factory pattern it can get so uh unwieldy unwieldy that it could be i mean it could be really frustrating to follow that kind of stuff yeah you're creating a class to create your class so you're definitely uh exploding your code a little bit. Yeah, and it can go deep. I mean, it could be more than one or two levels, right? I've heard stories.
Starting point is 00:39:32 All right, so that pretty much takes us through the factories and factory methods and abstract factories and yada, yada. Next up is builders. Shit, yada, yada over the best part. The best part is coming up when we talk about singletons. Oh. Okay. Grudge match.
Starting point is 00:39:51 Oh, God. Versus. All right, but right now we're talking about builders. And builders are different in that they're more about having your callers put together your actual object. So in the factory examples we talked about, it's really the factory that knows how to put these objects together. But in the builder, it's when you don't really know what you want that object to look like.
Starting point is 00:40:19 And so you need the calling code to actually put that together. And I think the best way to explain that is actually with some examples from the.NET framework. One of my favorites is the string builder. And so what you usually use string builders for is it's a convenient, great way to actually build strings in memory. And you can do stuff like loop over arrays or lists and actually append to the string builder. And when you're done kind of building this big, string, you say string builder dot to string, and it generates you an object based on those kind of complex decisions that you made along the way. And maybe even a better one to mention is the
Starting point is 00:40:54 actual URL builder. And that's a class where you can pass in like a domain name, and you can pass, you know, a query string. So things like that would go up in the URL arguments, request variables, get type stuff. And you can kind of compose this method by method. You say add argument, add argument, set domain. Then you say to string, and out comes your URL. It's actually the URI builder. Oh, look at that. I need glasses.
Starting point is 00:41:28 URI builder. So now we need a factory to create you some glasses i'm sure someone's made a url builder so he just made himself right see what he did there that's right but uh what what um i don't know if i can explain this very well you guys will have to help me here but to me the big difference between this and Factories is that it's the client code that's calling the shots. Well, I think even taking it a step further, though, you're actually building it. It does exactly what it says. So you have your initial thing where you instantiate your builder class, right, like your string builder. And then you're going to keep calling append, append, append, append. And so basically what it's doing is it keeps taking your inputs,
Starting point is 00:42:07 and then when you're finally done, you call toString, and then it spits you out what you want at the end. I almost fear that the string builder example might be a little too simple. I'm not saying that it's not an elegant implementation of it, but it might be a little too simple and easy to overlook the complexity of really what's happening there but my uh my initial takeaway from from what the builder pattern does for you is use the builder pattern when you need to build complex objects um the factory pattern isn't
Starting point is 00:42:40 necessarily that it's building a complex object although it may be but hiding that complexity exactly you're not aware of any of that whereas with the builder pattern you you can be adding you know a little bit more aware of it so in your uri example if you're specifying a port or you're specifying a protocol or you're specifying the host like you're more aware as the caller of the parts that you're saying like these are the parts that i want now go make me a pizza i don't care about how you had to do it like i don't want to know what you had to set the the oven temperature to but i want some pepperoni i want some cheese you know you know you're going to go through the ingredient list and then it's going to build the complex object for you right and you know talking about our maze example, an example of a maze builder here would be
Starting point is 00:43:25 a class that had methods like add room, add door, add trap, something like that. And it would actually be up to the client to determine what order and how to call those arguments in order to construct its final object. Yeah, that's actually a really good example. And then it does spit you out the thing at the end, right?
Starting point is 00:43:43 That's the whole point, is you provide the pieces, the ingredients, as it were, and then it sp spit you out the thing at the end right like that's the whole point is you provide the pieces the ingredients as it were and then it spits you out the final product yeah so it's really the client code that's calling the shots so that one's pretty simple or by calling the shots you mean like adding the ingredients yeah yeah i like the idea of ingredients the The pizza thing was beautiful. You're welcome. Yeah, yeah. Italian outlaw. Hey, it's a little pizza. Isn't pizza actually American, though?
Starting point is 00:44:14 All right, for another show. Yeah, I don't know. All right, so what we got for pros, then? What's some pros on the builder? It's a great way to build a complex object. I've never worked with a something that had a builder suffix on it and said oh man i wish this was done some other way that's a good point it feels elegant right anytime you use one factory builder
Starting point is 00:44:36 now you're onto something a factory builder factory hey so seeing as how we don't have this in the tip of the week i mean for those who don't know what the string builder class is shouldn't we kind of tell them why it's important uh absolutely you should yeah so i mean take it away froggy right yeah i mean for anybody that's actually doing dot net stuff you see a lot of times people just keep appending to a string right strings are immutable every time you change change it, it's recreating it. You're getting new space and moving it and moving it and moving it, right? With a string builder, it doesn't do that.
Starting point is 00:45:12 You just keep appending to the object, correct? And then at the end of it, it creates you a string. So it's not keep moving memory locations. As far as I understand it, that's pretty much the way it works, right? All right. All right. So trick question then. Which one produces the faster operation?
Starting point is 00:45:30 A string builder.append, food.append, bar.append, and just keep on doing operations similar to that. Or concatenations with plus sign. Or string.format and then specify all your variable pieces and then have your parameter list or the last one would just be doing a bunch of string objects and then well i guess we already can cat that's the plus plus plus yeah yeah and it was what i like better the format i think would be faster all right format i got i got format faster from alan joe uh i like format better okay you like it better yeah it's more readable you see what's
Starting point is 00:46:11 going on if it's not super long yeah it's nice but but which one do you think is faster though not like better i like the uh format better yeah because if i'm right when we go back to our boxing thing it did not do that. It doesn't box those rights. There's actually a lot of – you can do your own Googling on this one, but there's both in the – well, I'm mostly thinking of the C Sharp world, but in other languages too maybe, and in Java because Java has similar concepts. There's a lot of uh
Starting point is 00:46:45 discussion about you know they each have their similar versions of doing these same things like the stringed up formats for example or the concatenations and uh it's the appender the string builder that's they're going to be the faster operation if you were to you know scale that out right and see which operation actually uh you know was faster interesting over and over even though i'm with joe that from a readability point of view the string.format is so much more clear to the developer coming behind you but depending on the language that you're working in it might not be as a good a performer i got a a question for you here. So have you ever seen a string builder that wasn't named builder or SB? Um,
Starting point is 00:47:30 yeah, they're always SB. Yeah. SB is it? Yeah. Or the same with URI builder. Yeah. It's always builder.
Starting point is 00:47:37 Is that a builder thing? I don't know. I guess it's kind of an abstract concept. Well, same with the factories though, right? It's always factory. Something factory.
Starting point is 00:47:44 Factory dot create stuff. Yeah. All right. Yeah. True. So maybe that's what the gang abstract concept. Well, same with the factories, though, right? It's always factory. Something factory. Factory.createStuff. Yeah, all right. Yeah, true. Maybe that's what the gang of four was really trying to get at. They just wanted us to all use common variable names. Right, yeah. Yeah, and it's nice that someone can see builder and know exactly what that means,
Starting point is 00:47:57 but the downside is it's definitely an abstraction from your domain. So, and we got any cons, then? What do we not like about the builder pattern absolutely nothing nothing you don't like about it i love that pattern love it it's your friend it's a little bit more verbose but i mean it kind of has to be right for what you're trying to do so yeah i mean it goes back to the whole thing you're adding your ingredients one piece at a time so uh it kind. I don't think there's any way around that. I got a question for you, a nice theory question. Is it still a builder if it takes away?
Starting point is 00:48:32 If I had a Starbucks class or a coffee class and you could say stuff like add parentheses soy, add parentheses vanilla syrup, what if I have a method like remove whip or no whip yeah it's still a builder yeah same thing it's just it's just taking away you're whittling away you're basically forming what you want this object to look like when it comes back well i can actually back that up with a real world example since we were talking about the uri builder if you were to specify the port as negative one, then it won't include the port when it does the two string on it. Nice, perfect.
Starting point is 00:49:09 But if you had a port otherwise specified or if you didn't specify negative one, then it would include either the port you specified or the default. So then I could create a class called a builder and only ever have it take things away. Potentially. I guess if I really
Starting point is 00:49:28 wanted to annoy you. And you're going to call it Black Hole, right? Black Hole Builder. Or Destructor. I'm going to make a little note and see if I can do something useful with this. Just to annoy everyone. To make a Destructor. And here we thought we were. I think this is how
Starting point is 00:49:43 Megatron got started. Evil. So I think we thought we were going to blow through builders, but it's actually kind of a fun one to talk about. Well, because it's one that you don't really think about that much, but it's out there in the wild, and you are already using it. And it's highly useful. But, yeah, so we'll move on.
Starting point is 00:50:04 So we did get some, in other news, And it's highly useful. and ask that if you can, give us a review, give us a rating. We really appreciate that. Like I said, it goes a long way to helping us out and helping others to find us. Yeah, and if you don't want to type one, just go click the five stars. I know that's what you want to do. Or copy someone else's. Make sure it's a good one, though. Yeah, agreed.
Starting point is 00:50:43 But, no, seriously uh the reviews are greatly appreciated so please if you happen to remember this after your drive listening to this you know uh go into itunes or stitcher or wherever and and you know drop us a little note yeah drop us a five-star review and then write us and let you know what you really think yeah yeah we're good with that all right so that was our mid-episode call to action. And we've still got a few more patterns to follow up with here. Those crazy creational patterns. That's right.
Starting point is 00:51:13 Back to those creational patterns. And the next one I want to talk about is not really something you talk about that much, at least in C Sharp, and that is the prototype pattern. And that's a pattern where you create new objects by cloning existing objects at runtime. And the two key words there are cloning and runtime. And I looked for some examples in.NET framework, and I couldn't really find any good ones. There's a clone method on system.encoding. There's one on solid color brush.clone. But I had a really hard time kind of justifying what those did. I'm sure it's really useful.
Starting point is 00:51:49 I just don't know. An example you're probably more familiar with is actually JavaScript. So its whole inheritance model is built off of prototyping. And so you basically clone objects, add to them, take away, and clone, clone, clone. And as I mentioned, the important parts here are clone and runtime. So an example that I actually just coded up here and will have a link to in the show notes is like kind of a 2D shoot or something like Gradius or 1942, or if you've never played games like this uh you control some sort of little ship it flies around the screen and shoots um lots and lots of um aliens or bad guys and as you kind of move around on this board you pick up power-ups and it changes
Starting point is 00:52:37 your bullets into fire or bombs or makes them shoot faster or two bullets at once or whatever. Is this how Mario got to be big? I don't know about that one. No? Okay. Now you got me thinking. That's not how I would have done it. So for this type of game, how I kind of thought I might do it one way would be to have my ship have like a prototypical copy of a bullet, right? And this bullet could have something like a speed property and maybe a power property that tells you how much damage it does to the bad guy.
Starting point is 00:53:15 And as I navigate my ship along, I can pick up power-ups and power up my bullets. But as I power up my bullet, I don't want to actually affect any of the ones that are out there now. So if I pick up like a laser power up and I've got a bullet that I previously fired halfway across the screen, I don't want it to change. Right. So every time I shoot this bullet, I make a clone of my prototypical bullet and then make it visible and shoot it off. Right. So that's kind of cool, but that's not the real power. Right. The real power here is that it's at runtime. So when I'm cloning these objects, I don't actually know what i'm cloning as long as they can clone themselves that's all i really care about so these can be bullets that i don't even know about at compile time so i could load like a third-party dll if i'm you know like enabled uh if i have a
Starting point is 00:54:01 game that's enabling mods and i can create and shoot bullets that third parties create, which is really cool. And it'll just kind of work and plug in as long as those objects know how to create themselves via a clone method. And that was the real key to what you were talking about, the runtime, was being able to pull in that plugin at runtime
Starting point is 00:54:21 and just clone those, which is really cool. Yep, I can shoot anything that knows how to clone itself. And Microsoft actually, the.NET framework actually has a method built in called clone that will do just that. And you can implement the iCloneable interface, create a clone method that returns an object, unfortunately. And there you go, you've created the prototype pattern. The problem, of course, with object is that you have to cast it,
Starting point is 00:54:48 and you're losing that compile time type safety. So you're boxing everything. Yep. I like to think maybe if Microsoft was doing that now, they would do something with generics. They could kind of enforce that, but I don't really fully thought that all the way out, so maybe it's not a good idea.
Starting point is 00:55:02 So anybody listening to this that had no idea what he's talking about when he said 1942 or uh gradius on the ipad you can download r-type awesome game and that is very similar and you should all go pay a dollar or two or whatever it is and play that until you just can't play anymore yeah and if you're not super old and maybe you grew up on Unreal Tournament or whatever, it's the same kind of concept. These games have mods. You can run around with a certain kind of gun, pick up a different kind of gun.
Starting point is 00:55:32 It doesn't modify the bullets that you have in flight, and you can also pick up guns that are made by third parties. Yep, very cool. All right, so what are the applicable reasons for doing this? Well, I like to think that if you don't know what you're going to be creating at runtime. So a good example here is another game, the game of Spore. I don't know if you guys have ever seen this, but it's got like this kind of creature creator where you can walk around and eat stuff that lets you evolve things like more arms or snouts or wings or whatever. And as your little creature kind of grows and procreates and creates little babies and
Starting point is 00:56:11 gradually takes over the world, then you're basically cloning these things and copying all their properties over to the next generation. And what's nice about this is you didn't have a class that specifically modeled this particular creature. It was all built up at runtime, possibly using a builder pattern, and then it's cloned in order to move on to the next generation and modify from there.
Starting point is 00:56:36 So that about wraps it up for prototypes. Pretty cool. We'll have a link to that GitHub project. So I guess we don't want to talk about singletons then. Nobody uses them. I think they were deprecated. All right. So just strictly speaking, right, from a pure dictionary kind of point of view, right,
Starting point is 00:56:58 it's a single instance of a class, right? The class itself restricts the instantiation of it to so that there's only one of it okay you know i i think if you didn't like singleton so much i i wouldn't dislike them or i wouldn't pretend to dislike them which is actually what i'm doing here well it's not that i like them so much it's just that what bothers me though is that when people get into their little uh you know anti-pattern crap that i'm like whatever so uh you know all right so so what does the the singleton structure normally look like right so one of the usual suspects in your um singleton um class is that the constructor will be private and it'll be parameterless right that that's
Starting point is 00:57:47 norm you know the bare bones minimum normal part that you'll see to it there's uh several different ways within um c sharp and java that you can create a uh a singleton. I'm not necessarily going to go over all of them, but just briefly, there's versions that you can do where you need to worry about thread safety, some that you don't need to worry about thread safety. There's static constructor singletons. There's double check locking singletons. So the point is that even within msdn there's several
Starting point is 00:58:28 of them um john skeet has written up an article where uh he he talks about um i think it was like a half dozen of of the different implementations for it and what he thought were the pros and cons for it so point is there's a bunch of them, right? And there's some that everyone likes and everyone has their opinions on it, right? But you said parameterless constructor, and if I had to kind of take a guess at why that's important, I think it's because these classes know how to create themselves, right? That's part of their draw.
Starting point is 00:59:05 Right, right. Because we don't even really know who's going to cause that creation, at least in the case of, like, you know, statics. We don't know who the first person to call that guy is. Yeah, that's true. So with a static constructor, you know, you're not going to take any kind of access modifiers or parameters on it. And it's going to be called automatically to initialize the class before the first instance is created.
Starting point is 00:59:32 So this is going to be through a static constructor, the way that's going to happen. And that constructor, you can't call it directly. And you have no control over when that constructor is executed at runtime. Now, I'm not so much a fan of those just because you have no way to do anything else with it a second time if you needed to. We'll come back to that in a little bit. But, yeah, it is a popular way to do.
Starting point is 01:00:06 Static constructor singletons are a popular way. And it's a valid way for some of your smaller use cases. Or, well, let me rephrase that. When you have – I like to think of it as like a simple class. Like when there's not a lot of logic to it then you know then it's maybe more safer to do it that way um so you know if you think that there's a chance that you're you know you could have any kind of a constructor exception thrown then static constructor is not going to be the one for you right because you get stuck in that uh that nasty
Starting point is 01:00:43 loop right um it does beg the question though like you know if you're when you're doing your is not going to be the one for you. Right, because you get stuck in that nasty loop. Right. It does beg the question, though, when you're implementing a singleton, if you should seal it or not, right? Because you can inherit from it. Is that true? So I know for a static class you can't inherit from it. Is that true? So I know for a static class you can't, right? So I know you can't seal a static class as far as I know because you can't inherit from it anyway. But if you had a singleton, right, and you sealed it.
Starting point is 01:01:18 I mean, the point is you only want the one. The one, yeah. So why would you allow for inheritance? You wanted multiple singletons of the same type. And so I guess that's kind of a downside to singletons is you're making a decision right there that there's only ever going to be one. Well, it's not required as part of the singleton implementation, but it certainly makes it more clear to everyone who's looking at your code that, you know. There shouldn't be more than one of these. Right.
Starting point is 01:01:48 I don't know. I mean, what if you had a singleton class that you could subclass, right? You could subclass it and let's say that it was two different types of connections. I don't know. Would that work? If you basically had, you didn't make it sealed, so you could inherit from it, but then your other two classes had the constructors that would new them up,
Starting point is 01:02:17 and one basically pointed to, I don't know, one directory and another pointed to another directory. But the point is that your base class would have all the implementation behind the singleton. Yeah. So how are you going to do that? Okay, here's an example. So maybe it's not so much that I want to have two
Starting point is 01:02:35 singletons around, but rather I want to use mine instead of yours. So I want to extend yours, override something, and then just only use mine. Yeah, you could do that. You could only override certain methods in it, right? As long as they're not static.
Starting point is 01:02:52 I mean, honestly, I've never tried to inherit from, you know, to create a subclass of another singleton, but that seems problematic. But you could do it. I mean, that would be the reason you wouldn't seal it, right? You could do it i mean that that would be the reason you wouldn't seal it right you could do it well what if you've got like um we'll say a singleton for like caching right and this caching could hold a bunch of memory and it might you might want to have um basically an abstract class for that that contains methods like flushing or stuff that's going to be common to all the children so the children are all we'll come back to that i mean like the the idea of inheriting from it seems to be weird but well let's let's move on though so because there's a
Starting point is 01:03:35 lot to get into here right so there's the static constructor that we talked about and you know one of the downsides to it is that um you, you know, if there's the possibility that anything bad can happen in it, you're not going to be able to reinitialize that static constructors. You can't do anything about it. Um, that sucks. Yeah. Yeah.
Starting point is 01:03:57 Um, there's another way that, um, John Skeet had, had, uh, written about, which I actually found interesting when I stumbled across this
Starting point is 01:04:06 article that he had, and we'll include a link to it in the show notes. I'd actually never seen this method done before, but I thought it was an interesting one where you have an outer class that the world can use, but then inside of it you have an inner private class that actually represents all the singleton construction logic. And you can have it to be a lazy initialization, but yet, um, um, you, you know, use, you know, because it's used by an instance field, for example, but, uh, you know, you, you can, uh, what am I trying to say here? Um, you can delegate to that inner class. Um, so you, you've got a class here that's got an instance method, right? So when you call, you know myClass.instance, it gets you that one single instance of it. Yeah. Okay, I see.
Starting point is 01:05:10 That's kind of cool. So you've got the class there, and then you've got this instance thing, which is basically responsible for creating that class the first time if it doesn't already exist. Yeah, it was, like I said, it was an interesting way. I hadn't used that one in my own code before, but when I saw his take on it, I thought, well, that was a pretty neat pattern with the private inner class to represent that static constructor singleton.
Starting point is 01:05:42 Yeah, and there's two things I really like about that, just kind of off the cuff. And one is the lazy initialization, right? Kind of like the static. So it only creates itself after and if it's called. But my favorite part there is that seems like an easy way to reset. And that's a problem that I see with static constructors. If you've got any sort of properties there and you just want to kind of reset that back to its initial state,
Starting point is 01:06:01 then you have to remember to go back and reinitialize all those settings to whatever their defaults were, which usually involves some sort of, you know, hacky reset method or something. But in this case, you can just kind of say, you know, set my object to null, and when you recall that instance again, if it sees that null there, it can go ahead and create it, and it's totally
Starting point is 01:06:20 from scratch, whatever the initial value should be, without you having to worry about what those were. Interesting. Yeah, yeah, I mean it is trying to combine the you know the both worlds there with the lazy initialization and the static constructor but then there's the more um uh you know let's call it the more modern way where um you know depending on you your version of dot net you might be able to use this, which is the lazy of T type. So you're going to be on a.NET 4 or higher.
Starting point is 01:06:51 And then in this singleton implementation, you can pass in the delegate constructor to it and still have your static instance, right? Based off the type. Yeah. It's another interesting approach on it, but I will say that, and maybe this is just from old school, kind of stuck in my ways,
Starting point is 01:07:38 my more tried and true method that I'm more of a fan of is the double-check locking version of that where in my whatever I'm going to use to represent my instance, then I will have a check to see if the instance is null and then grab a lock on some object and then check it again to see if the instance is still null. And then if it is still null, then I'll new up an instance of it. And then after I break out of the ifs, I'll return that instance. So, um,
Starting point is 01:08:08 you know, I, I call it a tried and true method, but that really depends on your language of choice though. And it's self healing too, right? Cause the static example, it crashes once it's done.
Starting point is 01:08:19 But in this case, if it crashes creating the first time, the second time comes around, it's still going to see the object is no, and it's going to try again. Well, so that's why I really like that pattern or that version of the singleton is that because it does give you some control over, you know, you're doing lazy initialization by not newing up anything at the time
Starting point is 01:08:42 that the application is loaded, but you're not doing it until you actually try to call it. So you get that advantage of it, but you have the advantage and the flexibility of saying, you know, if I want it to be, to reinitialize itself, I can just null it out and let it do its thing. Right. Um, provided you provide a setter. Yeah. Um, yeah. Or, well, you know, maybe some other way of, it doesn't have to be a setter, but some other way of having it null itself out if needed. Right? In Java specifically, the double-check locking pattern was not recommended prior to J2SE 5.0
Starting point is 01:09:34 because there was a bug in that runtime where there could be an out-of-order write that would allow the instance reference to be returned before the constructor was ever executed. And so depending on how parallel your system was and how fast it was, more often than not, you would see that cause a problem where you were expecting that the instance had been created because you were using the double-check locking, but because of the because the bug it hadn't yet and so then you would get back on a null reference or no null pointer exception um so so you know that's it in a nutshell uh you know related some of the types now you know like i said there's you can easily go and look and and there's at minimum a half dozen different ways on how to implement a singleton.
Starting point is 01:10:32 We talked about double-check locking. We talked about the lazy T. We talked about interclasses, static constructors, and we even talked a little bit about kind of sealing and inheritance. I'm not sure if we really said what singletons or kind of what the point was. Okay, you're right. So because I did go over like the base definition of it, though, when I said it was the single instance of a class. Yeah, but why would I want that?
Starting point is 01:10:58 Okay, so there's a couple places like, okay, some examples that you might only want one instance of the object, right? So, like, logging is one example that might be given. So, like, log for net, for example, right? You just have the one logger or log reference that's handling all of that I.O., and you're just trusting it to do it for you, right? Okay. That could be one example. that's handling all of that IO and you're just trusting it to, to do it for you. Right. Okay. Um, that could be one,
Starting point is 01:11:27 uh, example. So, so to follow along with that example, I could have used a factory there and said, create me log writer. I get my log writer and, and write along with all the other log writers. Or I could have a singleton called log and say log dot right.
Starting point is 01:11:39 And then wherever my code calls that, I don't have to worry about creating a new client. I can just kind of go for it. But the difference there though, is in your scenario where you were calling your factory, right, then you could have out-of-order writes happening to your log. And since you want these to be time-based so that you can go back through and later look at that log if you needed to replay anything or understand what happened. You want to be able to look at that log in the order of events that happened, right?
Starting point is 01:12:09 Right. So that might be an instance where you want to make sure that there's only one thing that's writing to that. Right. Yeah, I want a shared stream. I don't want a whole bunch of writers writing to this file. Well, on top of that also, with your singleton. Wow. Go ahead, Froggy. writers right into this file well on top of that also with your singleton wow go ahead froggy you've only got the uh you've only got that one instance on the heap right whereas if you're doing something like the factory anytime you instantiate that you're creating multiple pointers to multiple
Starting point is 01:12:36 spaces on the heap yep so well that's the point memory as well right but yeah but also and also not only the memory problems but then uh you you had multiple objects all trying to write to the same file, then you could get into I.O. Concurrency issues. Concurrency issues, too. So logging is an example that you will often see in regards to, well, why would I want a singleton? Well, in other places, like database connections, right? I've got some other ones, but we'll come back to that. Yeah, it sounds like it's useful whenever you need one object
Starting point is 01:13:10 to coordinate actions across a system. Thank you, Wiki. So another thing, though, at least in the C Sharp world, when you're implementing your singletons, you will often use your volatile keyword here to indicate that a field might be modified by multiple threads that are executing at the same time. So this will give you a good opportunity to use that one
Starting point is 01:13:43 if you haven't already. Yeah, I'm going to have to vlad and ask him about volatile again because as soon as he explains it to me and it's been at least twice now it just flies right out of my head along with regular expressions i love reggae so um yeah've, I've given the brief overview of, of the singletons here and the different versions of it. Um, yeah, so, so there's definitely, it makes them sound, you know, pretty rosy there, right? It sounds nice. But if you guys are near a computer right now, I've got a little ask of you. If you could just go, you you know open up chrome tab whatever
Starting point is 01:14:25 go to google and just go ahead and type singletons are oh i wasn't i wasn't trying to bring you into that oh oh i'm sorry did i uh did i do something wrong here because if i say singletons are then the first evil the first result there slip of tongue there there, is evil. Second is bad. Third is my favorite. It's pathological liars. Okay, well, that wasn't exactly where I was thinking that you were going to go with this. Okay, okay. I had something else in mind, but me versus the rest of the world.
Starting point is 01:15:00 Oh, yes. oh yes yeah specifically uh you know again we'll post the link in the show notes uh to john skeets article but um you know if you have if you're not already familiar with him he's a very well respected author uh i like his books and but he and i do have a difference of opinion uh when it comes to the preferred singleton implementation because he's a fan of the static constructor version of the implementation whereas like i said i really prefer the double-checked locking version and you if you read his article he makes a case for it why he doesn't like the double-check locking and some of that was based on you know uh language portability so you know depending on yeah depending on the version of java that you might be using then you know maybe that's not going to be usable for you
Starting point is 01:16:00 but um you know like i said it's – I don't like the static constructor version unless that is a simple class, right, that singleton's class. If there's any chance that that singleton could throw any kind of exception, then, you know, you're hosed in it. And I like the ability that I can reinitialize it if I wanted to. And I know that some will say, well, if there's the possibility that it could throw an exception, then you probably just need to refactor that to begin with. There's already other problems. And I'm not going to argue that point.
Starting point is 01:16:41 That's a fantastic point and a valid point. I just like the flexibility of the double-checked locking. Yeah, it's self-healing, right? It's nice. Yeah. But there's something about seeing that static class there, and you know exactly what that means. There could be only one.
Starting point is 01:16:54 I've never actually seen a class named something singleton, unlike the other patterns we've mentioned. So it's kind of nice to have that visual indicator. That's not a strong argument for it. Yeah, well, I mean, as far as your naming is concerned, though, it's not as nice as the naming, though, because it's still kind of hidden, though. It's like, you know, if your eyes happen to scan over that static keyword
Starting point is 01:17:20 in front of the constructor, then you might not recognize that it's a singleton at all. Whereas at least in my mechanism where you're you're using an instance uh property um you know to to represent your singleton it might be a little bit more clear to you if you were to come by behind me and look at the code yeah um if i see dot instance i know what that means and you know i've never actually seen the lazy T implementation in the wild before. Yeah, and I think that's because depending on the.NET framework that you're working with at the time, then it may not just be available to you.
Starting point is 01:17:56 And this goes back to the portability point of view, though, is that the lazy of T is definitely going to be specific to dot net and specific versions of dot net whereas you know like a double check locking a mechanism or a static constructor are going to be a little bit more general purpose right yep so then there's the anti-pattern crap. The naysayers. Oh, gosh. So I'll tell you, the thing I don't like about singletons is that they're generally a facade for global variables and global methods, like we mentioned with the logging, which is okay. But I generally think of globals as ways of kind of cheating proper encapsulation. But no, because you're not using them necessarily
Starting point is 01:18:49 like a global variable to share some value that you're going to use over and over. You're using them as something to do something for you and you only want the one. Not necessarily. It can be used exactly like you said. But, okay. and you only want the one. Not necessarily. It can be used exactly like you said. But, well, okay, so it's always bad to do bad programming.
Starting point is 01:19:11 Right. Okay. But where the intent of my point a moment ago, though, was that the purpose behind it isn't to, you know, if you're using it to store a variable that some user input, you know, and then you want to carry it throughout the rest of your application. And, you know, that's a whole other problem that you got going on there. You know, it's generally because you only want the one of the something. But do you always just want one of the something?
Starting point is 01:19:42 Like in the log example, you know, that's an example of a concrete class that knows how to create itself. So my calling code, you know, it's nice that it can just kind of say log dot right. But what's gross is when my unit tests start writing logs on my CI server, you know, something like that. Okay.
Starting point is 01:19:57 So this is where, um, some of the anti-pattern, um, FUD. Yeah. Well, I was trying to think of a good word for that.
Starting point is 01:20:05 You know, the case comes in about like, you know, that, that crowd doesn't like the singleton pattern because they say, well, it mandates its own creation and life cycle and persistence. And,
Starting point is 01:20:17 you know, it makes it difficult to test. How can you market things like that? But, um, and you're literally like kind of cementing this concrete class into your input into your calling code i mean the other patterns seem to get away from concrete implementations right they're not tightly coupled i'm not saying that it's okay so um it can be
Starting point is 01:20:41 right but like okay so like a static constructor singleton, right? I can definitely see a strong argument for that being difficult to test because if you wanted to say, let's say that you're testing your singleton class, right, and it's a static constructor singleton, then sure, now all your test cases that reference it, there will only be the one. So if you needed to have the ability to reinitialize it, then in your test case you can't, right? But, for example, going back to the double-check locking mechanism
Starting point is 01:21:11 that I mentioned where it's backed by an instance field and it can self-heal, as you put it, then you could have the ability to do some sort of a reset on it, depending on whatever method you named inside that singleton that would set your variable behind the scenes back to null so that it would self-heal the next time you called,
Starting point is 01:21:34 then I could see where that argument is kind of lessened as far as the inability to test the singleton. Yeah, and bad coding is still bad coding. You can mess anything up. But I usually see singletons in places like that that are kind of scary. And so if you've got a unit test that does some stuff and it modifies the state of that singleton, then you need to make sure in all those tests that you reset that state back
Starting point is 01:21:59 to where you expect it to be when you run, which is already kind of a weird situation anyway. But just something to kind of watch out for. It's definitely the biggest problem I have with it is testing. Right, and that's the whole general theme around why I'm not crazy about the static and structure singletons is that you have that inability to reset them, whether it be actually in your real production code
Starting point is 01:22:25 or in your use case, regardless, either way, you're up the creek. But another great example where you may want only one, right? And this is going back to the beginning of the show when we talked about your factory pattern, right? You might have a case where you want your factory pattern to return back a quote null version of an object, but it's not truly null keyword, but what you're wanting to get out is return back an empty version of it. So there's another pattern that's called the null object pattern, right? Where you return back
Starting point is 01:23:14 like a safe version of an object. So for example, the null object pattern could be simply if your method is supposed to return back a list, but the user didn't provide you something, rather than returning back the null keyword, you would return an empty list, and that empty list is used as part of the null logic pattern. So going back to the factory pattern, if you needed to return back some object that represented a null version of the object or an empty version of the object, you want to make sure that there's only one version of that null object.
Starting point is 01:23:58 In Alan's factory examples, he was using cars, right? So if you had a null car, right? You only want one null car. And the reason why is for equality checks later on, right? So if you had, if that null car was able to be implemented, or I'm sorry, instantiated multiple times, and you later wanted to say like, okay, well, did the car i just got back equal equal the null car well that wouldn't work unless it was a singleton yep but there there are other ways to kind of create singletons without actually specifying it in that class like the example i always come back to is dependency injection i can actually configure configure a class to only live for that application. And I can even control when it gets initialized.
Starting point is 01:24:48 So then that lets me handle the persistence and keep it alive and make sure there's only ever one. But I can also control the life cycle somewhere else, like in testing or in some other way. By the way, we definitely have to thank Raj, so tweet here, for getting
Starting point is 01:25:04 Alan out because he is dying. We are actually watching him. He's slumping in his chair as we speak. But he didn't want to let you down, Raj. Yeah, no, I mean, I understand your point. So, I mean, sure, there are a thousand ways to solve the problem right um but my only point like when people go on with the anti-pattern uh case though is uh there is a place for it right i mean that you know it's why it became a thing right if there was never a place for it and and no one ever needed this pattern
Starting point is 01:25:44 then it would have never been used like you know maybe it would have been written about and people would have just blown it off but you clearly there was a a use case for it and you know it's there yeah it's very practical you know a lot of times the the solution you see to the whole singleton antipyton thing is use the dependency injection and everyone writes about that on the internet on their blogs and on twitter and then they go to their day jobs and write singletons right yeah so yeah maybe that helps maybe it doesn't but uh yeah yeah so just to kind of recap that so singletons their big draw is that they know how to create themselves and so what that means is you don't have to configure these guys and create them.
Starting point is 01:26:27 You don't have to new them up. You don't have to have a factory. Your guys, your client, your calling code can just go ahead and just call methods on this thing, and you don't have to worry about whether it's been created, what the state is, any of that stuff. All that lifecycle stuff is handled by the class itself. That's a good summary i'll go with that cool so we actually so we just talked about all the creational patterns that wraps this up so wanted to kind of go over them real quick again so we talked about factory methods we talked about
Starting point is 01:26:58 all the different kinds of factories we talked about builder string builder url builder oh you forgot the uh hammer the factory the tool factory builder factory factory yeah don't hammer factory we don't buy hammers anymore though all right so we talked about factory factories we talked about builders we talked about prototypes with the whole kind of weird bullet thing and then we talked about the infamous singleton pattern and that's it for our main topic yeah so uh we got some resources that uh we'll be including in in our show notes there yeah first and foremost is that gang of four book which is just called design patterns even though no one ever calls it that well it does have like a subtitle
Starting point is 01:27:42 right the elements of reusable object oriented yeah but the main time it just flies right out Well, it does have like a subtitle, right? The elements are reasonable, object-oriented. Yeah, but the main title. It just flies right out of your head. Jeez. Did you hear something? It's like a frog. I don't know what that was. That's going to haunt me.
Starting point is 01:27:57 I might not be able to sleep tonight. I don't know if the mics can pick that depth up. Wow. That was creepy. All right. wow it's creepy that was creepy all right so um you know some other links that we'll be including in there there's a on the misty insight there was a great uh article about exploring the factory design pattern um there was a really good read as i mentioned um johnet's book, he has the C-sharp in-depth. It's currently on the third edition. It's a Manning publication. We'll include that as well.
Starting point is 01:28:31 There's just an in-general article on the MSDN site that's just design patterns in the.NET framework in general. It's also another great read. We'll include that one as well. I'm afraid for this next one. Yeah, and then there's the Design Patterns Library, and it's a ton of content up on Pluralsight. Unbelievable. It's like 15 hours, right?
Starting point is 01:28:57 Who is that guy? That's not the same guy that we were talking to earlier tonight, right? Yeah, you know what? I didn't even mention that. I actually spoke over a lot of Alan's talking points earlier because of his voice and so anything that i said that didn't make sense it was just plain wrong fair enough yeah i was really just covering for alan so okay yeah um so yeah there's i think he was right there's like 15 hours of material on those yeah that that's definitely a long one and it's a long list of big names too you know people uh
Starting point is 01:29:24 like donna belchum and glenn block and you know names we've heard before of course scott allen so you know these are these are big guys these are the smarties yeah there's uh over you know 11 authors for that uh that that one um plural site uh episode yeah that's just like that one series, right? Yeah. Yeah. And they keep adding to it. Yep. Okay, so with that, let's get into the tips of the week. So Lee Englestone wrote a blog entry on his site, manchesterdeveloper.com,
Starting point is 01:29:59 and you can find him on Twitter, at Lee Englestone. And I know I've used this feature before within visual studio. I don't know if you guys have, but what's really nice about this feature is that if you, you don't necessarily want to create a break point, but you want to create some kind of a bookmark to go back and find it. Right. So there is a bookmark feature within, um, visual studio and, uh, you can use, uh, you know, can use the little menu items up at the top or the keyboard shortcuts. So like, for example, Control plus B and then T to toggle the bookmark on and off. And then there are additional either icons or keystrokes that you can use
Starting point is 01:30:42 to toggle back and forth between the different bookmarks. Or you can use the, there's a bookmarks window if you turn on, you know, you go through your view options and turn on the other windows, there's a bookmark ones. And you can see all your bookmark references all at one time. But it's just a great way of giving yourself a little placeholder for a piece of code that you might want to inspect or be interested in but you don't necessarily want to create breakpoints and i know in the past i've definitely used uh breakpoints for more than their intended purpose oh yeah i do that with undo yeah i just feel bad but so just to make sure um these bookmarks do
Starting point is 01:31:24 what i think they do right i bookmark like a line in the file then i go along my merry way and i can say oh nope go back to where i was a few minutes ago right um that's absolutely right yeah you can you can go you can cycle between the bookmarks okay so so think of this as you know just like you would in um like on like on a kindle book right where if you wanted to scroll between them, but instead of pages, you're looking at lines of code. Gotcha. So it's a nice little feature in there. Yep.
Starting point is 01:31:55 And like I said, we'll include a link to Lee's blog article as well. All right. So my tip of the week, if I can can get this out i don't think you can yeah i'm you got a bet money on it i'm fading uh so there's a debugging object initializers wow so if you've ever had a problem this is comical now if you've ever i want to make him talk about more stuff i i won't make it much longer if you've ever i want to make him talk about more stuff i i won't make it much longer if you've ever been trying to debug uh properties of an object as you create it a lot of times you'll notice as you like try to f11 into it it'll just step over the entire object
Starting point is 01:32:38 initialization which can be insanely frustrating there is actually an option to where you can go into the Visual Studio settings and you can turn on Object Initializer. Oh, yes, thank you. If you go into Debugging General, then there is a Step Over properties and operations and operators, I'm sorry. And if you actually click that, it doesn't make sense. But the step over properties and operators, when you click that, it actually allows you to step through it. It sounds like it would skip over it, but that's not right.
Starting point is 01:33:20 Check the box, and it will allow you to do it line by line by F11. Yep, and if you head over to uh the show notes for this episode at you know what though cuttingblocks.net slash episode 11 or slash episode 10 we actually gave this one last week as well but we thought it sounded familiar awesome the good news is we've got a really nice shortcut i mean a screenshot and you're not going to forget this one. Beautiful. Well, I feel like maybe we should make him talk about something else.
Starting point is 01:33:49 I get it. Yeah, pony up, Alan. F3. Control F. There you go. Hold on a second. So there's a quick one. If you find a keyword in your file and you want to search for it, click on the keyword, hit Control-F3,
Starting point is 01:34:07 and instead of having to actually do Control-F and then type it in the word, it will actually go find that word where it follows next on the page. So Control-F3, my quick tip of the week, and I'm done. Let's play about this. As much as we talk about best practices, this is clearly a copy-paste error. Busted. My tip of the week was I've been reading Clean Code, awesome book. And one of the tips I just got out of there was it actually recommended using static methods instead of constructor overloads.
Starting point is 01:34:38 And so what that means is if I, say, have a color class, right, and one of the ways I can do that is new color parentheses and pass say hex values right and so I can create the color red from a string then you know okay that's cool that's normal but what's even better is to have a static method on that class called say from hex that can take in that same string and return the same um same new object but now it's much more descriptive so rather than me having this kind of constructor that you've got a f12 to and see if it means what you think it means now we've got a nice you know named method that does you know it just tells you flat out what it does so i thought that was a cool little life hacker tip oh so in your static method then you're saying
Starting point is 01:35:25 return new color with that hex. Yeah so it's basically the same thing as having a constructor overload it's just more descriptive. So you don't have to rely on these stupid summary tags in your code you can just have the method name be the actual description of what it's doing.
Starting point is 01:35:43 So with that, we will be putting the show notes and links, or putting the show notes and the show notes, we'll be putting the links and the show notes and things that we've talked about. And as we've asked before, please subscribe to us on iTunes and Stitcher and be sure to give us a rating or review using your favorite podcasting app.
Starting point is 01:36:05 Yep, and subscribe to us on iTunes, Stitcher, a rating or review using your favorite podcasting app. Yep. And subscribe to us on iTunes, Stitcher and more using your favorite podcasting app. Wait, did I just say that? I think we're all getting a little tired. So Alan might've got us all sick. All right.
Starting point is 01:36:18 How about, how about I'll wrap this up. I'll say that, you know, be sure to visit us at coding box.net where you can find our show notes, examples, discussions, and more. And contact us with a question or topic. Leave your name, preferred method of shout-out, whether it's your website or Twitter, whatever you want us to promote. And we'll mention you on the podcast, especially if you give us a review.
Starting point is 01:36:41 And make sure you send any sort of feedback, questions, or anything like that, rants, funny cat pictures to comments at codingblocks.net and make sure you follow us on Twitter at Coding Blocks. Bye. Bye. Beautiful

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