approach to writing functions

Peter Hansen peter at engcorp.com
Tue Feb 10 11:27:29 EST 2004


Bart Nessux wrote:
> 
> fp0 = os.popen("/sbin/ifconfig en0 inet", "r")
> fp1 = os.popen("/usr/bin/uptime", "r")
> fp2 = os.popen("/usr/bin/uname -a", "r")
> fp3 = os.popen("/usr/bin/wc -l /etc/passwd", "r")
> msg = MIMEText("-- IFCONFIG --\n\n" + fp0.read() + "\n-- UPTIME --\n\n"
> +  fp1.read() + "\n-- UNAME --\n\n" + fp2.read() + "\n-- PASSWD LC
> --\n\n" + fp3.read())
> fp0.close()
> fp1.close()
> fp2.close()
> fp3.close()

This sequence has duplication, so it could stand some refactoring.  Write
a routine that executes a command and returns the result, then call it
with various commands, something like this:

def cmd(c):
    f = os.popen(c, 'r')
    try:
        result = f.read()
    finally:
        f.close()
    return result

responses = [cmd(c) for c in
    ['/sbin/ifconfig en0 inet', '/usr/bin/uptime', '/usr/bin/uname -a',
     '/usb/bin/wc -l /etc/passwd']]

msg = MIMEText('blah %s, blah %s, blah %s, blah %s' % responses)

That's only one example of what you could do to simplify/make reusable
code.

The best thing I know of to decide when to make a function is when you have
code that is about to take responsibility for two different things.  Your
code has responsibility for setting up user info, retrieving command output,
execute four commands, generating the mail body from the results, 
setting up the entire mail message, and sending the mail message.  That's
six different areas of responsibility (give or take) and there should
probably be at least three or four functions in there to handle some
of those in a cleaner fashion.

Always ask yourself "what is this chunk of code responsible for?"  If
the answer is more than one thing, consider splitting it up.  This is,
by the way, effectively the concept of "cohesion", and you would do well
to learn about "cohesion" and "coupling".  You always strive for low
coupling (connections between different things) and high cohesion 
(responsibility for only closely related things) in code, if you 
want clean design.

-Peter



More information about the Python-list mailing list