Register to get access to free programming courses with interactive exercises

Code that kills polymorphism JS: Polymorphism

Creating objects

Look at the function below and say if it is polymorphic or not:

const sayHiByEmail = (user) => {
  const sender = new EmailSender();
  // Sending an email to a user
  sender.send(user.getEmail(), 'hi!');
};

On the one hand, it is polymorphic because we pass the user from outside, and we can substitute it by passing an object of another class there. On the other hand, we use the class EmailSender explicitly inside the function, and you can't replace it without rewriting the code itself.

This code demonstrates a simple but crucial idea. Subtype polymorphism is possible when we pass an object into a function from outside rather than construct directly inside it.

We can also create an object inside a function, but we should obtain the class name dynamically. We will look at this technique later in the lesson about metaprogramming.

Checking types

Another example is with a catch. Is there polymorphism in the code below?

const sayHi = (user) => {
  if (user instanceof User) {
    console.log(`Hello, ${user}!`);
  } else if (user instanceof Guest) {
    console.log('Hello, guest!');
  } else {
    console.log('Who are you?');
  }
};

Everything seems fine in this example: we pass the object from outside, but there is one snag. We check the type explicitly inside the function. So that behavior is not determined by the type.

The function itself decides how to behave. Moreover, it is hardwired to the types defined within it. If they change, we have to rewrite the function. As a result, there is no subtype polymorphism.

Type checking sometimes occurs and can be used to keep the code simple, but more often, it's a sign of poor design. One might say that such code doesn't correspond to OOP in its modern sense.

There are several approaches to solving the problem above:

  • Transferring the logic inside the classes. Then the function code becomes: user.sayHi(). You should be careful with this approach because it's easy to end up with god object. Generally, it's better to take a different approach.
  • Adding a new interface in the form of the isUser and isGuest methods

    const sayHi = (user) => {
      if (user.isUser()) {
        console.log(`Hello, ${user}!`);
      } else if (user.isGuest()) {
        console.log('Hello, guest!');
      } else {
        console.log('Who you are?');
      }
    };
    

Although there's no less code, it's still subtype polymorphism. The code is bound to methods, not types. Changing the class structure will not affect this function if the logic remains the same.


Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

About Hexlet learning process

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs
profession
Development of front-end components for web applications
10 months
from scratch
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.