Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

When to use modules?

by wolfi (Scribe)
on Mar 22, 2004 at 06:42 UTC ( [id://338572]=perlmeditation: print w/replies, xml ) Need Help??

i've had this little, meandering thought, so i thought, i'd just toss it out here.

up 'til now, (being a newbie,) i've been writing my code directly -> not using any modules. But in looking thru the SOPW, many questions involved the use of these modules, and it seems like every monk uses them regularly.

now, i know, that perl-programmers love short code. The less writing, the better. I know, that modules are used to avoid 'reinventing the wheel', as they say - as well as importing complex and long lines of code into a script by using but a few words.

so, i was surprised to find, that some of the most popular uses of these modules, requires the same amount of code or more - to call it - than just to simply write it out yourself.

an example (based on an example from CGI Programming with Perl pg 287 / O'Reilly):

example#1: CGI.pm ~

my $cookie = $q->cookie( -name => "cart_id", -value => 12345, -domain => ".oreilly.com", -expires => "+1y", -path => "/cgi", -secure => 1 ); print "Set-Cookie: $cookie\n";

example#2: normal (inline) synatx ~

print "Set-Cookie: cart_id=12345; domain=".oreilly.com"; path=/cgi; ex +pires=+1d; secure\n";

CGI.pm looks a tad longer.

But even if they were equal in length - isn't it better to do #2 and incorporate this directing into your script, rather than #1, which requires perl to do a whole other set of routines/processes (opening CGI.pm, looking for the code, resolving any variables there, and merging it into the 'main' script to arrive at the same result.) ...?

does it make that much difference or am i splitting hairs?

20040322 Edit by BazB: Changed title from 'To Import or Not To Import'

Replies are listed 'Best First'.
Re: When to use modules?
by revdiablo (Prior) on Mar 22, 2004 at 07:17 UTC
    does it make that much difference or am i splitting hairs?

    Well, in this particular case, you might be splitting hairs a bit, but behind the superficial face of your question lies a much bigger one. That is, should I use a module, or write my own equivalent code? I think the answer to that depends on the situation, but I'd bet more often or not the module is the way to go.

    There are many reasons, and this has been discussed at great length in the past, but for me the biggest reason is bugginess. Code has bugs; this is a fact. Using a module often helps mitigate the effect of this problem. Perhaps you could argue that the extra complexity of a module adds the chance for even more bugs, but I would counter that the most egregious bugs are of the semantic variety. These are the kind that modules are great for. Once discovered, fixing the module fixes the bug everywhere. It's an instant win, and a compelling reason to stick with the module over the (possibly simpler) hard-coded solution.

    As a final note, I should mention that arguing against modules, per se, in terms of efficiency is almost always a losing proposition. In this case, I would bet dollars to cents that the time it takes to send the cookie over the network is an order of magnitude higher than the time it takes to generate the cookie, module or not.

Re: To Use a Module or Not
by chromatic (Archbishop) on Mar 22, 2004 at 07:12 UTC

    The savings are not in making the easy things easier. They're in making the hard things easy and the impossible things merely difficult.

    If your problem's too easy to solve with a module, go ahead and do it yourself. Few problems worth solving stay that simple though.

Re: When to use modules?
by Aragorn (Curate) on Mar 22, 2004 at 11:07 UTC
    I don't think this is a good example. I can't imagine that your script uses cookies without any form decoding, page formatting or interaction with a file or database of some sort. You do all these things by hand too? The cookie function does a lot of things you neglect in your simple print statement, like entity encoding and expiry date processing. Also, your statement is short, but also plain wrong (no doublequote escaping).

    now, i know, that perl-programmers love short code. The less writing, the better.
    I can only speak for myself, but I suspect that lots of other Perl programmers agree with my if I say that the quote above is false. I like clear code. In Perl, that often goes hand in hand with short code because of the expressiveness of the language. I like Perl "golfing", but not in production code where I (and the team I work with) have to maintain it. There, I strive to create solid, clear, maintainable code.

    Most of the time, modules take a lot of work out of your hands and let you concentrate on the problem you're trying to solve. I probably could write a database interface or XML parser if I wanted to, but very capable people already have done so, excellently I think, and let me focus on the problems I have to deal with.

    Arjen

Re: When to use modules?
by astroboy (Chaplain) on Mar 22, 2004 at 10:57 UTC

    When I first started learning Perl, I did things via first principles too. In fact, I used to do things the same way I did in UNIX shell scripts. For instance, I used "system" to host out of my Perl script to call Oracle utilities to load data into a database, because that's what I did with ksh. Now I use DBI (unless I have very high volumes of data)

    The fact is, modules make the hard things possible. After spending 6 months writing everything I did from scratch, I bought a copy of The Perl Cookbook. If you haven't got it yourself, then you should get it asap. Scan the contents and see how many recipes you could write without using modules. The fact is, excluding trivial examples, modules enable you to connect to databases and mail servers, to write network servers and clients, parse languages, create and process graphics and pdf files, and interface with any number of commercial products. Try doing any of these from scratch!

    BTW: why use CGI.pm? Have a look at Use CGI or die by Ovid

Re: When to use modules?
by dragonchild (Archbishop) on Mar 22, 2004 at 14:02 UTC
    Modules and why one must use them. Hrmmm ...

    The reason you should use a module is because someone else much smarter than you has figured out the stupid details so that you don't have to learn it, understand it, and remember it. More importantly, when the stupid details change (as they always will), you don't have to even be aware that they changed. The module will DWIM and life will be good.

    Let's take your example. Others have already mentioned dealing with timezones and other headers being outputted. I'm going to go further and say "What if you're potentially not always dealing with HTML?" Sounds stupid? Maybe not ...

    I'm starting to design a Data-Access Layer (DAL) for interfacing two completely disparate applications (one in Perl, the other in Java) onto the same database. For ease of development, I'm going to use Apache as the server and use XML as the messaging structure. It will be very HTTP-like in that the client will send a request and the server will send a response. I can see using the concept of cookies to aid usage of the DAL from both the Perl and the Java sides. Maybe, a CGI-like module is written to use the same interface?

    Ok, maybe that wasn't as believable. But, how about this one? I just wrote a generalized datastream handler. It doesn't make any assumptions about the type of the file, if you give it a filehandle. This allows me to use IO::File, IO::Zlib, and any other IO::* module, plus typeglobs and stuff returned by open().

    Modules provide interfaces. If two modules conform to the same interface, they can be treated the same way. This is why IO::All is so powerful (and is even possible!)

    ------
    We are the carpenters and bricklayers of the Information Age.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

      The reason you should use a module is because someone else much smarter than you has figured out the stupid details...
      Not always smarter -- just less lazy :)

      In other words -- the wheel has already been invented, and the wheel is found to be good. But wheels are simple, and you could probably build a wheel, but you are building a car instead. You should never reuse square wheels, of course. But the part about not having to deal with 'stupid details' is absolutely right. It's all about not having to worry about stuff that you know you could re-implement (like wheels or spark plugs -- Lambourghini doesn't make spark plugs, do they?).

      Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. I like those best. Ah, what a good job...

        I would like to note that although new modules are sometimes (ok very often) buggy, They are put to heavy use by the community. This use tends to find and fix those bugs fairly quickly. (This is one of the benefits of Open Source Software as mentioned in The Cathedral and the Bazaar.)
Re: When to use modules?
by Abigail-II (Bishop) on Mar 22, 2004 at 10:34 UTC
    What's your point actually? You give one little example, using one function of a large, but no so great, module with a gazillion functions. Sure, the example as you give it doesn't save you much in keystrokes. But you can't make a general case about using modules or not based on a single example.

    It's like arguing doesn't need elevators because it's easier to step off the side walk on the pavement than using an elevator to do the same.

    Abigail

Re: When to use modules?
by Anonymous Monk on Mar 22, 2004 at 07:20 UTC

    LMAO, just look at your "inline syntax". You've proven yourself why you should use CGI. 'expires=+1d' is not a valid cookie expiration. When you pass '+1d' as an expiration date/time to cookie(), a valid date format is created out of that. Not to mention your inline style doesn't output a 'Date' header to accommodate for timezone differences... So yes, use CGI (or one of its equivalents such as CGI::Simple).

      Oops, I failed to notice that your CGI version does a manual header output, so it too misses out on the 'Date' header. You should be using print $q->header(-cookie => $cookie); to output the headers.

        The server (apache etc) will usually add the 'Date:' header for you, so it is not needed. Try perl -MCGI -e'print CGI::header()'.

        Your other points remain valid though.

Re: When to use modules?
by flyingmoose (Priest) on Mar 22, 2004 at 13:10 UTC
    Your thread title is slightly misleading. You say "To import or not to import", which made me think of modules and namespaces. Anyway...

    Writing functions (and reusing code) and using modules is a basic tenet of good programming practice. Good programming has never been about keeping code long or short -- it's about what is the most flexible, safe, or feature rich -- balancing requirements.

    The only time to 'inline' something would be when the function call was expensive (to save CPU load or equivalent), and here running time is not a major concern. If you were doing math, this might be different.

    Of course, quick and dirty scripts are allowed to have their way in many occasions, but you incur risks if they grow to be something important, so it all matters what your approach is.

    If you are trying to write 'good' code though, 'good' and 'short' are orthogonal. Often good can be short, but short is not always good. Good is usually clean, neat, and non-kludgy however. If you find a lot of error checking code making your program harder to read, move it to a function so you can keep your code clean -- but don't remove that code just because it makes the code shorter. In the case of your CGI example, I really don't find that syntax ugly at all, though I usually format my code so the dashes and arrows line up, at minimum. It makes me feel good:

    my $cookie = $q->cookie( -name => "cart_id", -value => 12345, -domain => ".oreilly.com", -expires => "+1y", -path => "/cgi", -secure => 1 ); print "Set-Cookie: $cookie\n";

    Silly, yes, but it makes that long code block seem fun and awe-inspiring. Ok, maybe not, but at least it's more readable -- especially when you want to start putting dollar signs in there.

Re: When to use modules?
by wolfi (Scribe) on Mar 22, 2004 at 08:12 UTC

    i won't argue with the anonymous monk, since any syntax errors were irrelevant to the my question.

    nor was i trying to detract from the value of modules. I just had a thought dealing with the simpler code i'm working with... and wished to share it...

    but thank you chromatic and revdiablo for your comments and the time spent in responding :-) I would agree with the points you made.

      i won't argue with the anonymous monk, since any syntax errors were irrelevant to the my question.

      Actually, our good friend Anonymous Monk perfectly proved the point I was trying to make. While there were indeed syntax errors in your sample code, that's easy to fix. The worse problem in your code was the semantic error. Namely, '+1d' is not a valid date for a cookie expiration. Support for that is built into the module, such that any code that feeds '+1d' into the cookie function gets the "fix" (or in this case, "feature" would probably be more accurate), and a valid date is put in its place. Now, you could probably code up your own subroutine to convert a string like '+1d' into a valid datestamp, but that code could have other bugs. And all your earlier simplicity is thrown out the window. This is exactly what we're trying to avoid with code re-use.

      thank you ... for your comments and the time spent in responding

      And thank you for asking an interesting question. Even though this discussion goes on again and again, it's still useful to bring up every now and then. Perhaps some Monks get tired of it, but, personally, I enjoy talking about things like this. Even more when it might benefit a newbie, recently embarked on his long and adventerous journey that is learning to program in Perl. :-)

Re: When to use modules?
by wolfi (Scribe) on Mar 23, 2004 at 12:20 UTC

    well, this all got started, because i'm working on a project, where i may not have access to install modules on the server - this, and the fact of me being new to perl, well - for this first project, i figured, i should do all the code myself. (Not because i like to work more, mind you, but because it's also about learning perl terms, structure, syntax, etc.)

    so, when i began cross-referencing these smallest tidbits of code, (and I know, my code up above is messed up, but i hope, you get the idea about what i was referring to) and well, the thought was... if i should really be using X module, if it's only going to be used once - or some small amount of time - during a script.

    Was a meditation, if you will - and why i placed it here, rather that in the SOPW section.

    but you all have given me a lot to chew over; Things which i had not considered. So, thanks to everyone again for the insight into the world of modules - and your time in sharing your ideas.

    happy coding *wink*

    :-)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://338572]
Approved by arden
Front-paged by Courage
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-04-26 00:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found