Purifying Typescript - Timothy Clifford

Purifying Typescript - Timothy Clifford

Show Video

I'm here today to talk to you about purifying. Typescript. But. Before we start a little intro about myself so. As. I said my name is Tim I am, an engineering, lead at BC gdv. As. Reg said I'm originally, from Australia, currently living in Berlin, at the moment, and. So the reason I decided to, to kind of give this talk is we. We use a lot of functional programming languages. At, BC, gdb but I've. Never actually used it in, conjunction with typescript, so, the. Initial thinking was is. This, a good idea how how, easy is it does it work well is, it worthwhile. So. What are we trying to get out of today so, we're trying to understand, how. To apply functional. Programming, techniques, with typescript. So. What. That means is rather, than doing a deep dive into some. Of the more. Academic. Or highly, mathematical parts. Of functional, programming I want to talk more, on practical, terms so give you some hard, examples. That you can take away and then start using tomorrow and. So how are we going to achieve this mission. Here's. Our agenda we're. Going to start with a short. Overview of functional, programming so, then we're going to talk a little bit about typescript, and why. It's useful what we should do with it then. We're going to get right, into some code and look at some. Examples. Of functional. Programming with, typescript we'll, finish off with a summary of what, works what doesn't and. Then last of all we'll talk about our next steps so if any of this is interesting to you and you want to learn more where. Can you take this next. All. Right so. Functional. Programming quick show of hands who has, attempted. Some form of functional, programming before, and. Cool. That's good and hands. Up if you're using functional, programming everyday, in your in your day job yeah. A few hands nice nice, alright. So. Let's. Get started. This. Is a little bit of a tongue-in-cheek. Diagram. But it's basically showing you that if you're coming from the, parrot of object-oriented. World you're. Used to learning all of these patterns all, of these principles. In. Functional, programming it's it's, slightly, oversimplified. Here but you're essentially, working with functions. So you're breaking everything, up into these small, reusable, functions.

So. It's a change in mindset. Functional. What, so. We talk about functional programming we, also talk about functional languages, so it's, good to make a distinction, before, we start so if, you, look on the internet if you google what is functional. Programming you will see, a million, different definitions, and it really depends on what. Type of languages, people are using what, their backgrounds, are if they're really mathematical. Backgrounds they'll have a different interpretation. As, to someone who's a more practical finger but, one of the better definitions. I have found is that, functional. Programming is building, software by composing, pure, functions. Avoiding. Shared, state mutable. Data and, side-effects so. Functions. A good changing. State and data, bad, and what. Functional languages are. Enabling. Or enforcing, the principles, of functional programming so. The. Stricter, a language. Is in. Enforcing, these principles, then typically. It's considered, more functional, or more pure so we'll talk a little bit about what pure, functional, languages are a bit, later. So. Where does functional programming come from. It. Draws. A lot from the. Lambda calculus which, has been around since the 1920s 1930s. Does. Anyone know who this young. Man with an amazing beard, is. No. So this is this is John McCarthy, and if, you do one thing after this talk you should all go and look. At who this man is and some, of the achievements. He had in his life so he's influenced, people like Steve. Jobs a. Lot. Of the Apple guys but. He's really interesting so in 1960. He, came up with a. Programming. Language called Lisp and this. Is considered the first. First. Functional, programming language. And, a lot of the languages that we see today for example closure, these. Are also considered. Building. Upon this Lisp idea so it's Lisp is actually, standing for list programming. So, since, the 1960's, we've had a plethora. Of. New. Functional. Languages we've. Also had in the last couple of years a lot of buzz around. Functional, programming in general so we've. Got a million different blog posts telling you that you, should learn one thing this year and that's functional, programming we've got. Thousands. Of different people telling you or, trying to explain to you what, what's a monad how does a monad work and. We've, got all these sort of heated debates about. Object-oriented. Is better no functional, programming is better, there's. So, there's a lot of discussion, and if, you, basically, forget, all the buzz don't.

Worry About all the all the arguments. Keeping. In mind that functional, programming still brings you a lot of benefits that you can still just. Start using and and get those benefits straight away. So. What are some of those concepts, and that. Bring those benefits so. These are just a few. So. First off we have, the. Concept of first-class. Functions. So. This is this. Means this this language must treat its functions, as first-class. And. What that means is that functions, can be passed as arguments. To other functions it, also means that functions can, be returned, by, other functions so we have have a look here we've got one. Example, function. As arguments. We're basically passing that in, and. Executing. Then the other one is creating. A function within its own scope and returning that as. You can see many, of you who write JavaScript, will see that, JavaScript. Does actually support first-class, functions. What. Else have we got pure. Functions, so, pure. Functions. Means. You, cannot cause, any side effects all of the change must be encapsulated within, your function, you. Cannot share any of your state. And. That given the same input and the same output. Your. Function will always return, the same value so. This is really useful for for. Doing things like lazy evaluation that, sort of thing so and then I've just got a small, little Haskell comic. There because everyone loves Haskell. Alright, a mutability. Hopefully. Everyone here knows about immutable. Objects but, for. Those of you who don't. Basically. It's constants everywhere so once. Once. You create an object you. Can't change its value again, that's it and. Recursion. So. Functional. Programming doesn't have any loops has no for loops it uses, recursion, so that means you're working with these higher-order. Functions. Like map, filter. So. A lot of you're probably already doing some, functional. Programming in some some, sort by using these these, higher-order functions, today, and. Currying. So. Carrying kering is another, interesting concept so this is basically taking a function. Which has many. Arguments, and you, carry this and then, what you're given is a sequence. Of functions. Each. With one argument so this this, allows you to create. Customized. Functions without having to the define them so it's, still a little bit abstract I've got a an example, coming on later that. Hopefully explains. This in a bit more detail and. Pattern. Matching so. Pattern. Matching is a mechanism for checking, a value against a certain pattern so think, of it as a switch. Statement on steroids, so you. Can see here the the switch. Statement on the right and match pattern, matching on the left it cleans, it up so this is a fairly trivial example, some of the some. Of the more, interesting.

Things, You can do with patent matching you're also worth. Looking at. So. What benefits do these bring. The. First one clean code so, you're working at a higher level of a distraction so that means you're going to have less boilerplate. Code you're, going to have no class hierarchies. So it should be easier, to read and. Easy to work with and because. You're breaking your code into these smaller sort. Of self-contained functions, it's, easier to kind of. Follow. What's going on have. A more more, understandable, code base, second. To that we, are working with more. And more complex systems as we go so. For. Example we're, dealing with a lot more concurrency, we're dealing with a lot more parallel. Processing. So not. Sharing states using, immutable, objects this, really helps when you're when you're working with a lot of concurrency, at the same time we, have these distributed, systems and these, are really difficult to reason, about so if we're if we're saying that we can't change state. And. We have these small, reusable. Functions. Then it's kind of breaking these big complex problems, up into smaller more. Manageable pieces, and. Testing. So. Testing is another good one so. Think. About if, you've, got these. Small again. Self-contained, functions, we, have no external, dependencies, no. Side effects so. That, basically means only thing you have to test is happening inside, this function so you're not mocking anything, you're not stabbing anything, it makes, your testing much easier, much simpler. Next. One typescript. So. Typescript, is a typed, superset, of JavaScript which. Compiles, to JavaScript and. What. Benefits. Does that bring. You. Get things like, compile. Time error checking through, using types you. Get safer refactoring, especially, when you're working with sort of larger code bases it's it's easier and safer to refactor you. Get, documentation. Through, your types so you can more easily see what. Does this function expect, as a parameter and what what's. It going to return me as, well. As that you get, we. Got optional typing so. Typescript. Uses or has the concept of type inference so you, don't actually have to. Define. All of your all your arguments as types it will it's clever, enough to infer. What these are and lastly. Job it's a JavaScript superset, which means you can actually write. Javascript. Inside. Your typescript, if you wanted to whether. Or not that's a good idea is another, another, argument but and. Down the bottom here we just have an, interesting. Talk from Gary. Bernhard who who gave a really sort, of quick demo about some. Of the interesting behavior that you see or when. Working with JavaScript and trying to infer, what types are. So. This is Anna's house Berg he's. The creator of typescript, and this. Is a quote he gave about types. In general and I think this kind of shows that the. Approach. That typescript, takes when working. With types so. It. Does it does give you benefits but at the same time you lose a bit of the the flexibility, of JavaScript, so it's important, not to force, people to be too strict, but at the same time having that little, bit of safety there gives you gives you some nice benefits. All. Right so, we've. Talked about, functional. Programming we've talked about. Typescript. How. Do we go in combining, those together so we're going to a quick, code. Demo with a few examples. All. Right, so, first. Off we have two functions is, that big enough for everyone. Yeah. Okay so we've got up the top we have an untied, function, down. The bottom we, have a type function, the. Only difference, as you will see is the second function we are Anna type annotating. What. Our arguments, are so we're saying name should be a string and would, like sugar should be a balloon and it's going to return us a string, we're, not using any annotation. In the untyped version so we. Execute, those in, the same way the. Benefit, comes if for, example somebody tries to call. The. Untyped version and instead of us a name. They give a number there's no kind of warning, there's no nothing, nothing. Stated, to the user they think that's okay and. If, we try and do that with the typed.

Version You'll see we get this little, read, compile time era which is basically saying you, can't assign a number. To a string so this this is kind of the just scratching the surface of the benefits of typescript brings you the. Next one recursion, so. We. Have some. Simple symbol. Objects here we've got a customer, type which has a name and a, list of beverages at that customer lacs we've also got an array of these customers, so then we're creating, a function and we're, going to get the the name of all the, customers, who enjoy drinking coffee so we. Can see if we did this in a iterative. Way so using, loops we've. Got a lot of nesting, it's. Pretty, difficult to find out what's going on here, and. We've got a lot of cyclic, complexity, if we try and do this instead. With. Recursion so we've broken it up into these three separate. Functions, the, first one is basically. Calling filter, and maps so it's grabbing these customers, first, it's filtering, them using this is coffee drinkers function and then. It's mapping them just to get the customer name so, the. Benefits, with this is for. Me reading this it's a lock Sarah I, can test each of those individually. And it's. Just nice occurred in general if, we look at the. Next one immutability. So. Typescript. Has some inbuilt. Immutable. Objects being the read-only. So. We can make our customer read-only so. This this type, will then make, the name and the beverages, both. Read-only. And, then we can look at the read-only, array, and, this also makes a or. Provides us with a read-only array, which we can't once we've created that array we, can't add any more objects to it it's, basically, locked and immutable so we, can see down the bottom here if we try and grab. One. Of our customers, and change his, name to Bob that's. Not going to happen that's that's being prevented, and if we try and push a new customer, into this array we're.

Also Getting prevented, there, all. Right our next one, function. Composition, so. Function. Composition, is the. Combination. Of two. Or more functions to provide, you with a new function so if. We look at these three, in. This example we're working with a bank, balance and we want to basically. Transform, that so we're adding some. Celery we're subtracting some, fees and we're subtracting some, bills so if, we did this in a, kind, of traditional, way we can have. Our update, bank balance function which takes a balance. Passes. It to each of these functions individually it gets back the result and assigns it so this is this is doing some sort of bad. No-no, things in terms of functional programming it's it's sharing state it's mutating, objects. And. It's, just. Generally. Messy so, we. Can also do this in. Here. In subtract, bills we can get. Rid of this state mutation. We. Can get rid of this State mutation, by nesting. Our functions. But. I think everyone would agree here that that's that's, not readable, code it's very difficult to understand what exactly is going you know going on, in this code so instead, we. Are using a. Library. Here we're using a functional library it's called lambda, if, you look at our imports, so. What this gives us is a pipe, function, so we can pipe our. Data, through. These three separate. Functions. So we basically are given. This update, bank balance composed, and that. Accepts. Our data passes. It one by one through these functions, and then returns. Us the results so there's no sharing, of state we, get this nice smooth data pipeline, that we can then work with so if, I wanted to for. Example add, another, function into that it would be super, easy and super clean. All. Right the next one curring so as, promised. We. Have a. Function. Here it's still working with bank balances, so, we have three. Arguments. The, current balance the celery and the fees and. What. We want to do is curry this function so, if we look again we're using Ram de, so. What does carrying a let us do it's transforming. A function, with. Many arguments into a sequence of functions each with one argument so, first. Off what do we do we curry our, original, function here that gives. Us back a curried, function and so, this expects, our arguments, to be passed in one at a time and each step, of the process is going to give us back another. Function which is expecting, the, remaining, arguments so if we look at the. First one update bank-balance curried, we're giving it the the.

Current Balance that. Will give us back a function which still expects two of our arguments, we call that with. The the celery and then. The last one we call it with the fee so this this gives us flexibility. And when we provide, our arguments, it also, lets us we could, we. Can essentially pass these these, extra, functions off to other parts of our code and use them there it makes everything a lot more reusable and, flexible. The, last one is pattern. Matching. So. I know we said we weren't going to talk about monads. But I lied. As. You, can see here we're using, we're. Using a TS it's called TS monad it's a very simple, types. Grid monad. Library. And. We're, using what's called a maybe monad. So. If you want to really. Really. Simple, probably. Quite incorrect, definition. Of a monad here. It goes so if, you think about values, that you may be working with in, your code these. Values can have problems, or quirks so, maybe, your values null maybe it throws an error. What monads do is try and deal, with these quirks, or problems. By basically. Wrapping these in a container and then giving, you these operations, that you can then provide. Sorry. That you can then perform on these values depending, on what. What. They end up being so in, this case maybe, monad. Allows. You to specify something, that may, or may not be there so it could be a value. Or it could be null or it could be undefined. And. Functional, programming uses. Monads a lot especially when, dealing with, side-effects, so these are things that you don't know, what. The end results going to be so you wrap it in a monad essentially, so if, you're coming from a JavaScript, world. Promises. Are a similar thing to monads in that you you basically don't know what the response, of something is going to be it could be a success, it could be an error so. You wrap it in a prop in a promise so. What. We have here we. Have one one. Function called can withdraw money so that's taking a balance and that's, telling us whether or not this person is allowed to withdraw cash, from. Their account if they if, the balance has a value and if that balance is greater than zero, we. Can then. Say. Yes you can take some money out of your account if. We look at the pattern, matching version so, we. We, call a, sorry. Just. Grab some water. We. Call our function in a similar way, but. Here we're wrapping our balance in. Maybe. And so, what that allows us to do is when when, we unwrap that balance we can match, it against, just. Means yes it does have a value or. Nothing. So nothing means there was no value there and so it's just a nicer. Nicer. API to work with cleaner cleaner, code and again. This is a this is quite a trivial, example but hopefully, illustrates, you how you can then use pattern matching in your code. The, last, little. Thing I wanted to point out if you do decide to kind, of go down the the, typescript. Functional, programming. Path. There's, a, super, useful library, sorry. Super, loose useful, linting. Plugin. For typescript. ES linked immutable, and this.

Gives You a bunch. Of rules you can use for. Ensuring. That things are read-only, ensuring. That you're. Not. Using. Variables. You're, always using constants. You're not mutating, objects. So. This is super helpful if you're just getting started and the second, thing if, you're. New to typescript. There are a lot, of these. Extra. Static type checking options, so if, you, want to make your code. Super. Tight oh, that's. Good. Super. Type safe then you can basically enable. A lot of these too, all. Right and end. Of code. So. A summary, what, what, have we learned what what, works well with typescript and functional programming what doesn't. The. First thing, yeah. If you're new to if, you're new to functional. Programming a lot of this terminology, is. Scary. Monads. Muroids mono. IDEs funk tours category. Theory so you read these you start digging deeper and then you're like oh this is just this is my, mind is blowing it's too much work, my. Advice would be you don't you don't need to know all of these things. Just, get started it helps but, you can definitely get started, and just. Try it so the best way to learn something is to start writing, code start, getting these. Sort. Of concepts. Into your head and then over time these more. More. Difficult things like monads will start making sense and you'll start using them more. Types. Yeah. As we said safety, type safety is nice but. It doesn't come for free so the. More the stricter you make people's lives the. More freedom they kind, of lose so. You're you're trading off between safety, of your, code and dynamic. Ness so to speak, the. Other thing that's worth mentioning if, you're coming to typescript. With. A with a functional, programming mindset, a lot of the sort of JavaScript, libraries that are that are working, with, typescript. Can. Have some interesting, quirks in in, the types that they offer so lambda for example, is one of those. What. Else have we got so. Pure. Functions, easy. To write hard to combine so. Writing. These small self-contained functions, is, kind. Of the easy part the, the more difficult part is composing, these together into. A program. Which runs which. Makes sense which, understand. So this is again this is changing, the mindset from kind, of an imperative, programming. World to more of a declarative, so getting. Those getting. Those changes, and, understanding. What the the, best way to structure something in, a functional. World. Is take some time but yes, stick stick with it it comes after time and. Yes. Side-effects so we're all I, assume. Working with some something. To do with the web so, the web involves, writing, to the console running to files. Databases. All of these things are, considered. Side effects in in, the functional programming space so how.

Do We deal with that. Without. Making our lives an absolute, nightmare and. Yeah. This is this is basically a diagram. Taken from, sort. Of the Scala scholar. Approach. It's. Basically keep all, of your core logic. Your. Core business logic can. Be functional, and then, trying to isolate anything, that's anything, that's having, side effects try and keep that those two separate and then. Managing. Those separately will make your lives a be a bit easier and. Higher. Kind of types so. You, can think of these as generic. Generics. These. Are these are common. In type. Functional, languages like Haskell. And, Scala, and they're, really important if you want to be using things like monads, and ma nodes. Typescript, does not have higher, kind of types yet does not support them. This. Causes a few, issues. Sort. Of following the the pure functional. Programming mindset. There's, a few open discussions, but nothing, is kind of no. No short term solution looks to be on the cards. All. Right so next steps so. If you're yeah. If you're interested in this and you, want to sort, of learn more or dig deeper. How. Do you go about your your functional evolution, so as I've stressed the whole time it's it's a journey it's something that takes a bit of time at this, if you're coming from and, object-oriented, world and you, start writing functional. Code. The. First thing you're going to write is basically. Imperative. Code. In. A functional, style and don't. Be put off like a pure the, pure kind, of functional. Purists. Will will not like your code but didn't stick. With it you'll get you'll get better over time and you will. Make. That evolution. These. Are a few. Typescript. Libraries which are dealing with functional, constructs. So if. You want to dig deeper into the the very academic, the very mathematical. Parts. Of, functional. Typescript this.g, can see the first the first link. Is, an italian guy and, he's been doing a massive. Amount of work trying, to get, functional. Programming into typescript. True. Myth is also an interesting thing to look at then we have some beautiful. Data, structures, and yeah. This pure algebraic. Data types are also, fun. To play with then these are some functional. JavaScript, libraries which have, typescript. Typing so they're supported, in typescript Rambo's is a few of the examples we. Saw already sanctuary. And folktale, are also. Really. Good functional, rivalries, folktale. Is in the middle of kind of converting. Their code base to typescript. Immutable. Jas I'm sure most of you have heard of from Facebook and then if you're coming from like a scholar world or, dealing with futures. Flutter. Is also quite, cool so. Maybe. You want to take it one step further maybe you want to jump out of, typescript. And JavaScript. Completely so these are some, additional. Languages, some functional languages which all compile. To. JavaScript so. Elm Elm. Is. Super. Interesting language has been around for a few years now it's. Heavily influenced, by Haskell. The. Documentation. Is great and the debugging. Experience is also really helpful pure. Script is one of the new kids on the block. And then. We have reason, which is from Facebook and that's writing Oh camel which then compiles, into JavaScript. Idris. Is another, one so if you're interested, in. More. Haskell styled, languages. Which which, compiled with JavaScript this is when I recommend. Scala. Joyous, closure, script. This, is Scala, and closure, script both compiling, to JavaScript. Fable. Is F, sharp and, then. If you really want to go hardcore you can check out gh. CJ, s which is the Haskell. Compiler compiler. To. JavaScript. So. That's it I, hope, you got something out of today if. You want to sort, of chat, and dig deeper into any of this I'll. Be at the BCG. TV booth until the end of the day, but. Yet enjoy the rescue conference. We. Did have some great questions one of which I think was briefly. Sort of alluded, to in a second, last slide, it. Was, what do you think of Flo Jas. Everything. But no. I think it's also a it's, an oh good, alternative, to typescript so they're similar.

Kind. Of goals. I think I haven't, looked at added, in as much depth as I have typescript. But. They're kind of competing, competing. Subjects I know the. So. These higher kind of types that I spoke about which kind of restrict some of the the, functional, myths of a language. The. Flow. Is also dealing, with this and trying to solve that problem as well so they're both kind of in similar, positions all, right now, that that was the easy one the next one I have a feeling. Is one, of these ones, that is better asked, in a pub or other, place where you know anything where people bicker, about things yeah and the question was an opinion one there it's it it's, one that requests, your opinion, okay and. That, is with. Webassembly, going GA what. Webassembly. You know compiled - compiled sort of to the lower and, this. Is going yes yeah, sham use types, or district. Magazine said why not just go direct to haskell and so on and so forth which you, kind of touched on again by talking about a jcj, s yeah what, is your thought about where. This might take functional, programming yeah. It's it's, an interesting question i think. The the. Problem, typescript, has with, trying to approach this. Kind of functional, programming. Paradigm. And being as pure and as functional as possible it. Means, it has to kind of change a lot of its design principles, which is about keeping a little bit of, flexibility. And that dynamic nurse of javascript so. Will. Will, functional, typescript, ever be, something. That is, sort. Of worthwhile I'm not, sure. It. Certainly has its benefits at the moment but. Yeah. There's a lot of other good approaches, as well so if if I was to tomorrow, to start, start. A new project, and wanted to do in a functional style would. I use this. Probably. Depending. On it depends on the the problem you're trying to solve how technically, technical. And and. Meaty it is but there's other good options like elm pure, script are also more. Functional, and more following, the strict, functional. I've, gotta say I personally don't know I I. Could see arguments both ways I know historically. Our. Industry, has tended to favor things that look like whatever we were using five years ago we still have curly braces in a lot of languages, yeah we still have things there's a certain obvious inertia, towards oh this looks familiar so things that look a little like JavaScript probably have an appeal yeah however this.

Is A domain where a more a more pure language and with higher kind of types and other other things deliver. Some benefits so I don't know yeah I would say that this is if you're if you've never written sort of functional. Works. With functional languages before this is kind of a good good. Thing to put your toe in the water see how it is because it's not as strict as something like Haskell, or. Alum. For example so you can kind, of play around with these concepts, without getting, kind of slapped in the back of the head when you do something wrong fantastic. Folks what do you think of his talk. Like, thank you so much.

2018-10-11 23:22

Show Video

Other news