Naming blocks of code, structures and Object Orientation - efficient coding in manageable chunks
Soon after you start to program, you'll learn that you want to re-use code. And that re-use will sometimes come in the form of loops, and at other times in the form of named blocks of code which you'll call up from multiple places in your program, or indeed from multiple programmers.
• A good programmer is a
lazy programmer, who won't want to redo work that (s)he has already done.
• A lazy programmer is an
efficient programmer, as that means better use of development time
• A program that was efficient to write because it only includes each piece of logic once is also an efficient program to
maintain through its life.
There's only one place in the code that needs amending as requirements are updated, or where unplanned circumstances need to be accommodated
How do named blocks of code work?
You'll come across words such as
functions,
subroutines,
macros,
procedures,
commands,
macros,
methods,
defs
callable objects and perhaps a few more,
and they all follow similar principles
1. In your program, you define one of these blocks of code and you give it a name. They syntax will vary from language to langauge.
1a. Within the named block, you will make use of a number of
parameters - values which are passed in to the named block for it to operate on.
1b. At the end of your block, you will provide a
return statement or value, which is the result that's provided to the calling code.
2. Within your main program, you will
call the named block.
2a. You will include in the call which values are to be passed in at that particular place when it runs.
2b. You will take the result that the named block returns and save it to a variable (or test it, or perform further logic on it) in your main program.
Here's an example in Python. Firstly - the definition of the named block:
def capacity(seats_per_vehicle, vehicles):
total_seats = seats_per_vehicle * vehicles
cap = int(total_seats * 1.4)
return cap
Then an example of its use:
hs125_v = 8
hs125_spv = 65
london = capacity(hs125_spv,hs125_v)
print "Capacity to London is",london
And another example of it use:
todays_length = int(raw_input("How many vehicles on the TransWilts? "))
salisbury = capacity(73,todays_length)
print "Capacity on the TransWilts to Salisbury is",salisbury
Sample output:
munchkin:rcp grahamellis$ python pyfunc
Capacity to London is 728
How many vehicles on the TransWilts? 2
Capacity on the TransWilts to Salisbury is 204
munchkin:rcp grahamellis$
The names that I've used in the function definition (seats_per_vehicle and vehicles) are generic names - in other words, a common name that might be applied to any set of values passed in when considering the functionallity that's being provided.
The names used in the calling code are more specific - and indeed they can be variables, constant values, or even expressions.
The values passed in are position dependent. The function requires two paramaters in this example, so the call must be made with two values. The first of these values is passed into the first named parameter, and the second value is passed into the second named parameter.
In most langauges (including Python, used above, and C and C++, below), variablenames within the named block of code are in a different
namespace to variables in the main code. In other words, it doesn't matter what names are used within the function - they can't be seen in the calling code. They could even be the same names, but they're actually different memory location.
Think of it like forenames and surnames. I talk about "John", but "John Smith" and "John Brown" are different people.
But there's very often much more than just two numbers to be passed into a function - you'll very often have a whole raft of values and the calling sequence would expand from one or two parameters to a very much higher number if something better wasn't done.
As a starting point for this demonstration, I've placed a C function definition and used in a sample program
[here]. The function has two parameters - a width and a height:
float getdoggie(float w, float h) {
float rv;
if (w > h) {
rv = h/2.0;
}
else {
rv = w/2.0;
}
return rv;
}
and so it's called with two parameters:
d = getdoggie(w,h);
Using a
structure in C, we can gather all of the values we want to handle in our function into a group, and simply pass in the group (or, better, the address of the group) into the function. Sample code
[here].
Structure definition:
typedef struct {
int width;
int height;
char *material; } table;
The function definition then has only a single parameter:
float getdoggie(table current) {
float rv;
if (current.width > current.height) {
rv = current.height/2.0; }
else {
rv = current.width/2.0; }
return rv; }
and it's called with a single parameter:
d = getdoggie(mytable);
With a structure, it's still possible to call a function on the wrong type of structure, and each function name can only be used once. By adding the object oriented language facilities of C++, we can also associate named blocks of code with particular pieces of data. Not only does this tighten up on possible erroneous use, but it provides a separate namespace. And in turn that leads to us being able to share code within truely massive programs, but have that code well segmented for tested and maintainance purposes. The full example showing this from
last week's C and C++ course is shown
[here].
Here's the function definition:
float Table::getdoggie() {
float rv;
rv = ((this->width > this->height) ?
this->height : this-> width ) /2.0;
return rv;
}
and the call to it:
float reach = dining.getdoggie();
cout << "Dog Reach " << reach << endl;
The next series of public C and C++ courses runs in mid July ... if you're coming late to this article, though - don't worry. The course runs again in the autumn, and there will be three or four opportunities next year too
[schedule]. If you've got a group of 4 or 5 (or more) delegates, it's probably more cost effective for us to run a private course for you; that way, the course can be tuned to the exact background and target application of your delegate group.
(written 2012-05-06, updated 2012-05-12)
Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articles
Q906 - Object Orientation and General technical topics - Object Orientation: Individual Objects [227] Bellringing and Programming and Objects and Perl - (2005-02-25)
[507] Introduction to Object Oriented Programming - (2005-11-27)
[1543] Learning Object Oriented Principles (and perhaps Java) - (2008-02-17)
[1864] Object Oriented Perl - First Steps - (2008-11-01)
[1925] Introduction to Object Oriented Programming - (2008-12-06)
[2171] Cleaning up redundant objects - (2009-05-11)
[2173] Basic OO principles - (2009-05-11)
[2393] A first demonstration of OO, including polymorphism - (2009-09-04)
[2651] Calculation within objects - early, last minute, or cached? - (2010-02-26)
[3436] Moving from scripting to Object Orientation in Python - (2011-09-13)
[4021] Spike solution, refactored and reusable, Python - Example - (2013-02-28)
[4448] What is the difference between a function and a method? - (2015-03-04)
[4591] From single block to structure and object oriented programming - (2015-12-02)
[4650] Why populate object with values as you construct them? - (2016-02-18)
C232 - C and C based languages - Defining and using classes in C++ [2577] Complete teaching example - C++, inheritance, polymorphism - (2010-01-15)
[2578] Where are your objects stored in C++? - (2010-01-16)
[2579] Creating, setting up and using objects in C++ - (2010-01-16)
[3250] C++ - how we teach the language and the concepts behind the language - (2011-04-17)
[3716] Learning C++ - a design pattern for your first class - (2012-05-02)
[3810] Reading files, and using factories to create vectors of objects from the data in C++ - (2012-07-21)
[3978] Teaching OO - how to avoid lots of window switching early on - (2013-01-17)
[4129] Simple OO demonstration in C++, comparison to Python - (2013-07-01)
[4372] Template / design pattern for C++ constructor and accessors - (2014-12-29)
[4565] Allocation of memory for objects in C++ - Stack v Heap - (2015-10-31)
C204 - C and C based languages - Functions, Macros and programs in multiple files [775] Do not duplicate your code - (2006-06-23)
[1163] A better alternative to cutting and pasting code - (2007-04-26)
[1478] Some new C programming examples - files, structs, unions etc - (2007-12-19)
[2570] Function Prototypes in C - (2010-01-11)
[2575] Sharing variables between files of code in C - extern - (2010-01-14)
[2841] C Course exercise and sample answer - source in 2 files - (2010-06-30)
[3237] Using functions to keep look and feel apart from calculations - simple C example - (2011-04-09)
[3717] Returning extra results from a function in C - (2012-05-03)
[4338] Passing arrays into functions in C - (2014-12-02)
[4554] Passing information into functions in C - by name, by value - (2015-10-26)
[4555] Preprocessor directives in C and C++ - what they mean - (2015-10-27)
[4557] Function prototype - what they are and why you should use them - C and C++ - (2015-10-27)
Some other Articles
Lua TablesLearning to Program in Lua - public / open training course / classBank Holiday Monday, so it was pouring with rain.Walking by the wiverNaming blocks of code, structures and Object Orientation - efficient coding in manageable chunksMelksham ATC - freedom of the townStrawberry Cream Teas, Well House Manor, Melksham, starting this weekendSplitting a record into individual data values in C