[Tutor] Organizing my code, should I use functions?

Alan Gauld alan.gauld at btinternet.com
Wed Apr 22 17:52:49 CEST 2009


"Eduardo Vieira" <eduardo.susan at gmail.com> wrote 

> ....I simply decided to alter the code as little as
> possible and use the import statement. It's working this way. 
> Sounds wise? 

Its an acceptab;e approach bwhen you are doing exactly 
the same thing, but its not a very flexible approach and 
leaves you very vulnerable if you get a change that only 
applies to one of your solutions.


> I thought if I converted it to a function or a class would make
> it more flexible, 

A set of functions is probably sufficient from the sounds 
of things. That way you can mix n match the functions, 
pass in different arguments etc to get the same 
functionality but with more control.

> functions out of everything. I'm still too much attached to
> procedural, not functional programming, if I understand the terms
> correctly. 

procedural programming is where you use procedures 
or functions to accomplish the task. You link those functions 
together, either in a top level function or in global level cotrol 
script. This is also (more correctly) known as imperative style 
programming.

functional programming is quite different and comprises 
a set of rules about how the code should be structured.
In functional programming the whole program is a function 
that returns a value. Every function should return a value and 
functions should not alter any global data. Every function 
should ideally be an expression. No stateful constructs 
such as loops or assignment statements should be used 
(repetition is done via recursion). In practice most folks 
relax the rules a little and allow simple loops (ie using 
a counter as in 

for n in range(n))

and some assignments. But the ideal is to build a program with 
no state and everything done as an expression with nested sub 
expressions. It is very closely aligned with formal methods in 
Computer Science and formal languages such as Z or VDM

For most programmers functional programming is at least 
as big a conceptual leap from procedural or imperative 
programming as OOP.

I'll comment on the code separately.


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list