Register to get access to free programming courses with interactive exercises

Null Object Pattern JS: Polymorphism

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:

// Somewhere in the imaginary template articles/index.html.slim

if isAuthenticated && currentUser.hasArticles()
  each article in currentUser.getArticles()
    // Here we output the articles

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:

class Guest
{
  hasArticles() {
    return false;
  }

  getArticles() {
    return [];
  }
}

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:

if currentUser.hasArticles()
  each article in currentUser.getArticles()
    // Here we output the articles

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:

const fetchCurrentUser = (req) => {
    const userId = req.session.userId;
    // If there's an id in the session, we select the user from the database
    // Otherwise, we return guest
    return userId ? User.find(userId) : new Guest();
};

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):

# This code is in Ruby, but it's simple
class Guest
  def id
    nil
  end

  def avatar
    nil
  end

  def github_account
    false
  end

  def has_passed_at_least_one_project?
    false
  end

  def city
    ''
  end

  def seeking_job?
    true
  end

  def mentor?
    false
  end

  def locale?
    nil
  end

  def guest?
    true
  end

  def current_subscription_object
    FreeSubscription.new(self)
  end

  def type
    'guest'
  end

  def topics_count
    0
  end
end

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.

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:

Bookmate
Health Samurai
Dualboot
ABBYY
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.