Program for reliability and efficiency - do not duplicate, but rather share and re-use
Archive - Originally posted on "The Horse's Mouth" - 2010-07-19 06:39:05 - Graham Ellis
When you're writing a new piece of code - especially if you're also quite new to programming - you'll be concentrating so much on getting it to work that you may not be giving too much thought to making it easy look after your code later on (maintainance), nor to sharing a piece of code between programs. But in the medium and longterm, if you can avoid duplicating code you'll be saving yourself and you colleagues a lot of time and effort!
• If you find yourself copying and pasting a block of code, there's probably an easier way!
• If you duplicate a block of code, but then alter a few elements, don't say "that's not a duplicate" - say "I have identified which values will be parameters to a function"
I have an example here from a Python course at the start of last week. Look at this code:
while True:
him = int(raw_input("How many years old is he? "))
if him < 0 or him > 119:
continue
break
while True:
her = int(raw_input("How many years old is she? "))
if her < 0 or her > 119:
continue
break
It's almost exactly the same block of code - just the prompt and the result variable are changed, and a good case to make a named block of code. This is Python, so we used "def" but it could have been sub in Perl, function in PHP, or proc in Tcl.
The function code has to be defined before it is called - here's my example:
def getage(person_word):
while True:
question = "How many years old is " + person_word + "? "
age = int(raw_input(question))
if age < 0 or age > 119:
continue
break
return age
That does not run the code - it just defines it. You then call it by name, passing in the string that contains the person_word, and returning the result to another variable:
him = getage("he")
her = getage("she")
Taking that a step further, you'll want to share the code between programs. You can do that by putting your defined function into a shared file (usually alongside other functions that are to be shared) which you will then pull in as required in some way. In Perl, that would be a use or a require, in Tcl it would be a source, and in Python it would be a from or an import.
Structure your code well using these techniques - not only will you find you're making huge time savings in the long term, but you'll find that you're also wring more consistent and reliable programs - and that the benefits come in the short term too. Did I tell you that by naming a block of code, you provide a unit of code that's much easier to test and debug ... with a built in test routine and documentation too!