Photo by UX Indonesia from Unsplash
We have an interesting topic in web development to discuss in this article. It is a concept which some developers may think is not as important in web development. The concept we will be talking about today are interfaces. In this article I will explain to you why interfaces are important in web development. Let's get started!
What is an interface?
"An interface is a contract that defines signature of functionality" (Medium, 2019). The use of interfaces makes sure that all classes are created in accordance with the contracts that specify which methods and properties must be implemented. Additionally, in order to achieve abstraction, interfaces are utilized. Abstraction includes keeping all extraneous information from the user and just displaying the information that is necessary.
What are the benefits of using interfaces in OOP?
Now that you understand what exactly an interface is, you may still be wondering why interfaces are important. Interfaces must simply specify the behavior that an object must implement and so there are 5 key benefits of using interfaces in Object Orientated Programming. These benefits includes:
1. Creating highly loosely linked systems.
2. Implementing multiple class inheritance.
3. Implementing polymorphic behavior.
4. Developing applications in parallel.
5. Providing for improved unit testing through mocking.
Despite these benefits, JavaScript tends not to really use interfaces. But why? Let's discuss this.
Why JavaScript does not really use interfaces?
Languages such as Python is an OOP language, and so it supports the implementation of interfaces. JavaScript, on the other hand, doesn't come with a built-in method for designing or implementing interfaces. This makes sense because JavaScript doesn't utilize classes to construct objects and interfaces are a contract that specifies what classes should look like. However, because JavaScript is so adaptable, there are many other ways we can use it to construct interfaces. For instance, JavaScript that makes use of classes and interfaces can be produced using TypeScript. We will talk about TypeScript later on in this article. Overall, we may say that JavaScript is an object-based, dynamically typed language with prototype-based inheritance rather than to class-based inheritance.
How are objects created with JavaScript?
You may be thinking about how objects are creating in JavaScript. I have included code snippets to help you understand this better. Firstly, there are four ways to construct an object in JavaScript and these include:
1. Object Literals
2. New Operator or Constructor
3. Object Create
4. Class
Object Literals
A comma-separated list of paired names and values is known as an object literal or object initializer. As demonstrated below, you can build an object literal. In an object, you can dynamically add properties, even after the object has already been made. The dynamic property car.type is now added. The object literal is a straightforward expression that produces an object each time the code statement in which it appears is run.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//created an object literal for a car object where the name and value is seperated by a comma | |
const car = { | |
model: 'audi A4', | |
color: 'blue', | |
price: 6000 | |
} | |
console.log(JSON.stringify(car)); | |
// added a dynamic property | |
car.type = 'auto'; |
New Operator or Constructor
Utilizing the constructor function is the second method of creating an object. A function acts as a constructor and returns an object when it is called with the new operator. The constructor function can be used in two ways such as firstly making a function to specify the object type and secondly using the new operator to create an instance of an object. For instance, check out the code below.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The constructor function will create and initialize the car object by setting it with properties. The "this" keyword refers to the object. | |
function Car(model, color) { | |
this.model = model; | |
this.color = color; | |
} | |
const car = new Car('Audi A4', 'blue'); | |
console.log(car.model); |
Object Create
The object create method enables us to specify the prototype object and the properties which can also be used to create new objects. For instance:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Specify the object and the properties of the car | |
const Car = { | |
model: 'Audi A4', | |
color: 'blue' | |
} |
As demonstrated below, you can also construct another object using the Car object as a prototype. Using the Car object as a prototype to build the HEV (Hybrid Electric Car) object will mean that it has all the characteristics of the Car object.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// created a Hybrid Electric Vehicle (HEV) object which has the same properties as the above Car object | |
const HEVCar = Object.create(Car); | |
console.log(HEVCar.model); // Audi A4 |
Class
In JavaScript, a class can be created using the class property rather than a function constructor, and an instance can then be created using the new operator. Let's look at the code below to understand this better:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The class attribute can be used to create a class and we can introduce a new operator | |
class Car { | |
constructor(manufacturer, price) { | |
this.manufacturer = manufacturer; | |
this.price = price; | |
} | |
getData() { | |
console.log(this.manufacturer + " costs : " + this.price); | |
} | |
} |
The Car class can also be used to build the items as displayed below:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The Car class is used to create objects | |
const car1 = new Car("Audi A4", 400); | |
car1.getData(); | |
const car2 = new Car("Mercedes", 550); | |
car2.getData(); |
How can we emulate interfaces using JavaScript?
Despite the fact that JavaScript lacks a built-in method for designing or implementing interfaces, it is still a powerful language. JavaScript can be used to accomplish interface goals. So, how do we simulate interfaces? Well, 3 techniques can be used such as using comments, verifying attributes and duck typing. Let's discuss each techniques.
Comments
To mimic the interface, comments are used. This is regarded as the simplest but is however the least efficient technique. The "implements" and "interface" keywords are used to emulate other object-oriented languages in this approach. In order to prevent syntax errors, they are then commented out.
Verifying Attributes
This method is a little bit stricter than simulating the interface using comments because the interfaces are still just comments, but you can now check an attribute to discover what interfaces a class claims to implement. All classes explicitly state which interfaces they support, and objects wishing to interact with these classes can verify these declarations. If a class does not declare that it supports a necessary interface, you will encounter issues while describing the interfaces that a class implements. The biggest drawback of this strategy is that you can't be certain that the class actually implements this interface.
Duck Typing
Duck typing is a technique that decides whether an object may be used for a specific purpose, in this case, based solely on the methods it implements, whether an object is an instance of a class. The interface method must be evaluated using a helper function in order to determine whether an object implements an interface. The key point is that an object implements your interface if it has methods with the same names as those listed in your interface.
What is strict mode in JavaScript?
It is a semantically more restrictive or stricter version of JavaScript that generates errors for problems that would normally be handled silently. By beginning your script with the string "use strict," you can apply strict mode to the entire document. Alternatively, you can apply strict mode to certain functions by including the string "use strict" in those functions.However there are a few actions to take into considerations which are prohibited by JavaScript's strict mode as it will result in an error. The five actions to avoid are:
1. Function parameter duplication.
2. Giving read-only properties values.
3. Using variables that are not defined
4. Using reserved words as the name of a variable or function.
5. Eliminating objects, variables, or functions.
2. Giving read-only properties values.
3. Using variables that are not defined
4. Using reserved words as the name of a variable or function.
5. Eliminating objects, variables, or functions.
Why would we use strict mode?
We have noted that strict mode helps to eliminate errors by simply we can say that it is also simpler to create "secure" JavaScript in strict mode. Bad syntax that was previously tolerated is now actually an error. So strict mode is a resounding yes for all developers because it decreases defects, enhances security, and boosts overall efficiency of your application.
What is TypeScript?
TypeScript is an open-source object-oriented programming language that builds on JavaScript. It is a rigorous superset of JavaScript in terms of syntactic structure and offers richer documentation, validation, and a means to specify the shape of an object. In addition to the aforementioned, Typescript includes support for interfaces. In TypeScript, an interface explains how an object is shaped.
How can TypeScript be used to create interfaces?
The TypeScript compiler can use interfaces to give information about object property names and the datatypes that their values can contain. For your functions, variables, or the class that is implementing the interface, the interface adds the capability of strong type checking. It is possible for interfaces to be established implicitly by the compiler or to be explicitly defined.
Conclusion
Now that we have discussed interfaces, we can say that it is an important topic of JavaScript abstraction. We can simply say that interfaces is a list of things that a class has to have. Overall, interfaces are seen as powerful especially when multiple interfaces exists on the same class.Thank you for reading!
Sources
HyperionDev - Full Stack Web Development
JavaScript patterns - JavaScript Interfaces
Medium - What is Interface? by Rajesh Pillai
Comments
Post a Comment