DEV Community

KILLALLSKYWALKER
KILLALLSKYWALKER

Posted on

The Null Awakens: Making Missing Data Harmless

Usually in job portal , we got a lot of registration but some of user don't even finish the profile . Some user set their profile , some user not set at all .

This cause our code look really bad and hard to maintain where it become like this every time we want to use user profile .

$logo = $job->company && $job->company->profile
    ? $job->company->profile->logo
    : asset('images/default-company.png');
Enter fullscreen mode Exit fullscreen mode

there's a lot if checks . This is really hard to maintain when we want to use this in a lot of place .

The Solution : Null Object Pattern

The Null Object Pattern is a design pattern where instead of returning null, you return a special "empty" object that behaves like the real one but with safe defaults.

This removes the need for null checks and keeps our code clean.

First we create a NullProfile class

<?php

namespace App\Models\NullObjects;

class NullProfile
{
    public function getLogo(): string
    {
        return asset('images/default-company.png');
    }
}
Enter fullscreen mode Exit fullscreen mode

Once we have NullProfile class , we use it in model

class Company extends Model
{
    public function profile()
    {
        return $this->hasOne(Profile::class);
    }

    public function getProfileOrDefaultAttribute()
    {
        return $this->profile ?? new NullProfile();
    }
}
Enter fullscreen mode Exit fullscreen mode

Then we can use it like this , we don't need anymore complicated logic if in all over place anymore . Just use this and it will be safe enough .

$company->profile_or_default->getLogo();
Enter fullscreen mode Exit fullscreen mode

Why It Helpful

Usually for a job portal there will be multiple relationship that require us to access the company profile or user profile , by using this null object paatern we can avoids null checks across all our code . This can help to keep our views and controller clean and safe .

Why Not Just Handle in Accessors ?

1 . For me small project would be good enough already
2 . For field level default accessor already work great , but in this case the profile is object for the company .

Top comments (0)