2 Code readability and organization

 

This chapter covers

  • How to write readable code
  • Addressing code inefficiencies
  • Best practices in code layout and structure.

Writing well-organized and readable code is not a principle unique to PHP development. This is a general practice that we should always strive to adhere to develop maintainable and extendable applications. This benefits our team members and even our future selves when we need to revisit parts of the codebase.

Organizing a PHP codebase can be one of the most challenging endeavors for a web application developer. The default method of writing PHP generally interweaves its syntax with HTML code. This method of organization is easy enough for a beginner to see how they can work together. Still, it is not a sustainable way to organize application logic in the long run.

Beyond that, there are general programming principles that we are encouraged to adhere to, which can sometimes be compromised in a bid to get a working solution quickly. Sometimes we neglect proper spacing, indentation, and text layout practices. This leads to spaghetti-looking code that is difficult to read, debug and modify. Other mistakes we make include writing large blocks of code that could be divided into smaller methods, writing complicated code, and taking shortcuts.

We will review some mistakes that we sometimes make and review better approaches that we can take to ensure that our code not only works but also looks good.

2.1 Too many nested conditionals

2.2 Ignoring coding standards

2.3 Function doing too much

2.4 Overcomplication

2.5 Not commenting code where necessary

2.6 Inconsistent naming

2.7 Undescriptive and unreadable naming

2.8 Using arrays instead of classes

2.9 Using strings to represent dates

2.10 Optimizing for performance instead of readability

2.11 Not using type declarations

2.12 Summary