Avoid inline code and logic | Write Clean Code - Part 2
In our previous post we wrote how to reduce if else in php in order to write the clean. Today, I am going to show you how to avoid inline code and logic in PHP.
Consider, you have a piece of code, that will allow a user to upload the image into your system. The overall process is-
- A user can able to upload an image
- The code will check the extension of the uploaded image
- Cross-check whether is uploaded image extension is allowed to upload or not
- Allow to upload if the previous condition is pass, otherwise, show the error
I am sure, there are many ways to do that. I have a piece of code already that has written by one developer. Let’s review the code-
public function uploadFile()
{
$allowedFileExtensions = ['jpg', 'gif'];
// This will upload by user. This code is only to demonostrate
$fileName = 'nature.jpg';
$allowedFileToUpload = in_array(strtolower(end(explode('.', $fileName))), $allowedFileExtensions) ? true : flase;
if ( $allowedFileToUpload) {
# Upload your image
} else {
# Error and Redirect
}
}
This code works fine, without having any issue. But if you look into the code, I feel this $allowedFileToUpload = in_array(strtolower(end(explode('.', $fileName))), $allowedFileExtensions) ? true : flase;
line is kind of confusing or hard to read. I strongly believe this line can make more readable.
Let’s do refactor
After reviewing the code, I come out with the following refactoring. Here is my idea-
public function uploadFile()
{
$allowedFileExtensions = ['jpg', 'gif'];
// This will upload by user. This code is only to demonostrate
$fileName = 'nature.jpg';
$fileToPath = explode('.', $fileName);
$fileExtension = strtolower(end($fileToPath));
if ( ! in_array($fileExtension, $allowedFileExtensions)) {
// Error and Redirect
}
// Upload the file
}
My idea is to make each line more meaningful. Now you can see the lines I have used to have its own purpose. At least, each line describes it’s own task.
Feel free to share your idea also to improve this code better.
Thank you.