best practice

Best Practice With Return Types In PHP

23rd July 2018 - 9 minutes read time

I've been using PHP for a number of years and have seen the same things being done with return values from functions over and over again. I have always thought of this as pretty standard, but the more I think about it the less it makes sense. Looking back over my career I am quite sure that a few serious bugs could have been avoided if I had not mixed return types.

As PHP is a loosely typed language this gives the developers the ability to change the type of value that is returned from a function. This happens quite often within the PHP codebase itself as many built in functions will return false if an error happened.

A common practice in userland code is to return false from a function if something went wrong. This might be because it is encouraged in PHP itself.

Don't Validate And Format In A Single Function

30th June 2018 - 5 minutes read time

I wanted to impart a piece of advice to do with validation and formatting of user input, although I've never seen anyone suggest it. I guess it would come under the single responsibility principle so it might seem obvious to some people. There can be reasons why this might at least seem like a good idea at the time.

Essentially, if you want to validate that something is correct, don't format it at the same time. These two actions should be done in separate functions or even classes. I hope to demonstrate that using a single function validate and format anything is a bad idea. I'll mainly be using PHP to demonstrate this, but the principle should be pretty much the same in any language.

Take the following function called isValid(). This is an arbitrary and simple example but shows validation and formatting in use in a single function.