473,750 Members | 2,170 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

approach to writing functions

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.

Is this wrong? I know functions were not intended for this, but if I don't
use them in this manner, I might as well do everything globally, and I
don't see any difference in the two approaches.

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.

Just asking for a bit of guidance. If my program works, should it be
re-written to use functions or classes? Isn't Python flexible enough to
allow for many approaches to how it is used? I mean, I know nothing of OO
programming, but Python is still a *very* useful language to me *and* to
the programmer who is an OO god. So, can't there be room for all
approaches... the formal, enlightened, abstract method of the gods and the
informal, pragmatic, get-it-done method of the common man?

What do you guys think?
Jul 18 '05 #1
17 1506
On Mon, 09 Feb 2004 21:22:27 -0500, Bart Nessux wrote:
I understand that most people write functions to reuse code, no?
No. I write functions to make complex code sequences more simple --
i.e. for abstraction. Parcel up the behaviour that can conceptually be
considered a single action, and put it away in a function.

This has the valuable benefit that the function can then be re-used in
other places needing the same action; but that's not the reason I write
them to begin with.
So, I assume it would be better to write functions that are very
specific, as opposed to those that are more generic.
I've no idea how "re-use the code" leads you to think of more specific
functions -- surely the trend would be to more *generic* functions, that
can thus be re-used in more places?
Is this wrong? I know functions were not intended for this, but if I
don't use them in this manner, I might as well do everything globally,
and I don't see any difference in the two approaches.


I recommend you get a copy of Code Complete (Steve McConnell, published
by Microsoft Press). It is an extremely comprehensive and approachable
tome on the actual practice of writing code.

In particular, it explains just about every reason to use abstraction in
data, code and algorithms. Some you may have heard before, but my
feeling from your message is that a lot of it will be new -- and all of
it is valuable.

--
\ "If you go to a costume party at your boss's house, wouldn't |
`\ you think a good costume would be to dress up like the boss's |
_o__) wife? Trust me, it's not." -- Jack Handey |
Ben Finney <http://bignose.squidly .org/>
Jul 18 '05 #2
Ben Finney wrote:
I've no idea how "re-use the code" leads you to think of more specific
functions -- surely the trend would be to more *generic* functions, that
can thus be re-used in more places?
Yes, I got that part backwards. I meant generic. Thank you for pointing it
out. I'm dyslexic. To me, left is right and right is left. I work a lot
with files and file systems in general. I have a function that counts the
number of objects in a FS and returns that. It's very generic and can be
used with most any py script that needs to know how many FS objects are in
a certain path before doing something else.
I recommend you get a copy of Code Complete (Steve McConnell, published
by Microsoft Press). It is an extremely comprehensive and approachable
tome on the actual practice of writing code.

In particular, it explains just about every reason to use abstraction in
data, code and algorithms. Some you may have heard before, but my
feeling from your message is that a lot of it will be new -- and all of
it is valuable.


Thank you, I'll look into this
Jul 18 '05 #3

"Bart Nessux" <ba*********@ho tmail.com> wrote in message
news:c0******** **@solaris.cc.v t.edu...
I understand that most people write functions to reuse code, no?
Another reason is to define, name, and embody a concept, even if the
function is only used once.
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.
Are you in a position where you *have* to let such people read your code?
Just asking for a bit of guidance. If my program works, should it be
re-written to use functions or classes?
Working correctly is most important. Next is running fast enough. Then
you can consider whether you or another person can read, edit, or reuse six
months from now. As for rewriting, would *you* gain some personal benefit
from doing so?
Isn't Python flexible enough to allow for many approaches to how it is

used?

The language itself is. So are most users, I believe. It is intentionally
not a straightjacket language, even though some people find freedom from
braces to be constricting.

Python was made for people, not people for Python. Ditto for programming
theories.

Terry J. Reedy


Jul 18 '05 #4
Terry Reedy wrote:
"Bart Nessux" <ba*********@ho tmail.com> wrote in message
news:c0******** **@solaris.cc.v t.edu...
I understand that most people write functions to reuse code, no?


Another reason is to define, name, and embody a concept, even if the
function is only used once.


Another reason is that you need a callable object, whether it embodies some
high level concept or not.
--
Rainer Deyke - ra*****@eldwood .com - http://eldwood.com
Jul 18 '05 #5
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

Jul 18 '05 #6
On Mon, 09 Feb 2004 22:53:40 -0800, Paul Prescod wrote:
Imagine a university textbook without chapters. It is somewhat harder
to navigate the one long stream. By convention, programmers use
functions as "chapters."


Naah. The modules are the "chapters". Classes are "sections", and
functions are "subsection s".

And every sentence should fit on one 80-column line, or be broken into
multiple sentences that do.

--
\ "The trouble with Communism is the Communists, just as the |
`\ trouble with Christianity is the Christians." -- Henry L. |
_o__) Mencken |
Ben Finney <http://bignose.squidly .org/>
Jul 18 '05 #7
"Terry Reedy" <tj*****@udel.e du> wrote:

[bart]
Just asking for a bit of guidance. If my program works, should it be
re-written to use functions or classes?


Working correctly is most important. Next is running fast enough. Then
you can consider whether you or another person can read, edit, or reuse six
months from now. As for rewriting, would *you* gain some personal benefit
from doing so?


I disagree with the order in which you list these things, but that
might be caused by whether one sees Python as a language to express
ideas or as a tool to accomplish a more specific task. For example I
am not a native English speaker, but I guess nobody would think it
more important to avoid all spelling errors than to get the idea
across.

Posting scripts and ideas that are in this stadium is a bit dangerous
and one may end up with some egg (or pie!) in ones face, but since
software development is promoted most by removing errors in the
*early* stages it's a good strategy I think. Of course this shouldn't
result in long posts here with completely unqualified code.

However, asking specific questions about smaller functions is better
than posting 100+ lines of code and requesting that someone explains
why the script doesn't do what it is meant to do while it is still
unclear what a poster really wants the script to do.

While developing code I'm imagining a herd of virtual Python gurus
looking over my shoulder assisting me and requiring my code to be
readable ...

What I am trying to say is that if one develops code *as if* posting
it here, errors are detected sooner. And later errors are more costly
than early errors.

Anyway, I want more people to post code, even if it is not perfect!

Only after a lot of "eyeballing " and splitting the code up into
functions one should go to the next phase of testing the script for
possible errors and behavior in worst case scenarios. Of course Python
also accommodates for a grand unified style of programming, and both
styles can add value.

In the end well tested Python scripts often are readable and "obvious"
whichever method is used to produce them, which I think is a nice
effect of readable computer languages in general.

Anton
Jul 18 '05 #8
Paul Prescod wrote:
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.


OK, here is a script that works w/o OO or functions. It's very useful...
never fails. It helps sys admins track machines that have mobile users
who are using DHCP.

#!/usr/bin/python
#
# Tested on Linux Machines
# Run as cron as root
# May work on OS X too
#
# Dec 29, 2003 works on Mac OSX 10.3 like this:
# chown 'root' && chgrp 'wheel' && chmod '755'
# place in /usr/bin
#

from email.MIMEText import MIMEText
import smtplib
import os

u = "User" #Change This to user's name.
f = "ad***@XXX. edu"
t = "ad***@XXX. edu"

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()

msg["Subject"] = "%s's ifconfig Report" % u
msg["From"] = f
msg["To"] = t

h = "smtp.vt.ed u"
s = smtplib.SMTP(h)
s.sendmail(f, t, msg.as_string() )
s.quit()

Jul 18 '05 #9

"Anton Vredegoor" <an***@vredegoo r.doge.nl> wrote in message
news:40******** **************@ reader1.nntp.hc cnet.nl...
"Terry Reedy" <tj*****@udel.e du> wrote:

[bart]
Just asking for a bit of guidance. If my program works, should it be
re-written to use functions or classes?
Working correctly is most important. Next is running fast enough. Then
you can consider whether you or another person can read, edit, or reuse sixmonths from now. As for rewriting, would *you* gain some personal benefitfrom doing so?


I disagree with the order in which you list these things, but that
might be caused by whether one sees Python as a language to express
ideas or as a tool to accomplish a more specific task.


I gather you are putting my list in the second category. I see Python as
being excellent for both uses, and I think that part of its excellence is
that it works both ways as executable humancode.

The OP was asking about specific-task production code. I believe that he
should first be praised for meeting the prime directive for such, that it
work correctly, before being critiqued for secondary stylistic goals.
For example I
am not a native English speaker, but I guess nobody would think it
more important to avoid all spelling errors than to get the idea
across.


When writing to communicate ideas to other people, 'working correctly'
means successful communication of the intended idea. For this reason, I
sometimes post untested code that may not be exactly right but which
communicates an idea. But when I do so, I label it as 'untested' or
'something like' to communicate that it is idea-passing code rather than
tested execution code.

Terry J. Reedy


Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
1510
by: Chinook | last post by:
OO approach to decision sequence? --------------------------------- In a recent thread (Cause for using objects?), Chris Smith replied with (in part): > If your table of photo data has several types of photos, and you find > yourself saying > > if is_mugshot:
6
1858
by: Paul | last post by:
Hi. Just trying to find out the best approach as I beleive it might give me problems later on down the road. I have an ASP.NET application which references a shared database class which contains methods for serialising and de-serialising objects to the database storage. I put this as a shared class as multiple web clients will be using the class to store and retreive data, the problem I'm haivng now is that I think multiple threads...
2
2256
by: Rene | last post by:
Hi, In my VB6 application I'm using a class/object that is using full-async ADO. I can start multiple queries, the class stores the ADODB.Recordset object in an array and waits for the QueryComplete event. This will set the result and flag 'the query is finished' in the array. In my WaitForResult() method I wait till the flag 'query is finished' is set and return to the caller. While waiting I'm calling DoEvents and delay
2
1204
by: Mr Newbie | last post by:
I've just spent some considerable time putting together an application which works pretty much OK. The issue I have around design is mainly concerned with the Data Access layer. Yes, we can pull data modify it etc, but the code required to do so is not inconsequential, and the many functions one finds onself writing do mount up. All this is OK until you find you need to change a type or add or remove a field, everything has to change...
102
7116
by: Xah Lee | last post by:
i had the pleasure to read the PHP's manual today. http://www.php.net/manual/en/ although Pretty Home Page is another criminal hack of the unix lineage, but if we are here to judge the quality of its documentation, it is a impeccability. it has or possesses properties of:
5
1394
by: gw7rib | last post by:
I'm writing a program which has "notes" - these can appear on the screen as windows with text in. It is possible to create an "index note" - at present, this will contain a list of the titles (or other data, you can choose) of some or all of the notes - you can choose the selection criteria. Thus you can create notes to store any text you want to, in a relatively free manner, but you can easily fish out all the notes relating to some...
1
1254
by: =?Utf-8?B?Tkg=?= | last post by:
Hi, I have been building asp.net 2.0 apps now for a few years. In general I use MS Ajax and the MS Data Enterprise Application Block to manage the connecting and getting data from the database. My apps work very well espiecially with the introduction of MS Ajax. However, I dont take the normal OO approach. Obviously the .Net framework is OO based but when writing apps I take a different approach to what is the norm I'd imagine....
20
3089
by: mike3 | last post by:
Hi. (Xposted to both comp.lang.c++ and comp.programming since I've got questions related to both C++ language and general programming) I've got the following C++ code. The first routine runs in like 65% of the time of the second routine. Yet both do the same thing. However, the second one seems better in terms of the way the code is written since it helps encapsulate the transformation in the inner loop better making it easier to read,...
0
954
by: =?Utf-8?B?UGV0ZXIgUml0Y2hpZSBbQyMgTVZQXQ==?= | last post by:
You should never WaitForMultipleObjets or WaitForSingleObject on a GUI thread (unless there's a very short timeout). Creating another thread to perform the blocking (calling WaitFor...) is the recommended approach. -- Browse http://connect.microsoft.com/VisualStudio/feedback/ and vote. http://www.peterRitchie.com/blog/ Microsoft MVP, Visual Developer - Visual C#
0
8999
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8836
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9256
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8260
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6803
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4712
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3322
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2798
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2223
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.