Main Content

Code and code maintainance efficiency

Archive - Originally posted on "The Horse's Mouth" - 2005-06-08 05:36:35 - Graham Ellis

Three maxims of coding and system development; I'm reminded of these this week as I run a PHP course which is heavily biased towards good coding standards / writing robust and maintainable web sites, but they apply to other languages / coding systems too!

"If you find yourself repeating something, then there must be a better way of doing it".

Have you even copied and pasted a block of code? I know I have, and then I've probably modified the duplicate. If you're copying and pasting, think again. Perhaps you should be incorporating the block of code into a loop, or perhaps it should become a function? If you're copying and pasting, but then altering the copy, you can still use a loop or a function - the bits that you change will become the loop control variables, or the parameters to the function.

"If you think to your self 'surely someone else has done this before', they probably have"

Don't re-invent the wheel! You'll very rarely be the first person ever to want to do "x" or "y", so have a look for a function / procedure / command that does what you want. In the Open Source world especially, where code develops with a multitude of enthusiastic contributors, you'll find rich picking by browsing the manuals in the area around what you're looking for. On our Python course, I tell a story against myself. In a live application, I wanted to re-arrange a list into a random order. Great - wrote the code, tested it, and it worked well. Then I discovered that there's already a shuffle method in the random module that's a part of the standard distribution ...

And in PHP we have a saying - "There's a function to do that".

"Each component should perform a single task"

Keep each logical task in its own component. Why? Because, later on, you may wish to use that task again and if it comes bundled with a second task with which it's not logically connected, it may be non-trivial to separate out. Again, an example; the images on the left hand side of our web site are 132 x 300 pixels, and they're all bundled with a white band 8 pixels wide on the right to separate off the text from the margin. Great ... until I want to change the colour of the band. Because I've bundled the band and the picture in the same image file, there's no easy way.