I strongly encourage delagates on our courses to divide their code into managable, understandable, testable, re-usable chunks rather than write it all into a single block. And the adjectives I've used (managable, understandable, testable, re-usable) explain why.
You can process data within these chunks -
encapsulating the logic in there ... and indeed you can retain the data needed to be used by different chunks within the area of code that's included in the chunks so that after initially passing it in the programmer who
makes use of the chunks needed worry about managing that data, not indeed will (s)he have to understand what can be passed in and out where.
Let's see an example (in Python) ... here's some sample data being set up
numbers = [10,8,7,2]
Passinng the data into a series of named chunks of code -
functions - where each performs a task. A
good way to do things, but still the need to pass the data in to each of the named bloacks (functions).
avg = average(numbers)
r = ageRange(numbers)
print avg,r
If you pass the data in to a named set up chunk of code - a
constructor method which stored the data under some sort of handle (an instance variable), you can then access it as many times as you need though other
methods without having to keep passing in / managing the data on an ongoing basis.
andy = children(numbers)
avg2 = andy.getAverage()
r2 = andy.getRange()
print avg2,r2
In my first example code, I refrerred to the variable numbers
two times and if I had required to perform 10 operations, that would have been
ten references back to my original data. But in the second exanple I only referred to my data
one time and if I had been required to perform 10 operations, I would still only have had
one reference back to my original data. That saves me code, makes for clearer code and provides me with an environment in which its far harder to make silly logic errors.
• A name piece of code is called a
function
• A named piece of code that runs on a piece of stored data is called a
method
The complete code for the example above (showing definition and use of the function and method approach within the same source file) is
[here] - written to explain the difference on yesterday's
learning to program in Python course.
There are other advantages of using methods rather than functions too ...
• methods are limited to work on the right type of data, so you can have lots of methods all with the same name working on different data types. A big advantage when you put multiple programmer's code together and it turns out that two of you have used the same name.
• if you
intentionally use the same name for the same type of operation on different (but similar) data types, you can write common code to handle both data types at a higher level and your program will automatically select the right one to run at the right time. This is known as
polymorphism and saves a lot of coding using
switch and case and
if elseif elseif elseif else type structures.
There is an initial overhead in setting up objects, but in languages like Python this has been reduced toa tiny overhead and advise to new programmers / for new applications must be to use methods (which are excellent practise) rather than functions (which are good practise) most of the time. (written 2015-03-04, updated 2015-03-05)
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)
[3721] Naming blocks of code, structures and Object Orientation - efficient coding in manageable chunks - (2012-05-06)
[4021] Spike solution, refactored and reusable, Python - Example - (2013-02-28)
[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)
Y106 - Object Oriented Python [477] Class, static and unbound variables - (2005-10-25)
[834] Python makes University Challenge - (2006-08-15)
[900] Python - function v method - (2006-10-20)
[1306] Python class rattling around - (2007-08-16)
[1348] Screw it or Glue it? Access to Object variables - a warning - (2007-09-12)
[2017] Python - a truly dynamic language - (2009-01-30)
[2169] When should I use OO techniques? - (2009-05-11)
[2604] Tips for writing a test program (Ruby / Python / Java) - (2010-01-29)
[3085] Object Oriented Programming for Structured Programmers - conversion training - (2010-12-14)
[3399] From fish, loaves and apples to money, plastic cards and BACS (Perl references explained) - (2011-08-20)
[3673] Object oriented or structured - a comparison in Python. Also writing clean regular expressions - (2012-03-26)
[3878] From Structured to Object Oriented Programming. - (2012-10-02)
[3947] this or self - what are they, and what is the difference? (Python) - (2012-12-08)
[4028] Really Simple Class and Inheritance example in Python - (2013-03-04)
[4129] Simple OO demonstration in C++, comparison to Python - (2013-07-01)
[4721] When to check an object type - Python isinstance example - (2016-11-03)
Y105 - Python - Functions, Modules and Packages [96] Variable Scope - (2004-10-22)
[105] Distance Learning - (2004-10-31)
[294] Python generator functions, lambdas, and iterators - (2005-04-28)
[303] Lambdas in Python - (2005-05-06)
[308] Call by name v call by value - (2005-05-11)
[340] Code and code maintainance efficiency - (2005-06-08)
[386] What is a callback? - (2005-07-22)
[418] Difference between import and from in Python - (2005-08-18)
[561] Python's Generator functions - (2006-01-11)
[668] Python - block insets help with documentation - (2006-04-04)
[745] Python modules. The distribution, The Cheese Shop and the Vaults of Parnassus. - (2006-06-05)
[749] Cottage industry or production line data handling methods - (2006-06-07)
[775] Do not duplicate your code - (2006-06-23)
[821] Dynamic functions and names - Python - (2006-08-03)
[912] Recursion in Python - (2006-11-02)
[913] Python - A list of methods - (2006-11-03)
[949] Sludge off the mountain, and Python and PHP - (2006-11-27)
[959] It's the 1st, not the 1nd 1rd or 1th. - (2006-12-01)
[1134] Function / method parameters with * and ** in Python - (2007-04-04)
[1163] A better alternative to cutting and pasting code - (2007-04-26)
[1202] Returning multiple values from a function (Perl, PHP, Python) - (2007-05-24)
[1464] Python Script - easy examples of lots of basics - (2007-12-08)
[1784] Global - Tcl, PHP, Python - (2008-09-03)
[1790] Sharing variables with functions, but keeping them local too - Python - (2008-09-09)
[1869] Anonymous functions (lambdas) and map in Python - (2008-11-04)
[1870] What to do with a huge crop of apples - (2008-11-04)
[1871] Optional and named parameters in Python - (2008-11-05)
[1879] Dynamic code - Python - (2008-11-11)
[2011] Conversion of OSI grid references to Eastings and Northings - (2009-01-28)
[2439] Multiple returns from a function in Python - (2009-10-06)
[2440] Optional parameters to Python functions - (2009-10-07)
[2481] Sample code with errors in it on our web site - (2009-10-29)
[2506] Good example of recursion in Python - analyse an RSS feed - (2009-11-18)
[2520] Global and Enable - two misused words! - (2009-11-30)
[2718] Python - access to variables in the outer scope - (2010-04-12)
[2766] Optional and named parameters to Python functions/methods - (2010-05-15)
[2878] Program for reliability and efficiency - do not duplicate, but rather share and re-use - (2010-07-19)
[2929] Passing a variable number of parameters in to a function / method - (2010-08-20)
[2994] Python - some common questions answered in code examples - (2010-10-10)
[2998] Using an exception to initialise a static variable in a Python function / method - (2010-10-13)
[3159] Returning multiple values from a function call in various languages - a comparison - (2011-02-06)
[3280] Passing parameters to Python functions - the options you have - (2011-05-07)
[3459] Catching the fishes first? - (2011-09-27)
[3464] Passing optional and named parameters to python methods - (2011-10-04)
[3472] Static variables in functions - and better ways using objects - (2011-10-10)
[3474] Python Packages - groupings of modules. An introduction - (2011-10-11)
[3662] Finding all the unique lines in a file, using Python or Perl - (2012-03-20)
[3695] Functions are first class variables in Lua and Python - (2012-04-13)
[3766] Python timing - when to use a list, and when to use a generator - (2012-06-16)
[3852] Static variables in Python? - (2012-08-29)
[3885] Default local - a good choice by the author of Python - (2012-10-08)
[3931] Optional positional and named parameters in Python - (2012-11-23)
[3945] vargs in Python - how to call a method with unknown number of parameters - (2012-12-06)
[4029] Exception, Lambda, Generator, Slice, Dict - examples in one Python program - (2013-03-04)
[4161] Python varables - checking existance, and call by name or by value? - (2013-08-27)
[4212] Python functions - an introduction to how they work - (2013-11-16)
[4361] Multiple yields and no loops in a Python generator? - (2014-12-22)
[4407] Python - even named code blocks are objects - (2015-01-28)
[4410] A good example of recursion - a real use in Python - (2015-02-01)
[4441] Reading command line parameters in Python - (2015-02-23)
[4645] What are callbacks? Why use them? An example in Python - (2016-02-11)
[4662] Recursion in Python - the classic example - (2016-03-07)
[4719] Nesting decorators - (2016-11-02)
[4722] Embedding more complex code into a named block - (2016-11-04)
[4724] From and Import in Python - where is the module loaded from? - (2016-11-06)
Some other Articles
Binary data handling - Python and PerlRunning an operating system command from your Python program - the new way with the subprocess moduleDeciding whether to use parameters, conditional statements or subclassesSpike solution, refactoring into encapsulated object methods - good design practiseWhat is the difference between a function and a method?Overnight accommodation in Melksham - if Well House Manor is full!Combining tests into suites, and suites into bigger suites - Python and unittestGraphing presentations in Python - huge data, numpy and matplotlibElements of an exception in Python - try, except, else, finallySeventh stay away this year - and it's still only February!