Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Why use HTML instead of CGI? (code, discussion)

by deprecated (Priest)
on May 08, 2001 at 04:35 UTC ( [id://78733]=perlmeditation: print w/replies, xml ) Need Help??

I am writing code for a new client who has some "interesting" code. I am worried I will say too much and jeopardize my position there, so I will be as vague as I can be.

None of the code uses -T, -Mstrict, or -w. Furthermore, most of it is written in a manner like this:

print <<'HTML"; <html> <head><title>Email This Article to a Friend</title></head> <center> <b>The following fields are missing or inproperly filled </b> + </center> <p> <hr> error_fields <p> <hr> <p> Please use the <b>back</b> button on your browser to return and comple +te the form. </body> <html> HTML
instead of
sub error_mf_page { print header, start_html( "Email This Article to a Friend" ), p( {-align => 'center'}, b( "The following fields are missing or improperly filled" +) ), p(), hr(), "@error_fields", p(), hr(), p(), "Please use the", b( " back " ), "button on your browser to return and complete the form.", end_html; }
The scripts (around 200 or so) are littered with HTML, and filehandles that point to html files in various directories (with special variable names and the like which are s///'d in at compile time).

This code is so unmaintainable it makes me ill to work in it. I was originally brought in to write some new programs, and add some functionality, as well as diagnose and test some problems they were having. The deeper you look, the more problems you see. You cant just go in and actually write new code, because it takes you four hours to figure out what the current code is actually doing.

So my question for the monastery then is, is there actually any advantage to writing code like this? To embedding html into perl scripts rather than using it the way its supposed to be (i.e., perl is perl, html is html, keep them separate)? The code is written by good programmers, they have a firm concept of the way programming is done. But they lack any organized and consistent style, and to quote the senior developer, "I forget how it works, but as long as it works, thats the way it is." Did I miss the class on lapse-of-ethics when I was learning programming in college?

Has anyone else gone through a massive code-audit like this?

thanks
brother dep.

--
Laziness, Impatience, Hubris, and Generosity.

Replies are listed 'Best First'.
Re: Why use HTML instead of CGI? (codediscussion)
by Masem (Monsignor) on May 08, 2001 at 04:50 UTC
    I think what you're seeing is the evolution of improving CGI scripts. Before php was big, few thought of separating code and content (at least, the few that most CGI programmers payed attention to), and thus we see lots of HTML embedded in perl (including here documents and the CGI functions). PHP came along, which pushed the other direction, the inclusion of code into the HTML. Perl answered with tools like embedded perl and such, but many still saw this as a mess. Thus the development of all the templating libraries (HTML::Template, TT2, etc), which given the previous two solutions, is the most apparent way to do it best.

    I wouldn't necessarily blame the original programmers, as CGI programming techniques have developed over the years, and templating has only been 'in' for the last few years. However, if your task is to determine what needs to be done, you need to strongly push that templating will make the code easier to maintain and expand in the future.


    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
(dws)Re: Why use HTML instead of CGI? (codediscussion)
by dws (Chancellor) on May 08, 2001 at 04:58 UTC
    is there actually any advantage to writing code like this?

    The "advantage" was probably one of not exceeding the original author's capabilities. It might have been a case of "you do what you can with what you have". Getting a simple page working, and then copy the HTML into a CGI is a pretty simple way to get started, though longer term maintenance is a hassle.

    Time passes. The original author gets more competent, or a new, more competent developer (you) comes along.

    It's now a business decision as to whether investing time to clean this code up, say, by separating the HTML out into templates, makes sense. Your task is to provide management with information about the cost of the status quo (high on-going maintenance) versus the cost of a rewrite (some cost now, lower ongoing maintenance).

    They may weigh the risks and decide on status quo.

Re: Why use HTML instead of CGI? (codediscussion)
by stephen (Priest) on May 08, 2001 at 06:29 UTC
    I'm doing something very similar; I'm on a large Perl project that I'm trying to make intelligible. I'd add the following pieces of advice:
    • Write automated unit tests. (See Test and Refactoring.) Run them frequently.
    • Don't try to put all of the HTML into templates in one gigantic effort. Work a bit at a time, interspersing your refactoring efforts with adding new features to keep your managers happy.
    • Make sure that you get buy-in from your fellow developers. It does little good for you to be fixing old code when new code is being written with embedded HTML.
    • Write automated unit tests. Run them frequently. (Okay, but it's important!)

    stephen

Re: Why use HTML instead of CGI? (codediscussion)
by Anonymous Monk on May 08, 2001 at 06:16 UTC
    To me, the embedded HTML is very easy to read. The CGI.pm code is harder to read.

    Why does it matter whether I say "<p>hello</p>" or p("hello")? Either way the HTML is defined by the Perl script. There is a one-to-one correspondence between the embedded HTML solution and the CGI.pm solution.

    The question of which is easier to maintain depends upon who is maintaining it. Many of us have been looking at HTML for years and can read it very easily.

Re: Why use HTML instead of CGI? (codediscussion)
by novitiate (Scribe) on May 08, 2001 at 08:30 UTC
    There's more than one _WAY_, brother dep. -- you know that.
    Seriously though, I would be apt to find the functional interface
    to CGI.pm messy as compared to the
    OO interface; but that's my preference - not merlin's,
    who seems to dislike the OO int. of CGI.pm as (flaky|messy|quirky)
    don't quote me there, i can't rememeber exactly what he said.
    The point here is preference and style.
    For me, a lot of perl code I see is highly stylistic b/c of perl's flexibility, like a natural language.
    Imagine edting/re-wrting someone else's fiction ? It can be tough,
    comments that lead the way can ease the pain, but some art
    requires patience and TLC.
Re: Why use HTML instead of CGI? (codediscussion)
by thpfft (Chaplain) on May 08, 2001 at 16:45 UTC

    I'm inclined to disagree with both approaches show here, if that's any help. As someone else pointed out, the html is in there even when written in CGI.pm notation.

    It's not that perl is perl, as you put it: i think the rule should be more abstract: 'programming is programming and presentation is presentation'. the scripts should deal with data, and if a public face is involved then leave the designers to design it and just hand them the data later. It's good politics, apart from anything else.

    If it's any comfort, i go through this sort of audit/replace/reject all the time, and it's much more painful when the person who wrote the idiot spaghetti was you and it was only six months ago and you thought it was kind of cool at the time :(

      While I find coding HTML with CGI.pm cumbersome, I can think of a couple reasons why you might want to use it.

      Most scripts just gather input, validate and process one form.

      By utilizing CGI.pm, you can bring error handling and presentation up a notch.

      I recently wrote a simple module that inherets from CGI that allows me to register informational error messages for any missing/bad parameters with "error bullets" that are automatically displayed next to any form element registered with CGI.pm. (Also keeps track of colspans from the previous row so I don't hard code it. Makes maintainence easier.)

      All screens functions can do "double duty" (form/error respones) so usually you can have a one to one match between screens and functions.

      This would be a big pain to do without CGI or something else to handle HTML generation.

      I think an approach like this works very well as interfaces get bigger.

      I wrote a 10,000 line product/order management CGI interface for a fairly big (now defunct) dot com mixing and matching perl and html because CGI.pm's syntax was too cumbersome for me (I was too lazy).

      While I hacked it out in a couple days, enhancements where a huge headache.

      Below is a pretty trivial example but it doesn't take much longer to code it this way than to do it the down and dirty way and I think it is much cleaner. Everything is in one nice spot. The following example is at http://smb.yso.net/cgi-bin/silly.pl
      #!/usr/bin/perl # silly.pl # http://smb.yso.net/cgi-bin/silly.pl use CGI::ParamError qw(:standard :html3); my $q = new CGI::ParamError; # REQUIRED FIELDS # first_name last_name email print header(); unless (param()){ display_form(); }else{ unless (param('first_name')=~/\w/){ param_error('first_name',"Sorry, I need to know your first nam +e"); } unless (param('last_name')=~/\w/){ param_error('last_name',"Sorry, I need to know your last name" +); } unless (param('email')=~/^\w+\@\w+\.\w/){ param_error('email',"Sorry, param('email') doesn't seem like a + valid email"); } if ($q->has_errors){ display_form(); }else{ # DO SOMETHING HERE confirmation(); } } ######################################### sub display_form{ # show_error_messages() is part of my module, this is where the ve +rbose messages are displayed # Should be called AFTER fields are validated. print start_html(-title=>'Silly Script'), show_error_message(), start_form, "First Name",textfield(-name=>'first_name'),br, "Last Name",textfield(-name=>'last_name'),br, "Your Email",textfield(-name=>'email'),br, submit,br, end_form, end_html; } ######################################### sub confirmation{ print start_html(-title=>'Silly Script'), "Thanks for stopping by ",param('first_name')," ",param('last_ +name'),"!"; end_html; }
Re: Why use HTML instead of CGI? (codediscussion)
by snellm (Monk) on May 08, 2001 at 17:06 UTC
    IMHO it's always best to use seperate HTML template files, for at least two very good reasons:
    • Logical seperation of code and layout. Implementation of new designs, browser specific page etc becomes fairly trivial.
    • Ease of maintenance, especially if the HTML files are updated by non Perl-literate folk.

    Template Toolkit is a popular choice.

    -- Michael Snell
    -- michael@snell.com

Re: Why use HTML instead of CGI? (codediscussion)
by buckaduck (Chaplain) on May 09, 2001 at 02:04 UTC
    Consider this from the point of view of the Perl novice. Here's an example of an HTML table from the CGI documentation:
    print table({-border=>undef}, caption('When Should You Eat Your Vegetables?'), Tr({-align=>CENTER,-valign=>TOP}, [ th(['Vegetable', 'Breakfast','Lunch','Dinner']), td(['Tomatoes' , 'no', 'yes', 'yes']), td(['Broccoli' , 'no', 'no', 'yes']), td(['Onions' , 'yes','yes', 'yes']) ] ) );
    Not so bad as it stands, as long as you understand array references and hash references. But what if you don't? Early in my Perl career I gave up in frustration in the middle of some nested tables and just cut-and-pasted some existing HTML code. And it worked.

    I wouldn't do that today (in fact, I would probably now use a module such as HTML::Table or Data::Table for most HTML tables), and I have since revised most of my older code. But I'll admit that there were times when I used plain HTML to just get the job done. Not because I thought it was superior, but because I was still learning. And there's nothing wrong with that. (I hope.)

    buckaduck

Re: Why use HTML instead of CGI? (codediscussion)
by DrZaius (Monk) on May 08, 2001 at 18:36 UTC
    First off, there are no advantages to either of these formats.

    I believe that presentation changes 4 times before functionality, so with both of these examples, your html monkeys/programmers have the potentional to be playing with your cgi scripts and introducing errors.

    I am currently moving 2 medium sized sites and 10 or so minor sites that are written in a similar format. They all have to be changed as this style does not scale when you have many developers.

    If you want to be successful in moving your site, first you need to convince the people who influence the budgets. Then, you need to get a 'top down' view of all the functionality your websites offer.

    Once you are done this, you should be able to simplify and make you job a lot easier. Chances are, especially in our case, there is probably a lot more code than you really need.

    The less you have to write, the less time it will take. This may sound redundant, but think of the fact you will be maintaining the old system and writing a new system at the same time.

    cheers

Re: Why use HTML instead of CGI? (codediscussion)
by Maclir (Curate) on May 09, 2001 at 02:52 UTC

    Well, Brother Dep, you are probably between a rock and a hard place. I am going through a very similar process where I am, redesigning an organisation's internet and intranet web sites. Each has 200 plus pages, generally "static" - with the exception that maintenance has become a nightmare.

    I will be using EmbPerl::Object. This allows several things - a site to be built from reusable components (standard headers and footers, navigation bars and all that), and the seperation of perl code from html code. The HTML stuff still looks like HTML stuff, and the web writing people are stull happy. The perl code uses EmbPerl - which makes use of CGI.pm under its own covers.

    Now, that does not solve your immediate problems, which as I see it is summed up by:

    to quote the senior developer, "I forget how it works, but as long as it works, thats the way it is."
    It doesn't matter what the develoment environment is - everythime I hear that, I have visions of huge impending disasters. Think Pompei with smoke at the top of Mount Vesuvius. Think S.S. Titanic and "hey, there are a few icebergs around tonight". Think General Custer and "I can't see any indians here".

    You may be able to propose a transition from the current methods, to some form of templating - it really doesn't matter which one, they all are much better than your current situation. Then, when a particular page / module needs to be modified, convert it to the new architecture.

    Good luck - I think you are going to need it.

    Update: Thanks, deprecated, for reminding me how to spell Pompei.

Re: Why use HTML instead of CGI? (codediscussion)
by thabenksta (Pilgrim) on May 08, 2001 at 23:25 UTC

    CGI.pm is a very usefull tool, it's great for form data parsing, making dropdown menus, writing cookies, and so on. But, personally I don't like using it for formatting all html output, to me it just complicates things. And If a non-programmer has to get in and change something, they are out of luck. I see absolutley nothing wrong with printing out straight html.

    However, as many have mentioned above, Templating is a very nice option. I have started using templates for many reasons. One, the designers don't have to touch my code at all, they just make a pretty little html file and I run that through my program. Two, you can open html templates in GUI editors. While I still do most of my editing in TextPad, sometimes it's just faster and more efficient to do things in dreamweaver. Three, the code just looks better and is easier to manage when you don't have hundreds of lines of HTML to sift through. There are of course more advantages than that, but that was enough to change my mind.

    -thabenksta
    my $name = 'Ben Kittrell'; $name=~s/^(.+)\s(.).+$/\L$1$2/g; my $nick = 'tha' . $name . 'sta';
      CGI.pm is a very usefull tool, it's great for form data parsing, making dropdown menus, writing cookies, and so on. But, personally I don't like using it for formatting all html output, to me it just complicates things. And If a non-programmer has to get in and change something, they are out of luck. I see absolutley nothing wrong with printing out straight html.

      Maybe we could get Dreamweaver to output CGI.pm code...

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (7)
As of 2024-04-19 07:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found