PHP best practices #1: duplication is evil

I am very opinionated about my code.  The source of most of my opinions is the DRY/DIE principal: Don’t Repeat Yourself / Duplication Is Evil.

 

Take, for instance, a Human Resources application I worked on recently. It is a collection of web forms to get information to and from the HR department at work.  I inherited the system and had to make several improvements: form field validation had to be more robust, submitted form data had to be formatted in a prettier way, fields had to be removed/added, etc.

This was a pain. This application was simple – two forms, less than 50 fields total across each. Total lines of PHP code: 1000 maximum, including comments and HTML. That’s tiny! And yet, within this tiny code base, information was duplicated at least six times. And it was inconsistent – each duplicated piece of information told a different, contradictory story about the web form.

This is why I have internalized the DRY/DIE principal. If you stick with this principal from the get-go, applications are much more robust and easier to maintain. Luckily, my story has a happy ending: I ported 90% of it to PHP-Frame and modified the forms with time to spare, and even got a few nice cosmetic extras in.

tl;dr for this post: next project you’re working on, count how many places you duplicate similar information. Try to minimize that number. I reduced it from 6 to 2 in my application (all the form field validation requirements laid out in the application’s Model; and all the form fields laid out in HTML).  Many methods can be used to avoid (or eliminate, when refactoring) duplicated code and information, including solid framework design (which I have focused on thus far) and using generated code (which I haven’t delved into very much). Regardless of which path you take: don’t duplicate code, and don’t duplicate information.  Duplication is evil.

 

Further reading:

Rule three [wikipedia]

Single source of truth [wikipedia]

Don’t Repeat Yourself [wikipedia]

Separation of concerns [wikipedia]

This entry was posted in Coding, News and tagged . Bookmark the permalink.

One Response to PHP best practices #1: duplication is evil

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>