JavaScript From Beginner To Advanced

0% completed

Previous
Next
JavaScript - Polymorphism
Image

Polymorphism is a term derived from the Greek words poly (many) and morph (form), and in the context of object-oriented programming, it refers to the ability of different objects to respond to the same method call in different ways. Essentially, it means "many forms" of a single method. Polymorphism is a fundamental concept in software development that allows systems to be more flexible and extensible—making it easier to add new features while minimizing changes to existing code.

The power of polymorphism lies in its ability to let different classes have different implementations of the same method, defined in a common interface or parent class. For example, think of a function in a drawing application that asks various shapes like circles, squares, and triangles to draw themselves. While the function to initiate the drawing is the same, the way each shape draws itself can be vastly different—circles show a round edge, squares show four equal sides, and so forth. This allows programmers to use a unified interface to interact with objects of different classes, reducing complexity and increasing manageability.

Ways to Achieve Polymorphism

In JavaScript, polymorphism can be achieved through inheritance and the use of prototype chains:

  1. Method Overriding - Subclasses override a method of their parent class to provide specific behavior while maintaining the same interface.
  2. Duck Typing - JavaScript, being a dynamically typed language, naturally supports polymorphism where an object's suitability is determined by the presence of certain methods and properties, rather than the object's type itself.

Example: Simplified Polymorphism with Method Overriding

Let's create astraightforward example where two types of payment methods, CreditCard and PayPal, both extend a generic PaymentMethod class. Each will have their own implementation of a pay method, but can be used interchangeably in the same context.

Javascript
Javascript

. . . .

Explanation:

  • PaymentMethod Class:

    • Acts as the base class with a generic pay method that provides a default payment message.
  • CreditCard and PayPal Classes:

    • These classes extend PaymentMethod and override the pay method to provide specific behaviors appropriate for each payment type.
  • processPayment Function:

    • This function is designed to accept any object that adheres to the PaymentMethod interface (i.e., has a pay method). This demonstrates polymorphism by allowing different types of payment methods to be processed using the same function.
  • Polymorphism Usage:

    • The function processPayment is called with instances of CreditCard and PayPal. The specific pay method of each class is invoked, showing polymorphism in action where the same interface (pay method) is used for different underlying classes.

Example: Achieving Polymorphism Through Duck Typing

Duck typing in JavaScript allows for a more flexible approach to polymorphism. In this example, two different payment methods are created not through a common class, but as individual objects that both implement a pay method. This approach highlights JavaScript's ability to use polymorphism based not on a strict inheritance hierarchy, but on the presence of certain methods or properties.

Javascript
Javascript

. . . .

Explanation:

  • DebitCard Object:

    • Defines an object DebitCard with a pay method. This method logs a message indicating a payment is being made using a debit card, showing the amount being paid.
  • BankTransfer Object:

    • Similar to DebitCard, but represents a bank transfer method. Its pay method logs a payment being made via bank transfer, also showing the payment amount.
  • handlePayment Function:

    • This function is designed to process payments regardless of the specific payment method object passed to it.
    • It checks if the passed item has a pay method, reflecting the concept of duck typing: if it looks like a duck (has a pay method), it's treated as a duck.
    • If pay exists, it calls this method with the specified amount, effectively processing the payment.
    • If the object does not have a pay method, it logs an error message stating "Invalid payment method".
  • Calling handlePayment:

    • The function is called twice, once with DebitCard and once with BankTransfer, each time with different payment amounts. These calls demonstrate the function's ability to handle different payment methods uniformly without needing a common superclass or interface.

This example showcases the power of duck typing in enabling polymorphism in JavaScript. It allows different objects to be used in the same function (handlePayment) as long as they provide the necessary methods (pay), making the code flexible and extensible.

Benefits of using Polymorphism in JavaScript

  1. Code Reusability:

    • Polymorphism allows programmers to reuse a single interface to represent different data types. For instance, a function written to handle an object of a superclass can handle objects of all subclasses. This reduces the need to write new code for each new object type, promoting code reuse.
  2. Maintainability:

    • By using polymorphic principles, software becomes easier to manage and maintain. Changes in one part of a system can have minimized effects on other parts, reducing the likelihood of bugs when enhancements or modifications are made. This is because the use of generic interfaces means that components are less tightly coupled.
  3. Scalability:

    • With polymorphism, systems are easier to scale and extend over time. New classes can be added with little or no modification to existing functions or classes that use the polymorphic interfaces. This facilitates the growth and expansion of systems with minimal disruption to existing functionality.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next