TypeScript Factory Patterns (No BS TS Series 2 Episode 1)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
no bsts is back with series two it's an all-new series in series one we covered the basics of typescript and in series two we are going to look at every single design pattern in the original gang of four design patterns book and why because i get asked about design patterns a lot and there's a really good reason for that data structures algorithms and design patterns are the three fundamental things that you need to know that are absolutely perennial languages come and go frameworks come and go but design patterns stay relatively the same now we're going to take a look at all of the design patterns in that book and more and because it's typescript we are going to do both the object oriented version of them as well as the functional programming version of them so it's really cool i think you're going to be really excited by this series i certainly am but before we get into it i am super excited to announce the release of no bsts the book for 34.99 you can have the book that accompanies the series it's over 200 pages and i've covered every single episode and more including this episode in fact every single time a new no bsts video comes out it's gonna have a corresponding chapter in the book and you are going to get an update it's really exciting stuff it's basically a subscription to the series i'm super excited about it not only does it have all of the code and the descriptions everything that's been in the series but it also has behind the scenes stuff how to do these videos it's just really a fun book and a fun read i think it is of course the link to where you can buy the book is in the description down below so what are we covering in this week's video we're covering three different design patterns all of these are factories the abstract factory pattern the builder pattern and the factory method pattern and they're all meant to loosen the coupling between the code that decides whether an object should be created from the code that actually does the object creation which makes your code that much more reusable and reusability is an important key factor to almost all of the design patterns so let's jump right into the abstract factory pattern okay so our example of an abstract factory pattern is a logger so in this case we have our client which could be an app or anything like that we have a factory called the logger factory that we then call a method on and it will decide for us whether we're in production mode or development mode to give us the either production logger or the development logger pretty simple stuff but it does allow you to loosen that coupling between the client code and the logger code so you don't have to put that logic of whether you're in development mode or in production mode all over your code base you just call the logger factory and it gives you the appropriate one okay so this is our project we have our three directories here one for the abstract factory one for the builder and one for the factory method so let's go into the abstract factory and we're first going to initialize our project and i'm going to add typescript and ts node and then after that i'm just going to initialize typescript so let me get rid of the terminal and then i'm going to create a factory class ts file and i'm going to specify an interface for the logger now that's going to have all the basic logging methods so info warn debug and we also want error and i'm going to implement this in two different ways i'm going to implement a production logger which implements ilogger and what i'll do in this case is just copy and paste all these and then put in stubs and for production logger all you really want are the warnings and errors so in this case i'll do console.warn and then give the message and then also console.error but our development logger is going to do all of them okay so now we've got our basic logger is down now we need to go and create the factory so let's create a new class called logger factory and then i'm going to use the github copilot code as a good starting point for this but in this case i don't want to pass in the environment i want that to come from the environment variable so i'm going to say process dot env and then node end and so if we're in production mode then we return the production logger otherwise you return the development logger so i'm getting some grief here from typescript that it doesn't know what process is so let me go back over to the terminal and add the types for node in development mode and the last thing i need to do is just export this so let's go try it out i'm going to go create a factory class test.ts and from there we're going to import the logger factory from factory class and i will use it to create a logger and then i'll do some login let's see debug let's just say that's a debug message and then warn info and error now if we go back to the implementation we can see that the default here is we want the development logger so we should expect that when we run this we're just going to get all of those messages so let's try that out and see and yeah we get all of them and now if we change the environment so we say node and equals production what do we get we just get the warning and the error it's just like that but here's a great thing though from this factory class test perspective i don't have to worry about any of that i just get the logger and then it does gives me back the appropriate one based on the environment easy peasy so i mentioned at the start of this i'm going to give you the functional variant as well as the objectorial variant of each one of these so let's go build the function variable of our factory class i'm going to go copy all this and create a new file called factory functions ts the interface remains the same for sure and this one the production logger just becomes a function that returns an eye logger and there you go and in here we have the development logger again it's a function that returns an ilogger looking good so far and then we'll rebuild logger factory as a function called create logger and all we need to do is just call production logger or development logger okay looking pretty good let's uh now go and use it so i'll copy this and we'll call this factory functions test.ts and so we'll change the import to be factory functions and this would be create logger and that's it so let's try it again with our factory functions i'm going to do mpx ts node and then factory functions test and again we expect that all four come out and they indeed do so let's try it again with node and equals production and we just get the warning error messages how cool is that so exactly the same pattern implemented both in oop and also in functional style okay so the next one we're going to take a look at is the builder pattern and i'm going to use a different scenario for this we are going to scrape a directory full of files and we're going to see if the file is a json file then we'll parse it using json and if it's a text file then we'll just bring it in as a piece of text so with the builder pattern the app first creates an object that has some methods on it and so in this case that's going to be like is a json file parse json file and parse text file and then it gives that to the generic scraper as the implementation of its guts essentially so the directory scraper its job is to just go and scrape through that directory but then when it comes to actually creating the objects from those files it gives that responsibility over to the methods that are in that builder so it makes that directory scraper that much more generic and in fact maybe even the scraper methods are also generic and they can be used in other contexts so and again a very nice pattern so let's go build it okay so the first thing i need to do is close up a bunch of these and we're gonna take a look at our builder directory which has already the typescript setup and i'm gonna go in there and create a new folder called data and that's gonna have in it two files it's gonna have a json file dot json say you know some value is true really doesn't matter and then we're going to have a text file say avengers is cool okay so now we've got our data and i'm going to create a new file called dur scraper class dot ts and in there i'm going to create an interface for file reader and its job is to say are you a json file and given a file it's going to say yes or no and in the case of a text file i'm going to say read text give it the file name and it's going to return a string and then it's also going to have a read json which just returns really unknown you don't know what's in the json that's fine so now we're going to create our directory scraper and it's going to use one of these file readers to process the files that it finds it's going to have a constructor that takes a path and then it's going to have that reader which is a type of ifile reader and then it's going to have a scan files function that scans through all those files so we'll start off by returning fs reader sync actually yeah thank you github copilot that's awesome and then we're going to reduce and the output of this reducer is going to be a record it goes from a string to an unknown and we're going to start off with that file and also an empty object at this point we're going to say is this a json file or not so we're going to call that file reader and we're going to say are you a json file and if we are then we are going to call that file your rejson and if not then we're going to do the read text file and at the end we are going to return the new accumulator now we need to import fs all right so because typescript is set a little strict i'm going to go and copy this as the type for the accumulator and also say that the file is a type of string and the one last thing i need to do is make sure that i get the pathing right so add on here the door path and then also the file name okay cool so let's go and implement our file reader and then in read text i'm going to read the file as text and in read json take that same file and basically just do exactly the same thing except run through json.parse all right so we've implemented now our file reader and now we're going to essentially merge these two things together so we want to create a file reader and we also want to create a directory scraper we want to give it the directory where the data is and we also want to give it the file reader that we just created and then we want to get the output of that from the scan files and then see what it looks like in the console i'm going to run ts node on that file and we can see that we had a json file that gives us some value as true and a text file that has avengers is cool so here's the really cool part about this directory scraper is now loosely coupled to the file reader and we can reuse both of these things if we had a different type of parsing that we wanted to do on these files this directory scraper could be used to implement that and if we wanted to we could also reuse the file reader in a different context to actually go and read different types of files it's actually really nice and loosely coupled between these two things okay so let's go build a functional version of this i'm now going to go and create a new file called dur scraper functions dot ts i'll keep the interface the same and then i'll start by making a directory scraper function here that's going to take the der path and the file reader and that's really just going to be scan files and there's no this so we just got to get rid of a bunch of that and there's no public let's get rid of that all right looking pretty good so now let's implement the file reader so we'll call this file reader and it's of a type ifile reader and we'll just add some commas but of course get rid of the file reader that we had down here and we're just going to call directory scraper and give it our arguments file reader and data okay let's give it a go nice and of course all of this code is available to you in github and you can keep trying it out for yourself all right let's try one more design pattern to loosely couple in this case our directory scraper so we're going to use exactly the same example in both the builder and also the factory method so in the factory method pattern the app is going to instantiate directory scraper which is going to descend from the abstract directory scraper and that abstract directory scraper is going to have the logic of iterating through the directory and then the directory scraper is going to have the concrete methods for is json parse text and parse json and the great thing about this particular pattern is in this case the app doesn't need to know that these two things are disconnected it can just directly instantiate directory scraper and get the implementation that it wants all right let me close out a few files here and i'm just going to copy the data in the factory method because it'd be the same data in both cases now because these two are so closely related i'm actually going to copy the implementation from here into dura scraper class within factory method and then i'll go into the factory method directory and here i'm going to add types node that gives us access to that fs and i'm going to take these methods from ifilereader and put them in just a scraper and call them abstract and i'm going to say that the directory scraper class itself is abstract since it cannot be instantiated as is but of course we don't need a file reader since we are in a sense the file reader when those abstract methods are actually implemented so let me go and remove file reader and in this case we just want to call this because we have that as part of our implementation so now the file reader extends directory scraper and implements those missing methods and down here all we need to do is instantiate file reader as opposed to directory scraper and then we just give it our directory path and we can get rid of file reader because we are a file reader and let's see how we're doing there you go but again we get that really nice loose coupling between the logic of the directory scraper and the implementation around whether a file is a json file or not or how to parse the files that it gets so you could have multiple versions of a directory scraper that scrape the directory in different ways all right let's go try out the functional version of this i'm going to copy this one and create dir scraper functions and i'm going to keep around file reader in this case and we're going to create a new thing called create directory scraper and it's going to just take a file reader and it's going to be a functor it's actually going to return a function and that function is going to be the directory scraper so we will return a function which takes a directory path we'll call it dur path just be easy and it in turn then does that fs redirsync and all that so now we need to actually instantiate one of these things i'm going to create a new value called dur scraper and then use that create directory scraper with file reader and now that dura scraper just takes the directory because it already has the file reader which we gave it when we created it all right let's give it a try not bad pretty cool okay so again we've abstracted away the implementation of the directory scraping or the directory iteration from the mechanics of how we want to actually parse the files we found when we did that directory scraping and that's a really good way to loosen the coupling between these two things all right well i hope that helps you understand these three design patterns the abstract factory pattern the builder pattern and the factory method pattern and how you can use those to disentangle the logic that decides whether you want to create an object from the code that actually goes and creates the object of course i'd love to hear from you and your ideas about these patterns or this series in the comment section down below feel free to grab no bsts the book on sale right now the link is in the description down below if you like this video be sure to hit that like button if you really liked the video be sure to hit the subscribe button and click on that bell and you'll be notified the next time a new blue collar coder no bsts series 2 video comes out so exciting not a bad start all right onward and upward
Info
Channel: Jack Herrington
Views: 2,468
Rating: 4.984375 out of 5
Keywords: typescript, design patterns, software engineering, best practice, object oriented, design patterns in typescript, typescript tutorial, typescript design patterns, design pattern, typescript crash course, typescript factory patterns, factory patterns in typescript, no bs ts series 2, abstract factory pattern typescript, GoF design patterns
Id: -1YhP5IOBCI
Channel Id: undefined
Length: 22min 6sec (1326 seconds)
Published: Mon Sep 20 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.