Technology

Object Oriented vs Functional Programming with TypeScript


Which is better object-oriented or functional programming how about composition or inheritance semicolons or no semicolons is it pronounced Jif or gif and is a hot dog of sandwich today you’ll get all the answers and I encourage you to just accept these as the facts and not try

Out anything on your own there’s only one correct way to write code and if there’s one thing that employers hate it’s creative problem-solving skills from their programmers if you’re new here like and subscribe and congrats to Alexander Torres here the random t-shirt winner from last week and a huge thank

You to Patrick Neal Lou he contributed to the content of this video and has helped out hundreds if not thousands of developers on our slack Channel so make sure to spam him with a thank you message let’s go ahead and take care of the easy ones first when

Writing your code you should leave some Mikael arms out and then have prettier add them back when you save the file gif stands for graphics interchange format so it’s obviously pronounced gift following the first word in the acronym itself is a hot dog sandwich well that one’s a little more complex so let’s

Wait till the end of the video how about object-oriented versus functional programming if you guessed object-oriented is better you’re completely wrong and if you guessed functional programming you’re way off base debating programming paradigms at this level is like debating art there is always more than one way to

Solve a problem especially in JavaScript and it’s great to debate these things but there are no absolutes there’s going to be a trade-off for every decision that you make let’s start by taking a look at some functional typescript code the most important concept in functional programming is the concept of pure

Functions this means that the output of your function should only depend on its inputs for example here we have a function called two string which takes a value as its argument and then returns that value formatted as a string we can make this an impure function by mutating

The number variable directly this would be considered a side-effect and functional code should produce no side-effects in addition they should not rely on any outside value to produce a return value pure functions are easier to test and also easier to reason about because you don’t have to think about

Anything happening outside of the function itself another core principle of functional programming is immutable data functional code is stateless meaning that when data is created it is never mutated for example we can simulate this in JavaScript by using object freeze on this array of numbers we could hack around this but it

Prevents us from doing things like a right push which you wouldn’t do in a functional program so obviously our data has to change somehow if we have a dynamic software application so you’ll often be passing functions as arguments to other functions so here we have a typical first order function which takes

A value and returns a different value in this case just appending an emoji to a string now a higher-order function is one that either takes a function as an argument or it turns a function itself javascript has some really nice built-in higher-order functions for arrays such

As map so instead of using a for loop we can just pass in our function to map which will run our add emoji function on every element in the array and transform the value so that gives us a very concise and elegant way to transform the

Values in an array another cool thing we can do is create functions that return functions this is very useful when you want to start with some base functionality and then extend it with some dynamic data let’s imagine we’re building a weather app and we need to append strings with certain emojis we’ll

Start with a base function called append emoji and then use it to compose more complex functions so in this case the inner function takes both of the arguments and adds them together we can use this to create more specialized functions that point to a specific emoji for example we’ll have a rain function

And a Sun function then we can call this function with the string that we want the emoji appended to the end result is some concise and readable code that doesn’t rely on any shared state that would make it difficult to test that’s about as basic as it gets for functional

Programming and things get a lot more interesting when you have asynchronous data and side-effects and things like that so now let’s go ahead and compare this to object-oriented programming the best comparison I’ve seen is to a baking recipe I’ll have a link to that in the description the object-oriented or

Imperative approach on the top gives you a clear set of statements to follow to get the cake to its final state the functional or declarative approach on the bottom describes the state and logic involved but has no opinion on the actual control flow now let’s go ahead and look at some object-oriented

Typescript code the first thing we’ll do is define a class which itself doesn’t really do anything but rather it serves as a blue print for instantiating objects so an instance of this emoji class will be an object with an icon property then the constructor method is special because it

Runs once when the object is instantiated will pass an argument to the constructor with the actual emoji icon and then we’ll set that equal to the property on this object and the emoji class works similar to a function but we use the new keyword in front of

It and as you can see when we do that it creates the an emoji object with an icon property of Sun in typescript there’s an easier way to do this because we have the concept of public and private members so if we use the public key word

In front of the argument in the constructor typescript will automatically know to set that as a public property on each object when you declare a property or method public it means it’s available to the class itself and any instances of the class that can be both a good and a bad thing for

Example we can simply change the icon by just mutating the value on its object on one hand it’s very convenient but on the other hand if you have a lot of code doing this it can be hard to keep track of and hard to test effectively I’d like

To point out at this point that classes in JavaScript are actually just syntactic sugar for functions and prototype one heritance if we can pile our code to yes three you can see that it’s just a function with a closure that prevents the local variables from bleeding out into the

Global scope that’s just something to be aware of but typescript also provides some tools for us to improve the tone that we have when writing object-oriented code for example we can mark members as private so that they can only be used inside of this class definition this means that we can

Separate our public API from internal logic for this class for example if we want to make this icon value and mutable we can make it private and we’ll define a getter so the user can read the value but not change the value another important thing to point out here is

That class instances can have their own internal state let’s imagine we have a button where the user can toggle the emoji and maybe go back and forth between different states this is a really simple thing to implement an object-oriented programming will add another private property to this class

Called previous and then use a getter to retrieve that value then we’ll define a change method which will mutate the actual icon value on this instance when that happens we’ll first change the previous value to the current icon and then update the current icon to the new

Value on the first console log we get the Sun icon and undefined and if we mutate the state a couple times you can see that our internal values on this class instance have changed so the end result is that we have a class that’s encapsulated all the logic for how an

Emoji should work and with typescript we automatically have an interface and documentation for this class another cool thing you can do with classes is define static methods the unique thing about a static method is that it’s on the class itself and not an instance of a class so we’ll just go ahead and

Define a static method here which itself is actually a pure function and its job is simply to add one to the input argument the cool thing is that we can now use the Emoji class as a namespace to run this function now we’re going to switch gears and talk about composition

Versus inheritance for code reusability this is an area where people tend to get very strong opinions and the actual definition of composition tends to be a little convoluted but the whole thing really just boils down to this with inheritance you start with a larger base class then have child classes inherit

All of this functionality and override or extend it with whatever custom behaviors that they need composition on the other hand breaks apart the interfaces and logic into a lot of small pieces then builds up larger functions or objects by combining these pieces together let’s go ahead and take a look

At an example of inheritance we start with the class of human that has a public property of name and has the ability to say hi but what if we have a lot of other objects in our program that are similar but implement slightly different features based on what they’re

Designed to do for example in a video game you might have a human character and then a super human character that has all the human abilities but with a little something extra in typescript we can simply inherit all the functionality from the human class by saying super

Human extends human we do have an argument in the constructor so we’ll also need to add that to the constructor without private or public then we call super which will execute the code in the constructor of the parent class which in our case is just initializing this name

Property at this point we’ll go ahead and define an additional method called super power then we’ll create an instance of the super human class and what you’ll see here is that it has this or power method whereas the regular human does not but the superhuman can still call all the methods that were

Defined in the parent class inheritance can be great in the right situation but you want to avoid creating really deeply nested classes because it becomes very hard to debug when things go wrong somewhere in the middle as an alternative we can use composition and there are actually multiple different

Ways we can apply this pattern in angular we can do it by injecting services into our components and also at the template level by creating directives I’m not going to cover that here but it’s just one of the awesome things about angular that I’ve covered in many other videos another alternative

Is to concatenate objects together which I’ve seen covered in several different articles on the web the idea here is that you decouple your properties or behaviors into objects or functions that return objects we can then merge all these objects together into a final function that does everything that we

Need it to this is usually referred to as a mixin pattern and it’s just a certain type of multiple inheritance so the terminology between composition and inheritance is sort of convoluted in any case this mixin pattern can be very powerful but in its current form we lose all of the ergonomics of class-based

Object-oriented programming that might be a good or bad thing depending on who you ask but typescript actually gives us the flexibility to use mix-ins in a class-based format first I’m going to pull in this really ugly function from the typescript Docs which we’ll see in

Use here in just a minute from there I’m going to create a couple of small behavior classes that define the individual behaviors instead of trying to encapsulate everything in a single class so these classes are more concerned with what something does instead of what something is now in the

Superhero class there’s a very subtle difference from the previous example instead of extending the class we are going to implement multiple classes when you implement something you’re only concerned about its interface and not its underlying code it’s the apply mix-ins function that we defined at the very beginning that will actually take

These interfaces and apply their code to this class that does leave us with some extra boilerplate code where we have to actually type the return values on the methods for this class in this case we have two methods say hi and super power both of which return strings and the

Final step is the requirement to call that apply mix-ins function with the base classes the first and the mixed in classes as the second argument now we can finally answer the question is a hot dog a sandwich if you use inheritance then you’re going to have to inherit from some base sandwich

Class which means it is a sandwich but if you use composition then you can just pull in the hot dog in the bun meaning that it is not a sandwich I’m gonna go ahead and wrap things up there if this video helped you please like and

Subscribe and I just want to say thank you to everybody for an amazing 2018 I’m super grateful for the community around this channel and I look forward to pushing things even further in 2019 I’m going to be taking a short break for the next couple of weeks and then I have a

Video plan for January 1st so stay tuned for that I hope everybody has an awesome end of the year and you can still find me on slack if you have any questions or need anything at all thanks for watching and I’ll talk to you soon

#Object #Oriented #Functional #Programming #TypeScript
For More Interesting Article Visit : https://mycyberbase.com/

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *