Use cases of Lookup Tables – Pro refactoring

Use cases of Lookup Tables - Pro refactoring

Introduction

Hi, my name is Success David and today we are going to intensively at working with lookup tables – Use cases of Lookup Tables – Pro refactoring. I will start by writing the code in a way that looks familiar to you and then I refactor using lookup tables. These simple but vital techniques will go a long way to simplify your code and even offer better performance.

What are lookup tables?

In computer science, a lookup table is an array that replaces runtime computation with a simpler array indexing operation. While generally speaking, its just an array of key value pairs that can easily be reference instead of always reaching out to the database.

Whereas a lookup table can not only be represented as array, it can also be a database table, redis cache. But in this tutorial we are going to work with PHP Arrays.

Why use Lookup tables

From my personal experience, the effective use of a lookup table can greatly improve the performance of any application and also save you several lines of code.

Use cases of Lookup Tables – Pro refactoring

Example One: Do something based on the user’s role

if ($user->type === 'admin' || $user->type === 'editor' || $user->type === 'author'){
 // Do something
}

Refactor to Lookup table:

if (in_array($user->type, ['admin','editor','author'])) {
 // Do Something
}
if (collect(['admin', 'editor', 'author'])->contains($user->type)) {
  // Do Something
}

Basically what the above codes do is check if the user type is in the array, and you’ll agree with me that the refactors using the lookup table is simple and easy to read.

Example Two: Redirect user to the proper page

Okay in this second example, we are going to redirect a user to a certain page depending on the user’s type.

public function update(User $user)
{
	if($user->type === 'admin') {
		return redirect ('/admin');
	}else if ($user->type === 'editor') {
		return redirect ('/editor');
	}else if ($user->type === 'mod') {
		return redirect ('/moderator');
	}else {
		return redirect ('/guest');
	}
}

Looking at the above code, there is probably room to refactor, so here is how I will refactor it using lookup table

public function update(User $user)
{
	$destinations = [
		'admin' 	=> '/admin',
		'mod'		=> 'mod',
		'editor'	=> 'editor'
	];

	return redirect($destinations[$user->type]);
}

Now with this refactor, we are writing declarative code and not imperative code. Imperative code writes more easily while declarative code reads more easily.

Be the first to comment

Leave a Reply