[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

[FWP] Goal oriented programming



  The Perl style guide says you should put the important thing on the
  left, which is another way of saying you should try to make your goal
  clearer to the reader.
               -  Larry Wall

Some people rail against TMTOWTDI, claiming that new programmers should
have fewer choices. Recently, on a different list, we had a discussion that
I thought went a long way toward showing how TMTOWTDI supports
goal-oriented code. That is, first you stop to think what you want to do
(novel :-)... then you choose the WTDI that best represents the goal.

This C-like fragment came over another list recently.

   for ($i=1;$i <= length($line);$i++) {
      $num = ord(substr($line, $i, 1));
      if ($num > 127) {
        print ("ASCII value exceeds 127\n");
      }
   }

Sadly, the programmer didn't understand that Perl indices start at 0, so
this is not only C-like, it's wrong.

   for ($i=0; $i < length($line); $i++) {
       ...
   }

Even fixed for 0-indexed lists, this still has a distinct C feeling to it,
as other list members pointed out.

One of the other list members suggested this more Perlish replacement

    foreach (split //, $line) {
      $num = ord $_;
      $num > 127 and warn "ASCII value exceeds 127.\n";
    }


What I found most interesting when looking at the suggested replacement was
not just the change in the loop. One could as readily have written

    $i = 0;
    while ($i < length($line)) {

or

    for (0 .. length($line)-1) {

arguably setting $length = length($line) outside the loop. These would have
been more Perlish solutions.

Instead, I was interested in how the solution had moved from a simple
"count from here to there" loop to a structure that has no obvious counting
in it at all. It had moved from representing a goal of

    "loop over the numbers 0 to n, by 1, processing ..."
to
    "process each of the characters in the string, in turn"

The ability to refocus the goal (and Perl's language support to allow that)
seems to me the best defense of TMTOWTDI.
-- --
       |\      _,,,---,,_       Vicki Brown <vlb@cfcl.com>
 ZZZzz /,`.-'`'    -.  ;-;;,_   Journeyman Sourceror: Scripts & Philtres
      |,4-  ) )-,_. ,\ (  `'-'  P.O. Box 1269  San Bruno  CA  94066
     '---''(_/--'  `-'\_) http://www.cfcl.com/~vlb  http://www.macperl.com

==== Want to unsubscribe from Fun With Perl?
==== Well, if you insist... Send mail with body "unsubscribe" to
==== fwp-request@technofile.org