Main Content

Coding efficiency - do not repeat yourself!

Archive - Originally posted on "The Horse's Mouth" - 2010-11-02 06:54:28 - Graham Ellis

"If you find yourself repeating something ... there's probably a better way"

"If you find yourself thinking "surely someone's done this before" ... they probably have, and their code is probably available to you"

The things I find myself saying very frequently in courses ... for delegates who are new to programming get so involved in writing code that's going to work that they don't stop and think if they're doing to much work; they concentrate so much on the immediate task in hand, nose to grindstone, that they don't always look at the wider picture.

1. If you repeat the same code several times in succession, you probably should be using a loop.

2. If you repeat the same code several times in your program, you probably should be splitting that code out into a function.

3. If you find yourself writing the same code in several programs, you probably should be using an included file.

4. If you find yourself writing complex code to do a common, simple task there's probably a built in function to help you.

5. If you find yourself writing code that - surely - someone has done before, look at the resource libraries for the language you're using - PEAR, PECL, CPAN, Gems ... or at SourceForge.

Remember that if you duplicate code, you're duplicating the need for any fixes as you test and debug the code, and you're duplicating the maintainance tasks ongoing for the whole life of the code - and that will be a huge waste of time and effort.

From yesterday's PHP course: [control - no functions or includes] and [With functions and an include] ; [here] is the include file.