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
andisGuest
methodsconst 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.
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.