Clean Code - Classes - Beau teaches JavaScript

Setting up Method Chaining in JavaScript Classes

=====================================================

In this article, we'll explore how to set up method chaining in JavaScript classes. We'll start by looking at an example of traditional method chaining and then dive into how method chaining works when returning objects.

Traditional Method Chaining

-------------------------

When creating a function with traditional method chaining, you would typically return the object itself after each method call. This allows for a more flexible way of constructing objects.

For instance, consider this traditional method chaining:

```javascript

function createCar(color, make, model) {

var car = {};

car.color = color;

car.make = make;

car.model = model;

return car;

}

var c = createCar('pink', 'F150', 'model');

```

As you can see, the `createCar` function returns the object itself after each method call. This allows for chaining of method calls.

Method Chaining with Returning Objects

--------------------------------------

However, this approach can lead to issues when trying to chain methods on an undefined object.

```javascript

function createCar(color, make, model) {

var car = {};

car.color = color;

return car;

}

var c = createCar('pink');

c.make = 'F150';

c.model = 'model';

```

In the above example, `make` is not a valid property on an object. This is because `createCar` returns `undefined`, and you cannot call a method on `undefined`.

To fix this issue, we need to change our approach so that we are returning the object itself after each method call.

```javascript

function Car(color, make, model) {

this.color = color;

return this;

}

Car.prototype.make = function(make) {

this.make = make;

return this;

};

Car.prototype.model = function(model) {

this.model = model;

return this;

};

var c = new Car('pink', 'F150', 'model');

```

In the above code, we define a `Car` constructor that returns `this`, which allows us to chain method calls.

```javascript

var c = new Car('pink').make('F150').model();

```

As you can see, this approach is much more flexible and avoids the issue of trying to call methods on an object that has not been initialized.

Composition vs Inheritance

-------------------------

When deciding whether to use composition or inheritance in JavaScript classes, there are some key differences to consider.

Inheritance is like "is a" relationships. For example, if you have a `Human` class and a `Person` class that inherits from `Human`, then `Person` is an instance of `Human`.

Composition is more flexible than inheritance. Composition is used when you want to create an object that has a relationship with another object.

Here's an example of traditional inheritance:

```javascript

function Animal(name) {

this.name = name;

}

Animal.prototype.eat = function() {

console.log('The animal eats.');

};

function Human(name, age) {

this.name = name;

this.age = age;

}

Human.prototype = Object.create(Animal.prototype);

Human.prototype.constructor = Human;

Human.prototype.talk = function() {

console.log('The human talks.');

};

```

In the above example, `Human` is an instance of `Animal`, and therefore can call the `eat()` method.

However, this approach is problematic because if you add a new method to the `Animal` class, you're not sure whether it will be accessible by your `Human` class.

Composition addresses these issues:

```javascript

function Employee(name, email) {

this.name = name;

this.email = email;

}

function EmployeeDetails(ssn, salary) {

this.ssn = ssn;

this.salary = salary;

};

Employee.prototype.taxData = function() {

return new EmployeeDetails(this.ssn, this.salary);

};

```

In the above example, `Employee` has a relationship with `EmployeeDetails`, but it is not an instance of `EmployeeDetails`. Instead, `Employee` uses the `taxData()` method to create an instance of `EmployeeDetails`.

Conclusion

----------

Method chaining is a powerful tool in JavaScript classes that allows for flexible object construction. By returning objects after each method call, you can chain methods together, making your code more readable and easier to use.

In addition, composition and inheritance are different approaches to creating relationships between classes. While inheritance is useful when you want to create an "is a" relationship, composition is better suited when you want to create an object that has a relationship with another object.

By understanding these concepts and how to apply them in your code, you can write more flexible and maintainable JavaScript classes.

"WEBVTTKind: captionsLanguage: enthis is the fifth video in my clean code series based on Ryan mcdermitt's article this series is about how to write clean code that is readable reusable and refactor now I will talk about classes it's always better to write small functions than classes but if you do need a class you should use es6 classes instead of how classes are created in es5 especially if you need inheritance so let me show you how an es5 looks this is the bad way to do it so here is how you used to do it when you were um using es5 if you wanted inheritance I'm not going to go through all the details because again this is not how we want to do it but um we would create an animal and this is how you would create the the animal class and you could add a move function to it and if you wanted to inherit from the animal class you're going to create mammal and you you are going to have to um call the animal class within pass in the age but then if you want to add a fur color to the mammal that's different than the animal class this. fur color you are going to um create this the Prototype based on the animal class you are going to um create what the Constructor is uh basically there's a lot of different steps pretty long compared to what you will see for the es6 CL class so let me show you what the es6 class would look like and I just pasted that in and you can see this is much shorter this is the whole thing right here and it's so it's a lot more readable this es6 class is a lot more readable then you see what this es5 class looks like so we're going to create the class animal you're going to have the Constructor where you passing the age you're going to have the function move which is not defined in this example but we have the mammal which is going to extend animal that's how you're going to do inheritance and you're going to do super age which passes in the age here create the fur color uh create the the live birth function that's in the mammal class but not the animal class then we have the human class which extends mammal class you're going to pass in three things in the Constructor but it's going to do super agent fur color where this is just going to call the the previous function the function which is then going to pass the age to this function then you're going to create your your new uh language spoken variable here and you create you can create a new function here uh basically the point is that it's just a lot easier to read now let's go on to Method chaining method chaining allows your code to be more expressive and less verbose the easiest way to explain method chaining is just to show you so first I'm going to show you what it would look like without method chaining now this is the bad way to do it so if you create a class and you're going to have the Constructor here and this is some of the default values and then you can also um have these functions where you can set the make you can set the model you can set the color and then you would save the class using this function which is not the save is not fully implemented but just as an example it's going to console.log these things when you're creating a car class you're going to do console car equals new car car that set color pink car. set color 4 car. set model F150 and then car. save now let me show you what it would look like with chaining it's mainly this part right here that it's going to be a lot simpler so let me put in the the good way which is how you do method chaining now when you're creating a function with method chaining you're just going to return this at the end of every function so everything is the same in this new class car except we have this line at the end of each function uh we're going to return this we're going to return this we're going to return this we're going to return this and this allows us to do something different first let me show you what it used to look like when you were creating a car we were saying we had do car. set color car. set make car. set model c. save now since we've returned the car object at the end of each function we can just do this we don't have to do c. set color c. set mate c. set model we can just do do set color pink do set make do set model and do set save because up here after the function is is run it's going to just return undefined and then when you try to call another function if we did set color pink and then we put dot set make without putting the car here it's going to say that it cannot call this function on undefined because we're not returning that car again at the end of the function but when we return this at the end of each function um if after it sets the color to Pink it's going to return the car object so on that same car object you can set the make and then you can set the model and then we're just changing the methods one after the other okay the last thing I want to talk is that you should prefer composition over inheritance inheritance is like what we did up here where we did mammal extends Animal Human extends mammal that's inheritance human is inheriting from mammal mammal is inheriting from animal composition is when you have one class that's referenced from another class but you don't necessarily extend that that class um I'll show you an example but it's good to know that there are actually good reasons to use inheritance and good reasons to use composition but you should try to use composition over inheritance when possible well let me show you an example of the composition and inheritance so here would be the bad way to do it with composition and so we're going to create the class employee which is going to have this Constructor name and email and then we're going to create the class ask employee tax data and say extends employee so employee tax data is inheriting from employee but it says right here this is bad because employees have tax data employee tax data is not a type of employee and you're going to use composition when you have a has a relationship like employees has a or have tax data you're going to use inheritance when you have an is a relationship like a human is a animal or is an animal if you want to add tax data you're not just going to extend employ and add the tax data here you are going to use um composition so let me show you what that would look like so in this composition example you're still going to have two classes so first we're going to define the employee tax data class with the social security number and salary and then we're going to define the employee class but not none of the classes are going to extend from another class we are just going to use the employee tax data class within the employee class so it says set tax data uh social security number and salary uh this is just a function or a method of the employee uh class and we are going to say this. tax data equals new employee tax data social security number and salary so we are just calling this class from with in this other class and that's how you would do composition oh whoops this was supposed to say that this is the the good way to do it now there are some good reasons to use inheritance even though it says bad up here you just have to think through what your your actual problem is so if you have an is a relationship then you should use inheritance like the human is a animal like I said or but if you have a has a relationship like if you have user and user details a user is not user details but user has a detail then you would use composition also you should use inheritance if you can reuse code from base classes like humans can move like all animals and the third reason why you would want to use inheritance is that if you can if you want to make Global changes to derive classes by changing a base class well that's clean code classes thanks for watching my name is Bo KS don't forget to subscribe and remember use your code for goodthis is the fifth video in my clean code series based on Ryan mcdermitt's article this series is about how to write clean code that is readable reusable and refactor now I will talk about classes it's always better to write small functions than classes but if you do need a class you should use es6 classes instead of how classes are created in es5 especially if you need inheritance so let me show you how an es5 looks this is the bad way to do it so here is how you used to do it when you were um using es5 if you wanted inheritance I'm not going to go through all the details because again this is not how we want to do it but um we would create an animal and this is how you would create the the animal class and you could add a move function to it and if you wanted to inherit from the animal class you're going to create mammal and you you are going to have to um call the animal class within pass in the age but then if you want to add a fur color to the mammal that's different than the animal class this. fur color you are going to um create this the Prototype based on the animal class you are going to um create what the Constructor is uh basically there's a lot of different steps pretty long compared to what you will see for the es6 CL class so let me show you what the es6 class would look like and I just pasted that in and you can see this is much shorter this is the whole thing right here and it's so it's a lot more readable this es6 class is a lot more readable then you see what this es5 class looks like so we're going to create the class animal you're going to have the Constructor where you passing the age you're going to have the function move which is not defined in this example but we have the mammal which is going to extend animal that's how you're going to do inheritance and you're going to do super age which passes in the age here create the fur color uh create the the live birth function that's in the mammal class but not the animal class then we have the human class which extends mammal class you're going to pass in three things in the Constructor but it's going to do super agent fur color where this is just going to call the the previous function the function which is then going to pass the age to this function then you're going to create your your new uh language spoken variable here and you create you can create a new function here uh basically the point is that it's just a lot easier to read now let's go on to Method chaining method chaining allows your code to be more expressive and less verbose the easiest way to explain method chaining is just to show you so first I'm going to show you what it would look like without method chaining now this is the bad way to do it so if you create a class and you're going to have the Constructor here and this is some of the default values and then you can also um have these functions where you can set the make you can set the model you can set the color and then you would save the class using this function which is not the save is not fully implemented but just as an example it's going to console.log these things when you're creating a car class you're going to do console car equals new car car that set color pink car. set color 4 car. set model F150 and then car. save now let me show you what it would look like with chaining it's mainly this part right here that it's going to be a lot simpler so let me put in the the good way which is how you do method chaining now when you're creating a function with method chaining you're just going to return this at the end of every function so everything is the same in this new class car except we have this line at the end of each function uh we're going to return this we're going to return this we're going to return this we're going to return this and this allows us to do something different first let me show you what it used to look like when you were creating a car we were saying we had do car. set color car. set make car. set model c. save now since we've returned the car object at the end of each function we can just do this we don't have to do c. set color c. set mate c. set model we can just do do set color pink do set make do set model and do set save because up here after the function is is run it's going to just return undefined and then when you try to call another function if we did set color pink and then we put dot set make without putting the car here it's going to say that it cannot call this function on undefined because we're not returning that car again at the end of the function but when we return this at the end of each function um if after it sets the color to Pink it's going to return the car object so on that same car object you can set the make and then you can set the model and then we're just changing the methods one after the other okay the last thing I want to talk is that you should prefer composition over inheritance inheritance is like what we did up here where we did mammal extends Animal Human extends mammal that's inheritance human is inheriting from mammal mammal is inheriting from animal composition is when you have one class that's referenced from another class but you don't necessarily extend that that class um I'll show you an example but it's good to know that there are actually good reasons to use inheritance and good reasons to use composition but you should try to use composition over inheritance when possible well let me show you an example of the composition and inheritance so here would be the bad way to do it with composition and so we're going to create the class employee which is going to have this Constructor name and email and then we're going to create the class ask employee tax data and say extends employee so employee tax data is inheriting from employee but it says right here this is bad because employees have tax data employee tax data is not a type of employee and you're going to use composition when you have a has a relationship like employees has a or have tax data you're going to use inheritance when you have an is a relationship like a human is a animal or is an animal if you want to add tax data you're not just going to extend employ and add the tax data here you are going to use um composition so let me show you what that would look like so in this composition example you're still going to have two classes so first we're going to define the employee tax data class with the social security number and salary and then we're going to define the employee class but not none of the classes are going to extend from another class we are just going to use the employee tax data class within the employee class so it says set tax data uh social security number and salary uh this is just a function or a method of the employee uh class and we are going to say this. tax data equals new employee tax data social security number and salary so we are just calling this class from with in this other class and that's how you would do composition oh whoops this was supposed to say that this is the the good way to do it now there are some good reasons to use inheritance even though it says bad up here you just have to think through what your your actual problem is so if you have an is a relationship then you should use inheritance like the human is a animal like I said or but if you have a has a relationship like if you have user and user details a user is not user details but user has a detail then you would use composition also you should use inheritance if you can reuse code from base classes like humans can move like all animals and the third reason why you would want to use inheritance is that if you can if you want to make Global changes to derive classes by changing a base class well that's clean code classes thanks for watching my name is Bo KS don't forget to subscribe and remember use your code for good\n"