home *** CD-ROM | disk | FTP | other *** search
/ Netrunner 2004 October / NETRUNNER0410.ISO / regular / ActivePerl-5.8.4.810-MSWin32-x86.msi / _3d2da65b4fd9f319de477337e662fee0 < prev    next >
Text File  |  2004-06-01  |  32KB  |  685 lines

  1.  
  2. #Time-stamp: "2001-02-23 20:07:25 MST" -*-Text-*-
  3. # This document contains text in Perl "POD" format.
  4. # Use a POD viewer like perldoc or perlman to render it.
  5.  
  6. =head1 NAME
  7.  
  8. HTML::Tree::AboutObjects -- article: "User's View of Object-Oriented Modules"
  9.  
  10. =head1 SYNOPSIS
  11.  
  12.   # This an article, not a module.
  13.  
  14. =head1 DESCRIPTION
  15.  
  16. The following article by Sean M. Burke first appeared in I<The Perl
  17. Journal> #17 and is copyright 2000 The Perl Journal. It appears
  18. courtesy of Jon Orwant and The Perl Journal.  This document may be
  19. distributed under the same terms as Perl itself.
  20.  
  21. =head1 A User's View of Object-Oriented Modules
  22.  
  23. -- Sean M. Burke
  24.  
  25. The first time that most Perl programmers run into object-oriented
  26. programming when they need to use a module whose interface is
  27. object-oriented.  This is often a mystifying experience, since talk of
  28. "methods" and "constructors" is unintelligible to programmers who
  29. thought that functions and variables was all there was to worry about.
  30.  
  31. Articles and books that explain object-oriented programming (OOP), do so
  32. in terms of how to program that way.  That's understandable, and if you
  33. learn to write object-oriented code of your own, you'd find it easy to
  34. use object-oriented code that others write.  But this approach is the
  35. I<long> way around for people whose immediate goal is just to use
  36. existing object-oriented modules, but who don't yet want to know all the
  37. gory details of having to write such modules for themselves.
  38.  
  39. This article is for those programmers -- programmers who want to know
  40. about objects from the perspective of using object-oriented modules.
  41.  
  42. =head2 Modules and Their Functional Interfaces
  43.  
  44. Modules are the main way that Perl provides for bundling up code for
  45. later use by yourself or others.  As I'm sure you can't help noticing
  46. from reading
  47. I<The Perl Journal>, CPAN (the Comprehensive Perl Archive
  48. Network) is the repository for modules (or groups of modules) that
  49. others have written, to do anything from composing music to accessing
  50. Web pages.  A good deal of those modules even come with every
  51. installation of Perl.
  52.  
  53. One module that you may have used before, and which is fairly typical in
  54. its interface, is Text::Wrap.  It comes with Perl, so you don't even
  55. need to install it from CPAN.  You use it in a program of yours, by
  56. having your program code say early on:
  57.  
  58.   use Text::Wrap;
  59.  
  60. and after that, you can access a function called C<wrap>, which inserts
  61. line-breaks in text that you feed it, so that the text will be wrapped to
  62. seventy-two (or however many) columns.
  63.  
  64. The way this C<use Text::Wrap> business works is that the module
  65. Text::Wrap exists as a file "Text/Wrap.pm" somewhere in one of your
  66. library directories.  That file contains Perl code...
  67.  
  68. =over
  69.  
  70. Footnote: And mixed in with the Perl code, there's documentation, which
  71. is what you read with "perldoc Text::Wrap".  The perldoc program simply
  72. ignores the code and formats the documentation text, whereas "use
  73. Text::Wrap" loads and runs the code while ignoring the documentation.
  74.  
  75. =back
  76.  
  77. ...which, among other things, defines a function called C<Text::Wrap::wrap>,
  78. and then C<exports> that function, which means that when you say C<wrap>
  79. after having said "use Text::Wrap", you'll be actually calling the
  80. C<Text::Wrap::wrap> function.  Some modules don't export their
  81. functions, so you have to call them by their full name, like
  82. C<Text::Wrap::wrap(...parameters...)>.
  83.  
  84. Regardless of whether the typical module exports the functions it
  85. provides, a module is basically just a container for chunks of code that
  86. do useful things.  The way the module allows for you to interact with
  87. it, is its I<interface>.  And when, like with Text::Wrap, its interface
  88. consists of functions, the module is said to have a B<functional
  89. interface>.
  90.  
  91. =over
  92.  
  93. Footnote: the term "function" (and therefore "functionI<al>") has
  94. various senses.  I'm using the term here in its broadest sense, to
  95. refer to routines -- bits of code that are called by some name and
  96. which take parameters and return some value.
  97.  
  98. =back
  99.  
  100. Using modules with functional interfaces is straightforward -- instead
  101. of defining your own "wrap" function with C<sub wrap { ... }>, you
  102. entrust "use Text::Wrap" to do that for you, along with whatever other
  103. functions its defines and exports, according to the module's
  104. documentation.  Without too much bother, you can even write your own
  105. modules to contain your frequently used functions; I suggest having a look at
  106. the C<perlmod> man page for more leads on doing this.
  107.  
  108. =head2 Modules with Object-Oriented Interfaces
  109.  
  110. So suppose that one day you want to write a program that will automate
  111. the process of C<ftp>ing a bunch of files from one server down to your
  112. local machine, and then off to another server.
  113.  
  114. A quick browse through search.cpan.org turns up the module "Net::FTP",
  115. which you can download and install it using normal installation
  116. instructions (unless your sysadmin has already installed it, as many
  117. have).
  118.  
  119. Like Text::Wrap or any other module with a familiarly functional
  120. interface, you start off using Net::FTP in your program by saying:
  121.  
  122.   use Net::FTP;
  123.  
  124. However, that's where the similarity ends.  The first hint of
  125. difference is that the documentation for Net::FTP refers to it as a
  126. B<class>.  A class is a kind of module, but one that has an
  127. object-oriented interface.
  128.  
  129. Whereas modules like Text::Wrap
  130. provide bits of useful code as I<functions>, to be called like
  131. C<function(...parameters...)> or like
  132. C<PackageName::function(...parameters...)>, Net::FTP and other modules
  133. with object-oriented interfaces provide B<methods>.  Methods are sort of
  134. like functions in that they have a name and parameters; but methods
  135. look different, and are different, because you have to call them with a
  136. syntax that has a class name or an object as a special argument.  I'll
  137. explain the syntax for method calls, and then later explain what they
  138. all mean.
  139.  
  140. Some methods are meant to be called as B<class methods>, with the class
  141. name (same as the module name) as a special argument.  Class methods
  142. look like this:
  143.  
  144.   ClassName->methodname(parameter1, parameter2, ...)
  145.   ClassName->methodname()   # if no parameters
  146.   ClassName->methodname     # same as above
  147.  
  148. which you will sometimes see written:
  149.  
  150.   methodname ClassName (parameter1, parameter2, ...)
  151.   methodname ClassName      # if no parameters
  152.  
  153. Basically all class methods are for making new objects, and methods that
  154. make objects are called "B<constructors>" (and the process of making them
  155. is called "constructing" or "instantiating").  Constructor methods
  156. typically have the name "new", or something including "new"
  157. ("new_from_file", etc.); but they can conceivably be named
  158. anything -- DBI's constructor method is named "connect", for example.
  159.  
  160. The object that a constructor method returns is
  161. typically captured in a scalar variable:
  162.  
  163.   $object = ClassName->new(param1, param2...);
  164.  
  165. Once you have an object (more later on exactly what that is), you can
  166. use the other kind of method call syntax, the syntax for B<object method>
  167. calls.  Calling object methods is just like class methods, except
  168. that instead of the ClassName as the special argument,
  169. you use an expression that yeilds an "object".  Usually this is
  170. just a scalar variable that you earlier captured the
  171. output of the constructor in.  Object method calls look like this:
  172.  
  173.   $object->methodname(parameter1, parameter2, ...);
  174.   $object->methodname()   # if no parameters
  175.   $object->methodname     # same as above
  176.  
  177. which is occasionally written as:
  178.  
  179.   methodname $object (parameter1, parameter2, ...)
  180.   methodname $object      # if no parameters
  181.  
  182. Examples of method calls are:
  183.  
  184.   my $session1 = Net::FTP->new("ftp.myhost.com");
  185.     # Calls a class method "new", from class Net::FTP,
  186.     #  with the single parameter "ftp.myhost.com",
  187.     #  and saves the return value (which is, as usual,
  188.     #  an object), in $session1.
  189.     # Could also be written:
  190.     #  new Net::FTP('ftp.myhost.com')
  191.   $session1->login("sburke","aoeuaoeu")
  192.     || die "failed to login!\n";
  193.      # calling the object method "login"
  194.   print "Dir:\n", $session1->dir(), "\n";
  195.   $session1->quit;
  196.     # same as $session1->quit()
  197.   print "Done\n";
  198.   exit;
  199.  
  200. Incidentally, I suggest always using the syntaxes with parentheses and
  201. "->" in them,
  202.  
  203. =over
  204.  
  205. Footnote: the character-pair "->" is supposed to look like an
  206. arrow, not "negative greater-than"!
  207.  
  208. =back
  209.  
  210. and avoiding the syntaxes that start out "methodname $object" or
  211. "methodname ModuleName".  When everything's going right, they all mean
  212. the same thing as the "->" variants, but the syntax with "->" is more
  213. visually distinct from function calls, as well as being immune to some
  214. kinds of rare but puzzling ambiguities that can arise when you're trying
  215. to call methods that have the same name as subroutines you've defined.
  216.  
  217. But, syntactic alternatives aside, all this talk of constructing objects
  218. and object methods begs the question -- what I<is> an object?  There are
  219. several angles to this question that the rest of this article will
  220. answer in turn: what can you do with objects?  what's in an object?
  221. what's an object value?  and why do some modules use objects at all?
  222.  
  223. =head2 What Can You Do with Objects?
  224.  
  225. You've seen that you can make objects, and call object methods with
  226. them.  But what are object methods for?  The answer depends on the class:
  227.  
  228. A Net::FTP object represents a session between your computer and an FTP
  229. server.  So the methods you call on a Net::FTP object are for doing
  230. whatever you'd need to do across an FTP connection.  You make the
  231. session and log in:
  232.  
  233.   my $session = Net::FTP->new('ftp.aol.com');
  234.   die "Couldn't connect!" unless defined $session;
  235.     # The class method call to "new" will return
  236.     # the new object if it goes OK, otherwise it
  237.     # will return undef.
  238.  
  239.   $session->login('sburke', 'p@ssw3rD')
  240.    || die "Did I change my password again?";
  241.     # The object method "login" will give a true
  242.     # return value if actually logs in, otherwise
  243.     # it'll return false.
  244.  
  245. You can use the session object to change directory on that session:
  246.  
  247.   $session->cwd("/home/sburke/public_html")
  248.      || die "Hey, that was REALLY supposed to work!";
  249.    # if the cwd fails, it'll return false
  250.  
  251. ...get files from the machine at the other end of the session...
  252.  
  253.   foreach my $f ('log_report_ua.txt', 'log_report_dom.txt',
  254.                  'log_report_browsers.txt')
  255.   {
  256.     $session->get($f) || warn "Getting $f failed!"
  257.   };
  258.  
  259. ...and plenty else, ending finally with closing the connection:
  260.  
  261.   $session->quit();
  262.  
  263. In short, object methods are for doing things related to (or with)
  264. whatever the object represents.  For FTP sessions, it's about sending
  265. commands to the server at the other end of the connection, and that's
  266. about it -- there, methods are for doing something to the world outside
  267. the object, and the objects is just something that specifies what bit
  268. of the world (well, what FTP session) to act upon.
  269.  
  270. With most other classes, however, the object itself stores some kind of
  271. information, and it typically makes no sense to do things with such an
  272. object without considering the data that's in the object.
  273.  
  274. =head2 What's I<in> an Object?
  275.  
  276. An object is (with rare exceptions) a data structure containing a
  277. bunch of attributes, each of which has a value, as well as a name
  278. that you use when you
  279. read or set the attribute's value.  Some of the object's attributes are
  280. private, meaning you'll never see them documented because they're not
  281. for you to read or write; but most of the object's documented attributes
  282. are at least readable, and usually writeable, by you.  Net::FTP objects
  283. are a bit thin on attributes, so we'll use objects from the class
  284. Business::US_Amort for this example.  Business::US_Amort is a very
  285. simple class (available from CPAN) that I wrote for making calculations
  286. to do with loans (specifically, amortization, using US-style
  287. algorithms).
  288.  
  289. An object of the class Business::US_Amort represents a loan with
  290. particular parameters, i.e., attributes.  The most basic attributes of a
  291. "loan object" are its interest rate, its principal (how much money it's
  292. for), and it's term (how long it'll take to repay).  You need to set
  293. these attributes before anything else can be done with the object.  The
  294. way to get at those attributes for loan objects is just like the
  295. way to get at attributes for any class's objects: through accessors.
  296. An B<accessor> is simply any method that accesses (whether reading or
  297. writing, AKA getting or putting) some attribute in the given object.
  298. Moreover, accessors are the B<only> way that you can change
  299. an object's attributes.  (If a module's documentation wants you to
  300. know about any other way, it'll tell you.)
  301.  
  302. Usually, for simplicity's sake, an accessor is named after the attribute
  303. it reads or writes.  With Business::US_Amort objects, the accessors you
  304. need to use first are C<principal>, C<interest_rate>, and C<term>.
  305. Then, with at least those attributes set, you can call the C<run> method
  306. to figure out several things about the loan.  Then you can call various
  307. accessors, like C<total_paid_toward_interest>, to read the results:
  308.  
  309.   use Business::US_Amort;
  310.   my $loan = Business::US_Amort->new;
  311.   # Set the necessary attributes:
  312.   $loan->principal(123654);
  313.   $loan->interest_rate(9.25);
  314.   $loan->term(20); # twenty years
  315.  
  316.   # NOW we know enough to calculate:
  317.   $loan->run;
  318.  
  319.   # And see what came of that:
  320.   print
  321.     "Total paid toward interest: A WHOPPING ",
  322.     $loan->total_paid_interest, "!!\n";
  323.  
  324. This illustrates a convention that's common with accessors: calling the
  325. accessor with no arguments (as with $loan->total_paid_interest) usually
  326. means to read the value of that attribute, but providing a value (as
  327. with $loan->term(20)) means you want that attribute to be set to that
  328. value.  This stands to reason: why would you be providing a value, if
  329. not to set the attribute to that value?
  330.  
  331. Although a loan's term, principal, and interest rates are all single
  332. numeric values, an objects values can any kind of scalar, or an array,
  333. or even a hash.  Moreover, an attribute's value(s) can be objects
  334. themselves.  For example, consider MIDI files (as I wrote about in
  335. TPJ#13): a MIDI file usually consists of several tracks.  A MIDI file is
  336. complex enough to merit being an object with attributes like its overall
  337. tempo, the file-format variant it's in, and the list of instrument
  338. tracks in the file.  But tracks themselves are complex enough to be
  339. objects too, with attributes like their track-type, a list of MIDI
  340. commands if they're a MIDI track, or raw data if they're not.  So I
  341. ended up writing the MIDI modules so that the "tracks" attribute of a
  342. MIDI::Opus object is an array of objects from the class MIDI::Track.
  343. This may seem like a runaround -- you ask what's in one object, and get
  344. I<another> object, or several!  But in this case, it exactly reflects
  345. what the module is for -- MIDI files contain MIDI tracks, which then
  346. contain data.
  347.  
  348. =head2 What is an Object Value?
  349.  
  350. When you call a constructor like Net::FTP->new(I<hostname>), you get
  351. back an object value, a value you can later use, in combination with a
  352. method name, to call object methods.
  353.  
  354. Now, so far we've been pretending, in the above examples, that the
  355. variables $session or $loan I<are> the objects you're dealing with.
  356. This idea is innocuous up to a point, but it's really a misconception
  357. that will, at best, limit you in what you know how to do.  The reality
  358. is not that the variables $session or $query are objects; it's a little
  359. more indirect -- they I<hold> values that symbolize objects.  The kind of
  360. value that $session or $query hold is what I'm calling an object value.
  361.  
  362. To understand what kind of value this is, first think about the other
  363. kinds of scalar values you know about: The first two scalar values you
  364. probably ever ran into in Perl are B<numbers> and B<strings>, which you
  365. learned (or just assumed) will usually turn into each other on demand;
  366. that is, the three-character string "2.5" can become the quantity two
  367. and a half, and vice versa.  Then, especially if you started using
  368. C<perl -w> early on, you learned about the B<undefined value>, which can
  369. turn into 0 if you treat it as a number, or the empty-string if you
  370. treat it as a string.
  371.  
  372. =over
  373.  
  374. Footnote: You may I<also> have been learning about references, in which
  375. case you're ready to hear that object values are just a kind of
  376. reference, except that they reflect the class that created thing they point
  377. to, instead of merely being a plain old array reference, hash reference,
  378. etc.  I<If> this makes makes sense to you, and you want to know more
  379. about how objects are implemented in Perl, have a look at the
  380. C<perltoot> man page.
  381.  
  382. =back
  383.  
  384. And now you're learning about B<object values>.  An object value is a
  385. value that points to a data structure somewhere in memory, which is
  386. where all the attributes for this object are stored.  That data
  387. structure as a whole belongs to a class (probably the one you named in
  388. the constructor method, like ClassName->new), so that the object value
  389. can be used as part of object method calls.
  390.  
  391. If you want to actually I<see> what an object value is, you might try
  392. just saying "print $object".  That'll get you something like this:
  393.  
  394.   Net::FTP=GLOB(0x20154240)
  395.  
  396. or
  397.  
  398.   Business::US_Amort=HASH(0x15424020)
  399.  
  400. That's not very helpful if you wanted to really get at the object's
  401. insides, but that's because the object value is only a symbol for the
  402. object.  This may all sound very abstruse and metaphysical, so a
  403. real-world allegory might be very helpful:
  404.  
  405. =over
  406.  
  407. You get an advertisement in the mail saying that you have been
  408. (im)personally selected to have the rare privilege of applying for a
  409. credit card.  For whatever reason, I<this> offer sounds good to you, so you
  410. fill out the form and mail it back to the credit card company.  They
  411. gleefully approve the application and create your account, and send you
  412. a card with a number on it.
  413.  
  414. Now, you can do things with the number on that card -- clerks at stores
  415. can ring up things you want to buy, and charge your account by keying in
  416. the number on the card.  You can pay for things you order online by
  417. punching in the card number as part of your online order.  You can pay
  418. off part of the account by sending the credit card people some of your
  419. money (well, a check) with some note (usually the pre-printed slip)
  420. that has the card number for the account you want to pay toward.  And you
  421. should be able to call the credit card company's computer and ask it
  422. things about the card, like its balance, its credit limit, its APR, and
  423. maybe an itemization of recent purchases ad payments.
  424.  
  425. Now, what you're I<really> doing is manipulating a credit card
  426. I<account>, a completely abstract entity with some data attached to it
  427. (balance, APR, etc).  But for ease of access, you have a credit card
  428. I<number> that is a symbol for that account.  Now, that symbol is just a
  429. bunch of digits, and the number is effectively meaningless and useless
  430. in and of itself -- but in the appropriate context, it's understood to
  431. I<mean> the credit card account you're accessing.
  432.  
  433. This is exactly the relationship between objects and object values, and
  434. from this analogy, several facts about object values are a bit more
  435. explicable:
  436.  
  437. * An object value does nothing in and of itself, but it's useful when
  438. you use it in the context of an $object->method call, the same way that
  439. a card number is useful in the context of some operation dealing with a
  440. card account.
  441.  
  442. Moreover, several copies of the same object value all refer to the same
  443. object, the same way that making several copies of your card number
  444. won't change the fact that they all still refer to the same single
  445. account (this is true whether you're "copying" the number by just
  446. writing it down on different slips of paper, or whether you go to the
  447. trouble of forging exact replicas of your own plastic credit card).  That's
  448. why this:
  449.  
  450.   $x = Net::FTP->new("ftp.aol.com");
  451.   $x->login("sburke", "aoeuaoeu");
  452.  
  453. does the same thing as this:
  454.  
  455.   $x = Net::FTP->new("ftp.aol.com");
  456.   $y = $x;
  457.   $z = $y;
  458.   $z->login("sburke", "aoeuaoeu");
  459.  
  460. That is, $z and $y and $x are three different I<slots> for values,
  461. but what's in those slots are all object values pointing to the same
  462. object -- you don't have three different FTP connections, just three
  463. variables with values pointing to the some single FTP connection.
  464.  
  465. * You can't tell much of anything about the object just by looking at
  466. the object value, any more than you can see your credit account balance
  467. by holding the plastic card up to the light, or by adding up the digits
  468. in your credit card number.
  469.  
  470. * You can't just make up your own object values and have them work --
  471. they can come only from constructor methods of the appropriate class.
  472. Similarly, you get a credit card number I<only> by having a bank approve
  473. your application for a credit card account -- at which point I<they>
  474. let I<you> know what the number of your new card is.
  475.  
  476. Now, there's even more to the fact that you can't just make up your own
  477. object value: even though you can print an object value and get a string
  478. like "Net::FTP=GLOB(0x20154240)", that string is just a
  479. I<representation> of an object value.
  480.  
  481. Internally, an object value has a basically different type from a
  482. string, or a number, or the undefined value -- if $x holds a real
  483. string, then that value's slot in memory says "this is a value of type
  484. I<string>, and its characters are...", whereas if it's an object value,
  485. the value's slot in memory says, "this is a value of type I<reference>,
  486. and the location in memory that it points to is..." (and by looking at
  487. what's at that location, Perl can tell the class of what's there).
  488.  
  489. Perl programmers typically don't have to think about all these details
  490. of Perl's internals.  Many other languages force you to be more
  491. conscious of the differences between all of these (and also between
  492. types of numbers, which are stored differently depending on their size
  493. and whether they have fractional parts).  But Perl does its best to
  494. hide the different types of scalars from you -- it turns numbers into
  495. strings and back as needed, and takes the string or number
  496. representation of undef or of object values as needed.  However, you
  497. can't go from a string representation of an object value, back to an
  498. object value.  And that's why this doesn't work:
  499.  
  500.    $x = Net::FTP->new('ftp.aol.com');
  501.    $y = Net::FTP->new('ftp.netcom.com');
  502.    $z = Net::FTP->new('ftp.qualcomm.com');
  503.    $all = join(' ', $x,$y,$z);           # !!!
  504.   ...later...
  505.    ($aol, $netcom, $qualcomm) = split(' ', $all);  # !!!
  506.    $aol->login("sburke", "aoeuaoeu");
  507.    $netcom->login("sburke", "qjkxqjkx");
  508.    $qualcomm->login("smb", "dhtndhtn");
  509.  
  510. This fails because $aol ends up holding merely the B<string representation>
  511. of the object value from $x, not the object value itself -- when
  512. C<join> tried to join the characters of the "strings" $x, $y, and $z,
  513. Perl saw that they weren't strings at all, so it gave C<join> their
  514. string representations.
  515.  
  516. Unfortunately, this distinction between object values and their string
  517. representations doesn't really fit into the analogy of credit card
  518. numbers, because credit card numbers really I<are> numbers -- even
  519. thought they don't express any meaningful quantity, if you stored them
  520. in a database as a quantity (as opposed to just an ASCII string),
  521. that wouldn't stop them from being valid as credit card numbers.
  522.  
  523. This may seem rather academic, but there's there's two common mistakes
  524. programmers new to objects often make, which make sense only in terms of
  525. the distinction between object values and their string representations:
  526.  
  527. The first common error involves forgetting (or never having known in the
  528. first place) that when you go to use a value as a hash key, Perl uses
  529. the string representation of that value.  When you want to use the
  530. numeric value two and a half as a key, Perl turns it into the
  531. three-character string "2.5".  But if you then want to use that string
  532. as a number, Perl will treat it as meaning two and a half, so you're
  533. usually none the wiser that Perl converted the number to a string and
  534. back.  But recall that Perl can't turn strings back into objects -- so
  535. if you tried to use a Net::FTP object value as a hash key, Perl actually
  536. used its string representation, like "Net::FTP=GLOB(0x20154240)", but
  537. that string is unusable as an object value.  (Incidentally, there's
  538. a module Tie::RefHash that implements hashes that I<do> let you use
  539. real object-values as keys.)
  540.  
  541. The second common error with object values is in
  542. trying to save an object value to disk (whether printing it to a
  543. file, or storing it in a conventional database file).  All you'll get is the
  544. string, which will be useless.
  545.  
  546. When you want to save an object and restore it later, you may find that
  547. the object's class already provides a method specifically for this.  For
  548. example, MIDI::Opus provides methods for writing an object to disk as a
  549. standard MIDI file.  The file can later be read back into memory by
  550. a MIDI::Opus constructor method, which will return a new MIDI::Opus
  551. object representing whatever file you tell it to read into memory.
  552. Similar methods are available with, for example, classes that
  553. manipulate graphic images and can save them to files, which can be read
  554. back later.
  555.  
  556. But some classes, like Business::US_Amort, provide no such methods for
  557. storing an object in a file.  When this is the case, you can try
  558. using any of the Data::Dumper, Storable, or FreezeThaw modules.  Using
  559. these will be unproblematic for objects of most classes, but it may run
  560. into limitations with others.  For example, a Business::US_Amort
  561. object can be turned into a string with Data::Dumper, and that string
  562. written to a file.  When it's restored later, its attributes will be
  563. accessable as normal.  But in the unlikely case that the loan object was
  564. saved in mid-calculation, the calculation may not be resumable.  This is
  565. because of the way that that I<particular> class does its calculations,
  566. but similar limitations may occur with objects from other classses.
  567.  
  568. But often, even I<wanting> to save an object is basically wrong -- what would
  569. saving an ftp I<session> even mean?  Saving the hostname, username, and
  570. password?  current directory on both machines?  the local TCP/IP port
  571. number?  In the case of "saving" a Net::FTP object, you're better off
  572. just saving whatever details you actually need for your own purposes,
  573. so that you can make a new object later and just set those values for it.
  574.  
  575. =head2 So Why Do Some Modules Use Objects?
  576.  
  577. All these details of using objects are definitely enough to make you
  578. wonder -- is it worth the bother?  If you're a module author, writing
  579. your module with an object-oriented interface restricts the audience of
  580. potential users to those who understand the basic concepts of objects
  581. and object values, as well as Perl's syntax for calling methods.  Why
  582. complicate things by having an object-oriented interface?
  583.  
  584. A somewhat esoteric answer is that a module has an object-oriented
  585. interface because the module's insides are written in an
  586. object-oriented style.  This article is about the basics of
  587. object-oriented I<interfaces>, and it'd be going far afield to explain
  588. what object-oriented I<design> is.  But the short story is that
  589. object-oriented design is just one way of attacking messy problems.
  590. It's a way that many programmers find very helpful (and which others
  591. happen to find to be far more of a hassle than it's worth,
  592. incidentally), and it just happens to show up for you, the module user,
  593. as merely the style of interface.
  594.  
  595. But a simpler answer is that a functional interface is sometimes a
  596. hindrance, because it limits the number of things you can do at once --
  597. limiting it, in fact, to one.  For many problems that some modules are
  598. meant to solve, doing without an object-oriented interface would be like
  599. wishing that Perl didn't use filehandles.  The ideas are rather simpler
  600. -- just imagine that Perl let you access files, but I<only> one at a
  601. time, with code like:
  602.  
  603.   open("foo.txt") || die "Can't open foo.txt: $!";
  604.   while(readline) {
  605.     print $_ if /bar/;
  606.   }
  607.   close;
  608.  
  609. That hypothetical kind of Perl would be simpler, by doing without
  610. filehandles.  But you'd be out of luck if you wanted to read from
  611. one file while reading from another, or read from two and print to a
  612. third.
  613.  
  614. In the same way, a functional FTP module would be fine for just
  615. uploading files to one server at a time, but it wouldn't allow you to
  616. easily write programs that make need to use I<several> simultaneous
  617. sessions (like "look at server A and server B, and if A has a file
  618. called X.dat, then download it locally and then upload it to server B --
  619. except if B has a file called Y.dat, in which case do it the other way
  620. around").
  621.  
  622. Some kinds of problems that modules solve just lend themselves to an
  623. object-oriented interface.  For those kinds of tasks, a functional
  624. interface would be more familiar, but less powerful.  Learning to use
  625. object-oriented modules' interfaces does require becoming comfortable
  626. with the concepts from this article.  But in the end it will allow you
  627. to use a broader range of modules and, with them, to write programs
  628. that can do more.
  629.  
  630. B<[end body of article]>
  631.  
  632. =head2 [Author Credit]
  633.  
  634. Sean M. Burke has contributed several modules to CPAN, about half of
  635. them object-oriented.
  636.  
  637. [The next section should be in a greybox:]
  638.  
  639. =head2 The Gory Details
  640.  
  641. For sake of clarity of explanation, I had to oversimplify some of the
  642. facts about objects.  Here's a few of the gorier details:
  643.  
  644. * Every example I gave of a constructor was a class method.  But object
  645. methods can be constructors, too, if the class was written to work that
  646. way: $new = $old->copy, $node_y = $node_x->new_subnode, or the like.
  647.  
  648. * I've given the impression that there's two kinds of methods: object
  649. methods and class methods.  In fact, the same method can be both,
  650. because it's not the kind of method it is, but the kind of calls it's
  651. written to accept -- calls that pass an object, or calls that pass a
  652. class-name.
  653.  
  654. * The term "object value" isn't something you'll find used much anywhere
  655. else.  It's just my shorthand for what would properly be called an
  656. "object reference" or "reference to a blessed item".  In fact, people
  657. usually say "object" when they properly mean a reference to that object.
  658.  
  659. * I mentioned creating objects with I<con>structors, but I didn't
  660. mention destroying them with I<de>structor -- a destructor is a kind of
  661. method that you call to tidy up the object once you're done with it, and
  662. want it to neatly go away (close connections, delete temporary files,
  663. free up memory, etc).  But because of the way Perl handles memory,
  664. most modules won't require the user to know about destructors.
  665.  
  666. * I said that class method syntax has to have the class name, as in
  667. $session = B<Net::FTP>->new($host).  Actually, you can instead use any
  668. expression that returns a class name: $ftp_class = 'Net::FTP'; $session
  669. = B<$ftp_class>->new($host).  Moreover, instead of the method name for
  670. object- or class-method calls, you can use a scalar holding the method
  671. name: $foo->B<$method>($host).  But, in practice, these syntaxes are
  672. rarely useful.
  673.  
  674. And finally, to learn about objects from the perspective of writing
  675. your own classes, see the C<perltoot> documentation,
  676. or Damian Conway's exhaustive and clear book I<Object Oriented Perl>
  677. (Manning Publications 1999, ISBN 1-884777-79-1).
  678.  
  679. =head1 BACK
  680.  
  681. Return to the L<HTML::Tree|HTML::Tree> docs.
  682.  
  683. =cut
  684.  
  685.