Development

Naming conventions, name length and style

Naming conventions

I suppose you have already read PSR-1 and PSR-2, which contain PHP’s naming recommendations. E.g. like camelCase for function names etc.

But there are few things which aren’t precised there, and can have a huge impact on your code quality.

Variables and Attribs naming style

First things first – you should use one style of naming the variables, which means that you should decide if

will be used and you should not mix that. In most of my projects, and on the team I work on, we use under_score. It’s alternative name is snake_case. Why?

  • It’s easier to see difference between variable and functions calls.
  • In the database, many times the column and table names use under_score. It will be good to use the same style for object attributes.

exception – the const should be named whole in UPPERCASE.

Too Short Names

Please forget about shortcuts or “imp” names. Something like that is terrible:

Nobody will know what was the intention of those. The name should simply say something about the variable data or function purphose.

Too Long Names

On the contrary – too long names are also code smells. If you need to use more than 3 words to name a function/attribute/variable. There are two possibilities: you are doing something wrong or there is too much logic in your code.

Option one – you are doing something wrong. E.g. you are using a domain name from your class in the function name, e.g:

Because you are inside the user class. It is according to the “single responsibility” principle that you cannot create anything other than user inside it, so you should not add “user” in your function names. In conclusion, the code should look like that:

Single Word

If you can, use single words in your function names. You should definitely do this for single operations like get, fetch, find, save, update, delete, all, first, etc.

It is also good to use antonyms, for example: begin – end, first – last, next – previous, min – max, add – delete, up – down, source – target.

Boolean methods 

Any boolean returning methods name  should start with: is… (isAdmin), has… (hasErrors), can… (canEExecute).

E.g. if you want to check if something is valid – don’t call the function “validate”, therefore expect it to return boolean. The function should be called “isValid” because “validate” should only be used to perform validation. Not to check the result.

Subsequent articles

  • Static Factory Methods aka Named Constructors: Read more…
  • Improving conditions clauses – few small things with hudge impact: Read more…