approach to writing functions

Paul Prescod paul at prescod.net
Tue Feb 10 01:53:40 EST 2004


Bart Nessux wrote:

> I understand that most people write functions to reuse code, no? So, I
> assume it would be better to write functions that are very specific, as
> opposed to those that are more generic. 
> 
> However, I have difficulty doing this. My code doesn't need to be
> super-modular (I don't need functions that can be used in dozens of
> different programs). So, my functions don't tend to be portbale and can
> sometimes span one, or perhaps two pages.

It's sort of a self-fulfilling prophecy. If you don't try to write 
reusable functions your code won't be reusable.

But, to be fair to you, it is harder to find code to reuse in Python 
than in lower-level languages because so much comes out of the box.

Even so, I very rarely write a program that does not reuse code in one 
way or another. Do you find that there are chunks of text that are 
almost identical sprinkled throughout your program?

> Say I have a program that contains no functions. Say that it is all global
> and it's written like a shell script. Say that it does what I intend it to
> do exactly. More experienced programmers fuss that I have not used
> functions to write it. They complain about global variables, etc. But, when
> I use functions and enclose everything in a one big function, I am in
> essence doing exactly what I was doing globally.

If the logic is simple, what you are doing is not necessarily bad style. 
But if the logic is complicated then eschewing functions can make it 
more, not less, complicated. For one thing you get so many indentation 
levels that it becomes hard to keep it in your head. For another thing, 
when you try to read your code six months from now it will not be in 
bite-sized bits you can keep in your head but rather in one long stream. 
  Imagine a university textbook without chapters. It is somewhat harder 
to navigate the one long stream. By convention, programmers use 
functions as "chapters."

> What do you guys think?

If I were you I would post one of these scripts and see if the function 
and OO fans can make it easier to read or maintain by using structured 
programming.

  Paul Prescod






More information about the Python-list mailing list