I'm working on an application written in PHP using OOP principles. The classes in my application usually represent a table in the database; for instance, 'student', 'teacher', 'class', 'schedule', etc. As the application gets more and more complex, I start running into situations where it feels like writing a new query would be more efficient / faster than reusing the lower level objects + methods than I've already written. What's the standard philospohy when it comes to this? Is it handled on a case-by-case basis? Do you always reuse your code to prevent repeating yourself, even at the cost of the efficiency gained from one database query?
In "Facts and Fallacies of Software Engineering," Robert Glass says code reuse in the small is a solved problem, i.e. it's relatively easy to write reusable functions for simple, fine-grained tasks.
But Glass also says code reuse in the large is an unsolved problem. I take this to mean that there's no hard and fast rule about code reuse. The only answer is:
- Apply judgment and experience as best you can.
- Prototype quickly.
- Be ready to refactor as needed.
Many project try to simplify the problem space by making assumptions or imposing "conventions" but these simplifications unavoidably sacrifice some features you may need.
See the approach the guys from Doctrine project are preaching. This did answer a lot of questions for me when I struggled with PHP architecture dealing database items.
You may want to think ahead (but don't get too carried away). Will there ever be a time where you will want to switch database rdbms, or perhaps switch to a server cluster. What affects will changes like this have on your code? What happens if the database needs to be normalized, and table definitions change? Will the code be easily modifiable to adapt to the new requirements, or will it be very tedious to scrub the SQL in many files throughout your code.
There are tradeoffs to every design choice, and there isn't always a right or wrong way. you just have to think about your application and what may be important to it.
Nothing is free, the choice is up to you.
I you want speed, code everything in assembler. If you need flexibility, use libraries frameworks, roll your own interfaces.
I always make my code reusable and when the time comes, optimize (enable APC, autoloading cache, refactor, compile as a PHP module etc.).