Tips and notes on writing code that is easy to read and pleasant to look at
Programs are meant to be read by humans and only incidentally for computers to execute. - Donald Knuth
You only write it once, you’ll read it lots of times
1// e.g.
2
3class UrlFetcher {
4 public static function fetchUrl() {
5 // ...
6 }
7}
8
9$response = UrlFetcher::fetchUrl($url); // read this out loud.
10
11// remember, some people subvocalize what they read..
if
blocks, you’ll avoid code duplication. If the return statement is in the if
blocks, you’re probably repeating it inside the many if blocks for every successful check 1// Don't do it like this
2<?php
3
4class User {
5 public function fullName() {
6
7 if ($this->firstName && $this->lastName) {
8 return $this->firstName . ' ' . $this->lastName;
9 }
10
11 return null; // return null by default
12 }
13}
1// Do it like this, this is better
2<?php
3
4class User {
5 public function fullName() {
6
7 if (!$this->firstName || !$this->lastName) {
8 return null; //return null if the firstName or lastName don't exist
9 }
10
11 return $this->firstName . ' ' . $this->lastName;
12 }
13}
Here’s and example of code where you’re uploading a file
1// This is MEH
2// You have to keep a mental model of states (if inside of if and then that else)
3<?php
4
5if (isset($_POST['file'])) {
6
7 if (in_array($fileExtension, $allowedExtensions)) {
8 // Upload file
9 } else {
10 return;
11 // Error and redirect
12 }
13
14} else {
15 return;
16 // Error and redirect
17}
1// This is BETTER
2// Do the negatives first (cleaner, easier to read, easier to maintain)
3<?php
4
5if (!isset($_POST['file'])) {
6 return;
7 // Error and redirect
8}
9
10if (!in_array($fileExtension, $allowedExtensions)) {
11 return;
12 // Error and redirect
13}
14
15// Upload the file!