Hey Guys,
By the time most new PHP developers are mid-level, they have learned that object-oriented code is the approach that works for them and for programming in general. And so they decide that they want to use objects. But for too many developers, that choice to use objects doesn't represent a shift in how they develop: their objects are still procedural, but now we have procedural code wrapped in a class.
Oops.
The failure to actually object-orient our OO code is one of the biggest mistakes we can make, but luckily it's also one that we can fix.
A different thought process
Object-oriented development is a different thought process from procedural code. In procedural code, we think in a straight line, from start to finish, as our program progresses. Object-oriented code, though, necessarily contains some misdirection. And so, we have to retrain our brains.
So how do we do this?
First, we start by recognizing that objects are entities that represent other aspects of our code, or our application. For example, when dealing with POST data, instead of simply reaching for the superglobals, we want to recognize that the POST data is part of a larger context, and represent them in some object form.
We can also recognize the fact that every service or dependency we have (database, file system, cache, APIs) are things that are worthy of being represented by objects that can be mocked, tested and removed by configuration.
Writing for tests
One of the advantages of well-written object-oriented code is the testability of that code. Instead of having to rely on the "browser refresh" test method, we can write automated tests that swap one object for another, and test against known states. This dramatically improves our reliability and development process.
But in order to do this, we have to recognize that outside services and dependencies need to be mockable, to be testable. And so, object-oriented development should revolve around making this easy to accomplish.
This is where test-driven development (or TDD) really shines: by forcing us to develop tests first, we end up writing testable code that matches our assumptions and expectations. While developing your tests first may seem to be overkill, if you approach development this way, you'll quickly find that it's something you cant' live without. And your object-oriented applications will be better for it.
Gatcha Bitch!
ReplyDelete