Yeah, now you know me

Clean Code PHP

Software engineering principles, from Robert C. Martin’s book Clean Code, adapted for PHP. This is not a style guide. It’s a guide to producing readable, reusable, and refactorable software in PHP.

Not every principle herein has to be strictly followed, and even fewer will be universally agreed upon. These are guidelines and nothing more, but they are ones codified over many years of collective experience by the authors of Clean Code.

Inspired by clean-code-javascript

Although many developers still use PHP 5, most of the examples in this article only work with PHP 7.1+.

Variables

Use meaningful and pronounceable variable names

Bad:

Good:

Use the same vocabulary for the same type of variable

Bad:

Good:

Use searchable names (part 1)

We will read more code than we will ever write. It’s important that the code we do write is readable and searchable. By notnaming variables that end up being meaningful for understanding our program, we hurt our readers. Make your names searchable.

Bad:

Good:

Use searchable names (part 2)

Bad:

Good:

Use explanatory variables

Bad:

Not bad:

It’s better, but we are still heavily dependent on regex.

Good:

Decrease dependence on regex by naming subpatterns.

Avoid nesting too deeply and return early (part 1)

Too many if else statements can make your code hard to follow. Explicit is better than implicit.

Bad:

Good:

Avoid nesting too deeply and return early (part 2)

Bad:

Good:

 

Avoid Mental Mapping

Don’t force the reader of your code to translate what the variable means. Explicit is better than implicit.

Bad:

Good:

 

Don’t add unneeded context

If your class/object name tells you something, don’t repeat that in your variable name.

Bad:

Good:

 

Use default arguments instead of short circuiting or conditionals

Not good:

This is not good because $breweryName can be NULL.

Not bad:

This opinion is more understandable than the previous version, but it better controls the value of the variable.

Good:

You can use type hinting and be sure that the $breweryName will not be NULL.

 

Comparison

 

Use identical comparison

Not good:

The comparison $a != $b return false but in fact it’s true ! The string ’42’ is different than the int 42

Good: Use the identical comparison will compare type and value

The comparison $a !== $b return true.

 

Functions

Function arguments (2 or fewer ideally)

Limiting the amount of function parameters is incredibly important because it makes testing your function easier. Having more than three leads to a combinatorial explosion where you have to test tons of different cases with each separate argument.

Zero arguments is the ideal case. One or two arguments is ok, and three should be avoided. Anything more than that should be consolidated. Usually, if you have more than two arguments then your function is trying to do too much. In cases where it’s not, most of the time a higher-level object will suffice as an argument.

Bad:

Good:

 

Functions should do one thing

This is by far the most important rule in software engineering. When functions do more than one thing, they are harder to compose, test, and reason about. When you can isolate a function to just one action, they can be refactored easily and your code will read much cleaner. If you take nothing else away from this guide other than this, you’ll be ahead of many developers.

Bad:

Good:

 

Function names should say what they do

Bad:

Good:

 

Functions should only be one level of abstraction

When you have more than one level of abstraction your function is usually doing too much. Splitting up functions leads to reusability and easier testing.

Bad:

Bad too:

We have carried out some of the functionality, but the parseBetterJSAlternative() function is still very complex and not testable.

Good:

The best solution is move out the dependencies of parseBetterJSAlternative() function.

 

Don’t use flags as function parameters

Flags tell your user that this function does more than one thing. Functions should do one thing. Split out your functions if they are following different code paths based on a boolean.

Bad:

Good:

 

Avoid Side Effects

A function produces a side effect if it does anything other than take a value in and return another value or values. A side effect could be writing to a file, modifying some global variable, or accidentally wiring all your money to a stranger.

Now, you do need to have side effects in a program on occasion. Like the previous example, you might need to write to a file. What you want to do is to centralize where you are doing this. Don’t have several functions and classes that write to a particular file. Have one service that does it. One and only one.

The main point is to avoid common pitfalls like sharing state between objects without any structure, using mutable data types that can be written to by anything, and not centralizing where your side effects occur. If you can do this, you will be happier than the vast majority of other programmers.

Bad:

Good:

 

Don’t write to global functions

Polluting globals is a bad practice in many languages because you could clash with another library and the user of your API would be none-the-wiser until they get an exception in production. Let’s think about an example: what if you wanted to have configuration array. You could write global function like config(), but it could clash with another library that tried to do the same thing.

Bad:

Good:

Load configuration and create instance of Configuration class

And now you must use instance of Configuration in your application.

 

Don’t use a Singleton pattern

Singleton is an anti-pattern. Paraphrased from Brian Button:

  1. They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell.
  2. They violate the single responsibility principle: by virtue of the fact that they control their own creation and lifecycle.
  3. They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.
  4. They carry state around for the lifetime of the application. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no for unit tests. Why? Because each unit test should be independent from the other.

There is also very good thoughts by Misko Hevery about the root of problem.

Bad:

Good:

Create instance of DBConnection class and configure it with DSN.

And now you must use instance of DBConnection in your application.

 

Encapsulate conditionals

Bad:

Good:

 

Avoid negative conditionals

Bad:

Good:

Avoid conditionals

This seems like an impossible task. Upon first hearing this, most people say, “how am I supposed to do anything without an if statement?” The answer is that you can use polymorphism to achieve the same task in many cases. The second question is usually, “well that’s great but why would I want to do that?” The answer is a previous clean code concept we learned: a function should only do one thing. When you have classes and functions that have if statements, you are telling your user that your function does more than one thing. Remember, just do one thing.

Bad:

Good:

 

Avoid type-checking (part 1)

PHP is untyped, which means your functions can take any type of argument. Sometimes you are bitten by this freedom and it becomes tempting to do type-checking in your functions. There are many ways to avoid having to do this. The first thing to consider is consistent APIs.

Bad:

Good:

 

Avoid type-checking (part 2)

If you are working with basic primitive values like strings, integers, and arrays, and you use PHP 7+ and you can’t use polymorphism but you still feel the need to type-check, you should consider type declaration or strict mode. It provides you with static typing on top of standard PHP syntax. The problem with manually type-checking is that doing it will require so much extra verbiage that the faux “type-safety” you get doesn’t make up for the lost readability. Keep your PHP clean, write good tests, and have good code reviews. Otherwise, do all of that but with PHP strict type declaration or strict mode.

Bad:

Good:

 

Remove dead code

Dead code is just as bad as duplicate code. There’s no reason to keep it in your codebase. If it’s not being called, get rid of it! It will still be safe in your version history if you still need it.

Bad:

Good:

 

Objects and Data Structures

Use object encapsulation

In PHP you can set publicprotected and private keywords for methods. Using it, you can control properties modification on an object.

  • When you want to do more beyond getting an object property, you don’t have to look up and change every accessor in your codebase.
  • Makes adding validation simple when doing a set.
  • Encapsulates the internal representation.
  • Easy to add logging and error handling when getting and setting.
  • Inheriting this class, you can override default functionality.
  • You can lazy load your object’s properties, let’s say getting it from a server.

Additionally, this is part of Open/Closed principle.

Bad:

Good: