10 Ways to Use Functions in Your Code to Become a Better PHP Developer

Tomasz Dobrowolski
5 min readMar 22, 2022
Photo by Remy_Loz on Unsplash

Functions are fundamental to writing code, making it vital that you write them well.

Well-written functions make your code efficient, easy to read and reduce the chance of errors.

Here is a list of advice on writing good functions with PHP examples, as detailed in Robert C. Martin’s book titled Clean Code:

1. Functions should do one thing

As a rule of thumb, functions should have one level of abstraction.

If there is more than one level of abstraction, not only is your code doing too much. It is difficult to understand for the reader and allows the possibility for other programmers to misinterpret the important parts of the code.

Take a function, for example:

public function getCategoriesFromSongID(int $songId): array
{
$arrayOfCategories = [];
$songInformation = $this->getSong($songId);
foreach ($songInformation['categories'] as $category){
array_push($arrayOfCategories, $category);
}
return $arrayOfCategories;
}

This is doing multiple things:

  1. Getting song information using the song ID.
  2. Looping through the array of categories in the song information…

--

--

Tomasz Dobrowolski
Tomasz Dobrowolski

Written by Tomasz Dobrowolski

I break down Software Engineering and Tech concepts | Backend Engineer 🐘

Responses (1)