Try to Stay DRY
Have you ever cut and pasted a piece of code and then tweaked the resultant new code just slightly in order to perform a variation on the first piece of code? Oh come on now, fess up. Well that nagging feeling of guilt you have is your innate understanding of the DRY Principle kicking in. Listen to it: it is trying to help you.
The DRY principle (Don’t Repeat Yourself) dictates that there is one and only one authoritative source for a piece of information or logic with in a system. Imagine that the code you just cut and pasted was an implementation of a business rule. A new requirement arose that instigated your rash action. There was just enough of a variance of behavior that generalizing the original method would have required more effort than you were willing to expend so you cut and pasted the code to implement the new functionality. The only problem is that now you have two pieces of code that share common functionality implemented in two different places. What happens when that common functionality needs to be changed? What are the risks that it will not get changed in every instance? I think you are getting the idea of the reason for the DRY principal.
The Pragmatic Programmer states:
DRY says that every piece of system knowledge should have one authoritative, unambiguous representation. Every piece of knowledge in the development of something should have a single representation. A system’s knowledge is far broader than just its code. It refers to database schemas, test plans, the build system, even documentation.
Failure to follow the DRY principal results in brittle, difficult to maintain code. One of the most blatant and yet pervasive violations of the DRY principle is coupling the database directly to the presentation layer of an application. Many naive application implementations will encapsulate SQL statements directly into PHP, or VB forms thus tightly coupling the presentation and the database. If you have ever had to root through code written by a junior VB programmer you will know exactly what I mean. Not only is this kind of code difficult to maintain, it makes changing the database very difficult. This kind of coding practice can have far reaching consequences. What seemed like such a quick implementation now reveals itself as a huge maintenance trap for the customer.
The best way to avoid this form of coupling is to encapsulate the business logic and the database access in their own components. The presentation layer can safely use those components without fear that emerging changes will break functionality all over the application: breakages that will have to be painstakingly hunted down and fixed, usually through an arduous process of trial and error.
While this might seem like SOP to a reasonably competent OO developer, it is amazing how many new applications are developed every day that do not adhere to this fundamental design paradigm. Don’t let yours be one of them. Keep it DRY.