Tdd: Chaining Constructors In Javascript

Test-driven development (TDD) has become an essential skill for any software engineer, and one of its most powerful tools is the constructor chain. Constructor chaining allows developers to quickly and easily create complex objects with just a few lines of code. In this post, we'll take a look at an example of constructor chaining in JavaScript, and explore why it can save developers time and effort while writing code.

Constructor chaining is a technique in which a class is created that contains a set number of instances of other classes. Then, these instances are connected together in a chain with each one calling the constructor of the following one. A good example of this technique is the popular “Chain-of-command” pattern, where the constructor for a particular class takes the constructor for another class and calls it, creating a chain of objects.

Given that JavaScript is an object-oriented language, this technique is quite easy to implement. To illustrate this, consider the following code. The first line defines a Person class, which has two properties: name and age. The second line defines a Builder class that takes an object representing a Person as a constructor argument.

class Person { constructor(name, age) { this.name = name; this.age = age; } } class Builder { constructor(person) { this.person = person; } build(name, age) { this.person.name = name; this.person.age = age; return this.person; } }

In the code above, the Builder class is using constructor chaining to create a new Person object. This can be seen in the build() method, where the Builder's constructor argument (a Person instance) is being used to create the new object.

Using the builder pattern, developers can create multiple Person objects in a single line. For example, the following code would create three People in a single call.

const people = new Builder(new Person()) .build('John', 20) .build('Sara', 25) .build('Dave', 30);

As you can see, this single expression creates three Person objects in a chain. This saves developers from having to call the constructor multiple times, which would not only be time consuming, but could also lead to errors in their code.

Constructor chaining is a powerful and flexible tool that can help developers create complex objects quickly and easily. It's a great way to streamline the development process and avoid common errors. So if you're looking to improve your JavaScript skills, give the constructor chain a try.