Separating your code for easier testing, understanding and re-use; example in Ruby
Archive - Originally posted on "The Horse's Mouth" - 2015-06-02 17:59:50 - Graham Ellis
You don't want to write the same piece of program twice. Nor do you want to have to call in the technical experts on a particular topic to work on general code. So you should separate your code (whatever language you're using) into named blocks, where the named blocks each represents an element that's likely to be repeated, or contains specialist algorithms which can usefully or potentially be maintained by a separate person / group.
Here's definition of some code that repeats:
def ask(question="")
print "#{question}? "
result = gets.to_i
return result
end
and here's an example of calling that code:
delegates = ask "How many delegates"
This separation also starts moving you towards:
• a shorter and more readable piece of calling code
• separation of logic into multiple files, so that appropriate logic can be shared between programs
• an abiity to test the code in a modular way (by adding test points)
From last week's Ruby course - a short example showing the separation - [here]. Public Ruby course details [here].
The example also shows the use of optional parameters to a method in Ruby, with default values specified if they're not given in the call, how you can build variable and expression resuts within a Ruby string, and how you can turn your script into an executable program file when running on a Linux or Unix operating system host