JS: Polymorphism
Theory: Null Object Pattern
Developers of sites with authentication often use the concept of a current user. This user authenticates through a form or logs in through a social network. The current user helps to display different blocks of information — for example, that user's blog. This kind of code usually looks like this:
Note the user authentication check. If you don't do it, the code will crash. It happens because we call the hasArticles() method on value null (if nobody logged in, there's no user). When there are one or two of these checks, it's okay. But if there are many, the code gets cluttered quickly. In addition, it's easy to forget to insert such a check.
Is there any other way to solve this problem? It turns out there is. You can use subtype polymorphism. To do so, we create a class that describes an unauthenticated user, such as Guest. Then we can add all the necessary methods to get polymorphic behavior:
Most of these methods return false or empty lists because this user has nothing. Why do we need it? Now the client code always counts on the existence of the user, and it no longer needs to check authentication:
Conditional constructions will go away in all patterns, but one question remains. Where and how does the process of creating our user take place? And this is where the only if remains, through which we create the right object.
It happens at the stage where the incoming request is processed, and the exact location depends on the framework used. The code at this point looks something like this:
This usage of polymorphism has a name — the null object design pattern. It's often used within frameworks and in application code. There are at least three such places on Hexlet. For example, we have dozens of methods in the Guest class. Here's what's inside (not an exhaustive list):

