null state pattern

Null State Pattern

Pius Adams Ijachi
2 min readJan 31, 2024

Unpacking the Null State Pattern

Definition:

The Null State pattern is a behavioral design pattern that provides an object with an appropriate default state when its state is undefined or null. It helps avoid messy if-else checks for null states, offering a cleaner and more maintainable code structure.

Use Case: Navigating User States

In the realm of user authentication, the Null State pattern can be a game-changer. Consider scenarios where you need to manage both logged-in and anonymous users seamlessly. Let’s dive into a practical example:

Scenario: A Seamless User Experience

Meet our PHP code snippet:

// make the interface
<?php
interface UserInterface
{
public function getUsername();
public function getEmail();
}
// make classes that implement it
class User implements UserInterface
{
private string $username;
private string $email;
public function __construct($username, $email) {
$this->username = $username;
$this->email = $email;
}
public function getUsername(): string
{
return $this->username . "\n";
}
public function getEmail(): string
{
return $this->email;
}
}
class NullUser implements UserInterface
{
public function getUsername(): string
{
return "Guest \n";
}
public function getEmail(): string
{
return "guest@example.com \n";
}
}
// Usagefunction getCurrentUser(bool $isLoggedIn): UserInterface
{
if ($isLoggedIn) {
return new User("john", "doe@gmail");
}
return new NullUser();
}
$loggedInUser = getCurrentUser(true);
echo $loggedInUser->getUsername(); // Works for logged-in users
$anonymousUser = getCurrentUser(false);
echo $anonymousUser->getUsername(); // Works for anonymous users too

Easy, right? The Null State pattern ensures a smooth user experience without the hassle of tangled if-else checks.

Here, we have a function getCurrentUser that dynamically provides either a logged-in user or a null user based on the $isLoggedIn parameter. The Null State pattern simplifies the user retrieval process, ensuring a consistent user experience.

Implementation: Check Out the Code

Head over to the GitHub repository for the full implementation and explore other design patterns.

Dive Deeper: Watch the Tutorial

For a more in-depth understanding, check out the accompanying YouTube video tutorial: YouTube — Null State Pattern in PHP. It breaks down the concept, providing practical insights and real-world applications.

--

--