3 Bugs

 

This chapter covers

  • How to avoid syntax errors
  • Reduce runtime errors
  • Best practices in code layout and structure.

Coding errors in application code cause bugs in applications. A bug is a side effect of undetected coding mistakes; sometimes, they can be from misinterpreted user requirements. Regardless of the source, some bugs are avoidable through clean coding practices.

The process of finding and fixing bugs is called debugging, and this can be a tedious process where we need to break down each line of code, assess what it is doing, figure out what it should do, determine if it is a problem, and then attempt to fix it. The more complex and abstract the bug, the more time-consuming it is to fix.

One way to mitigate bugs is to know and avoid common coding mistakes that lead to them, which is this chapter's focal point. We will cover common pitfalls that lead to bugs in our PHP application.

Bugs come in various forms, so this chapter will be something of a mixed bag - but always, we’ll always be considering the core idea: “What mistakes can we avoid, or what best practices can we follow, to minimize bugs in our code?” Let’s begin discussing the dangers of leaving dangling array references.

3.1 Confusing returning by reference and returning by value

3.2 Leaving dangling array references after loops

3.3 Using isset with null values

3.4 Incorrectly using the empty function

3.5 Referencing classes inside namespaced classes without importing

3.6 Confusing the different types of comparison operators

3.7 Using static methods

3.8 Omitting curly braces in single-statement code blocks

3.9 Accidentally using the assignment operator instead of the comparison operator

3.10 Not being aware of the default date format

3.11 Using variable names with different cases

3.12 Getting the "headers already sent" error

3.13 Summary