home *** CD-ROM | disk | FTP | other *** search
/ Source Code 1994 March / Source_Code_CD-ROM_Walnut_Creek_March_1994.iso / gnu / smltlktr.txt < prev    next >
Text File  |  1993-02-26  |  140KB  |  3,697 lines

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.                           AA TTuuttoorriiaall ffoorr GGNNUU SSmmaallllttaallkk
  11.  
  12.                                 _A_n_d_r_e_w _V_a_l_e_n_c_i_a
  13.                               Valencia Consulting
  14.  
  15.  
  16.  
  17.  
  18.           OOvveerrvviieeww
  19.  
  20.           WWhhaatt tthhiiss mmaannuuaall pprreesseennttss
  21.                This  document  provides a tutorial introduction to the
  22.           Smalltalk language in general, and the GNU Smalltalk  imple-
  23.           mentation  in  particular.   It  does not provide exhaustive
  24.           coverage of every feature of the language and its libraries;
  25.           instead,  it  attempts to introduce a critical mass of ideas
  26.           and techniques to get the Smalltalk  novice  moving  in  the
  27.           right direction.
  28.  
  29.           WWhhoo tthhiiss mmaannuuaall iiss wwrriitttteenn ffoorr
  30.                This  manual assumes that the reader is acquainted with
  31.           the basics of computer science, and  has  reasonable  profi-
  32.           ciency  with  a  procedural  language  such  as  _C.  It also
  33.           assumes that the reader is already familiar with  the  usual
  34.           janitorial tasks associated with programming-editing, moving
  35.           files, and so forth.
  36.  
  37.           11..  GGeettttiinngg ssttaarrtteedd
  38.  
  39.           11..11..  SSttaarrttiinngg uupp SSmmaallllttaallkk
  40.                Assuming that GNU Smalltalk has been installed on  your
  41.           system, starting it is as simple as:
  42.                % mst
  43.           the system loads in Smalltalk, and displays a startup banner
  44.           like:
  45.                Smalltalk 1.1.1 Ready
  46.  
  47.                st>
  48.           You are now ready to try your hand  at  Smalltalk!   By  the
  49.           way, when you're ready to quit, you exit Smalltalk by typing
  50.           control-D on an empty line.
  51.  
  52.           11..22..  SSaayyiinngg hheelllloo
  53.                An initial exercise is to make Smalltalk say "hello" to
  54.           you.   Type in the following line ("printNl" is a upper case
  55.           N and a lower case L):
  56.                 'Hello, world' printNl !
  57.           The system then prints back 'Hello, world' to you.1
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.                                        -2-
  71.  
  72.  
  73.           11..33..  WWhhaatt aaccttuuaallllyy hhaappppeenneedd
  74.                The  front-line  Smalltalk interpreter gathers all text
  75.           until a '!'  character  and  executes  it.   So  the  actual
  76.           Smalltalk code executed was:
  77.                 'Hello, world' printNl
  78.           This  code  does two things.  First, it creates an object of
  79.           type "String" which contains the characters "Hello,  world".
  80.           Second,  it sends the message named "printNl" to the object.
  81.           When the object is done processing the message, the code  is
  82.           done and we get our prompt back.
  83.                You'll  notice that we didn't say anything about print-
  84.           ing the string, even though that's in  fact  what  happened.
  85.           This  was  very much on purpose-the code we typed in _d_o_e_s_n'_t
  86.           _k_n_o_w _a_n_y_t_h_i_n_g _a_b_o_u_t _p_r_i_n_t_i_n_g _s_t_r_i_n_g_s.  It knew how to get  a
  87.           string  object,  and  it  knew how to send a message to that
  88.           object.  That's the end of the story for the code we  wrote.
  89.           But  for  fun,  let's  take a look at what happened when the
  90.           string object received the "printNl" message.
  91.  
  92.           11..44..  WWhhaatt aa ssttrriinngg ddooeess wwiitthh aa ""pprriinnttNNll"" mmeessssaaggee
  93.                The string object containing "Hello,  world"  was  sent
  94.           the message "printNl".  It then goes to a table2 which lists
  95.  
  96.  
  97.  
  98.             1 It  also  prints  out  a  lot  of  statistics.
  99.  
  100.  
  101.           Ignore these; they provide information on the per-
  102.  
  103.  
  104.           formance of the underlying Smalltalk engine.   You
  105.  
  106.  
  107.           can inhibit them by starting Smalltalk as:
  108.  
  109.  
  110.                % mst -q
  111.  
  112.  
  113.             2 Which  table?   This is determined by the type
  114.  
  115.  
  116.           of the object.  An object has a type, known as the
  117.  
  118.  
  119.           _c_l_a_s_s to which it belongs.  Each class has a table
  120.  
  121.  
  122.           of methods.  For the  object  we  created,  it  is
  123.  
  124.  
  125.           known as a member of the "String" class.  So we go
  126.  
  127.  
  128.  
  129.  
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136.                                        -3-
  137.  
  138.  
  139.           the  messages  which  strings  can receive, and what code to
  140.           execute.  It  finds  that  there  is  indeed  an  entry  for
  141.           "printNl"  and runs this code.  This code then walks through
  142.           its  characters, printing each of them out to the terminal.3
  143.           The central point  is  that  an  object  is  entirely  self-
  144.           contained;  only  the  object  knew how to print itself out.
  145.           When we want an object to  print  out,  we  ask  the  object
  146.           itself to do the printing.
  147.  
  148.           11..55..  DDooiinngg mmaatthh
  149.                A similar piece of code prints numbers:
  150.                1234 printNl !
  151.           Notice  how  we used the same message, but have sent it to a
  152.           new type of object-an integer (from class  "Integer").   The
  153.           way  in  which  an integer is printed is much different from
  154.           the way a string is printed on the inside,  but  because  we
  155.           are  just  sending  a message, we do not have to be aware of
  156.           this.  We tell it to "printNl", and it prints itself out.
  157.                As a _u_s_e_r of an object, we can thus usually send a par-
  158.           ticular message and expect basically the same kind of behav-
  159.           ior,  regardless  of  object's   internal   structure   (for
  160.           instance,  we  have seen that sending "printNl" to an object
  161.           makes the object print itself).  In later chapters  we  will
  162.           see  a  wide range of types of objects.  Yet all of them can
  163.           be printed out the same way-with "printNl".
  164.                White space is ignored, except as it  separates  words.
  165.           This example could also have looked like:
  166.                           1234
  167.                 printNl          !
  168.                An integer can be sent a number of messages in addition
  169.           to just printing itself.  An important set of  messages  for
  170.           integers are the ones which do math:
  171.  
  172.  
  173.  
  174.           to the table associated with the String class.
  175.  
  176.  
  177.             3 Actually, the message "printNl" was  inherited
  178.  
  179.  
  180.           from  Object.   It  sent  a  "print" message, also
  181.  
  182.  
  183.           inherited by Object, which then sent "printOn:" to
  184.  
  185.  
  186.           the  object, specifying that it print to "stdout".
  187.  
  188.  
  189.           The String class then prints its characters to the
  190.  
  191.  
  192.           standard output.
  193.  
  194.  
  195.  
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.                                        -4-
  203.  
  204.  
  205.                (9 + 7) printNl !
  206.           Answers  (correctly!)  the  value  16.  The way that it does
  207.           this, however, is a significant departure from a  procedural
  208.           language.
  209.  
  210.           11..66..  MMaatthh iinn SSmmaallllttaallkk
  211.                In this case, what happened was that the object "9" (an
  212.           Integer), received a "+" message with  an  argument  of  "7"
  213.           (also an Integer).  The "+" message for integers then caused
  214.           Smalltalk to create a new object "16" and return it  as  the
  215.           resultant  object.   This  "16"  object  was  then given the
  216.           "printNl" message, and printed "16" on the terminal.
  217.                Thus, math is not a special case in  Smalltalk;  it  is
  218.           done  exactly  like everything else-by creating objects, and
  219.           sending them messages.  This may seem odd to  the  Smalltalk
  220.           novice,  but  this  regularity turns out to be quite a boon-
  221.           once you've mastered just a few paradigms, all of  the  lan-
  222.           guage  "falls  into  place."   Before  you go on to the next
  223.           chapter, make sure you try math involving  "*"  (multiplica-
  224.           tion),  "-"  (subtraction),  and "/" (division) also.  These
  225.           examples should get you started:
  226.                (8 * (4 / 2)) printNl !
  227.                (8 - (4 + 1)) printNl !
  228.                (5 + 4) printNl !
  229.                (2/3 + 7) printNl !
  230.                (2 + 3 * 4) printNl !
  231.                (2 + (3 * 4)) printNl !
  232.  
  233.  
  234.  
  235.  
  236.  
  237.  
  238.  
  239.  
  240.  
  241.  
  242.  
  243.  
  244.  
  245.  
  246.  
  247.  
  248.  
  249.  
  250.  
  251.  
  252.  
  253.  
  254.  
  255.  
  256.  
  257.  
  258.  
  259.  
  260.  
  261.  
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268.                                        -5-
  269.  
  270.  
  271.           22..  UUssiinngg ssoommee ooff tthhee SSmmaallllttaallkk ccllaasssseess
  272.                This chapter has examples which need a  place  to  hold
  273.           the  objects they create.  The following line creates such a
  274.           place; for now, treat it as magic.  At the end of the  chap-
  275.           ter we will revisit it with an explanation.  Type in:
  276.                Smalltalk at: #x put: 0 !
  277.           Now let's create some new objects.
  278.  
  279.           22..11..  AAnn aarrrraayy iinn SSmmaallllttaallkk
  280.                An  array  in  Smalltalk  is similar to an array in any
  281.           other language, although the syntax  may  seem  peculiar  at
  282.           first.  To create an array with room for 20 elements, do:
  283.                x := Array new: 20 !
  284.           The  "Array new: 20" creates the array; the "x :=" part con-
  285.           nects the name "x" with the object.  Until you assign  some-
  286.           thing  else  to "x", you can refer to this array by the name
  287.           "x".
  288.                Changing elements of the array is _n_o_t  done  using  the
  289.           ":="  operator;  this operator is used only to bind names to
  290.           objects.   In  fact,  you  never  modify  data   structures;
  291.           instead,  you send a message to the object, and it will mod-
  292.           ify itself.  For instance:
  293.                (x at: 1) printNl !
  294.           which prints:
  295.                nil
  296.           The slots of an array are initially set to "nothing"  (which
  297.           Smalltalk  calls  "nil").   Let's  set the first slot to the
  298.           number 99:
  299.                x at: 1 put: 99 !
  300.           and now make sure the 99 is actually there:
  301.                (x at: 1) printNl !
  302.           which then prints out:
  303.                99
  304.           These examples show how to manipulate an array.   They  also
  305.           show  the  standard  way  in which messages are passed argu-
  306.           ments.  In most cases, if a message takes an  argument,  its
  307.           name  will  end with ":".4 So when we said "x at: 1" we were
  308.           sending a message to whatever object was currently bound  to
  309.           "x"  with  an  argument of 1.  For an array, this results in
  310.           the first slot of the array being returned.
  311.                The second operation, "x at: 1 put: 99"  is  a  message
  312.           with  _t_w_o arguments.  It tells the array to place the second
  313.           argument (99) in the slot specified by the first (1).  Thus,
  314.           when  we  re-examine  the  first  slot,  it  does indeed now
  315.  
  316.  
  317.  
  318.             4 Alert  readers  will  remember  that  the math
  319.  
  320.  
  321.           examples of the  previous  chapter  deviated  from
  322.  
  323.  
  324.           this.
  325.  
  326.  
  327.  
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334.                                        -6-
  335.  
  336.  
  337.           contain 99.
  338.                There is a shorthand for describing  the  messages  you
  339.           send  to  objects.  You just run the message names together.
  340.           So we would say that our array accepts both  the  "at:"  and
  341.           "at:put:" messages.
  342.                There  is  quite a bit of sanity checking built into an
  343.           array.  The request
  344.                6 at: 1
  345.           fails with an error; 6 is an integer, and can't be  indexed.
  346.           Further,
  347.                x at: 21
  348.           fails  with  an error, because the array we created only has
  349.           room  for  20 objects.5 Finally, note that the object stored
  350.           in an array is just like any other  object,  so  we  can  do
  351.           things like:
  352.                ((x at: 1) + 1) printNl !
  353.           which  (assuming  you've  been  typing in the examples) will
  354.           print 100.
  355.  
  356.           22..22..  AA sseett iinn SSmmaallllttaallkk
  357.                We're done with the array we've been  using,  so  we'll
  358.           assign  something  new  to  our  "x" variable.  Note that we
  359.           don't need to do anything special about  the  old  array-the
  360.           fact  that nobody is using it any more will be automatically
  361.           detected, and the memory reclaimed.6  So,  to  get  our  new
  362.           object, simply do:
  363.                x := Set new !
  364.           Which creates an empty set.  To view its contents, do:
  365.                x printNl !
  366.           the  kind of object is printed out (i.e., Set), and then the
  367.           members are listed within parenthesis.  Since it's empty, we
  368.           see:
  369.                Set ()
  370.           Now  let's toss some stuff into it.  We'll add the numbers 5
  371.           and 7, plus the string 'foo'.  We _c_o_u_l_d type:
  372.  
  373.  
  374.  
  375.  
  376.  
  377.  
  378.             5 As of release  1.1,  GNU  Smalltalk  does  not
  379.  
  380.  
  381.           actually catch this error.
  382.  
  383.  
  384.             6 This is known as "garbage collection."  It  is
  385.  
  386.  
  387.           generally  done  when  Smalltalk  finds that it is
  388.  
  389.  
  390.           running low on memory.
  391.  
  392.  
  393.  
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.                                        -7-
  401.  
  402.  
  403.                x add: 5 !
  404.                x add: 7 !
  405.                x add: 'foo' !
  406.           But let's save a little typing by using a  Smalltalk  short-
  407.           hand:
  408.                x add: 5; add: 7; add: 'foo' !
  409.           This  line  does  exactly  what the previous example's three
  410.           lines did.  The trick is that the semicolon operator  causes
  411.           the  message  to be sent to the same object as the last mes-
  412.           sage sent.  So saying "; add: 7" is the same  as  saying  "x
  413.           add:  7",  because "x" was the last thing a message was sent
  414.           to.  This may not seem like such a big savings, but  compare
  415.           the ease when your variable is named "aVeryLongVariableName"
  416.           instead of just "x"!  We'll  revisit  some  other  occasions
  417.           where ";" saves you trouble, but for now let's continue with
  418.           our set.  Type either version of the example, and make  sure
  419.           that we've added 5, 7, and "foo":
  420.                x printNl !
  421.           we'll see that it now contains our data:
  422.                Set (5 'foo' 7)
  423.           What if we add something twice?  No problem-it just stays in
  424.           the set.  So a set is like a big  checklist-either  it's  in
  425.           there, or it isn't.  To wit:
  426.                x add:5; add: 5; add: 5; add: 5 !
  427.                x printNl !
  428.           We've  added  "5" several times, but when we printed our set
  429.           back out, we just see:
  430.                Set (5 'foo' 7)
  431.                What you put into a set with "add:", you can  take  out
  432.           with "remove:".  Try:
  433.                x remove: 5 !
  434.                x printNl !
  435.           The set now prints as:
  436.                Set ('foo' 7)
  437.           The "5" is indeed gone from the set.
  438.                We'll  finish  up  with one more of the many things you
  439.           can do with a set- checking for membership.  Try:
  440.                (x includes: 7) printNl !
  441.                (x includes: 5) printNl !
  442.           From which we see that x does indeed contain 7, but  not  5.
  443.           Notice  that  the  answer  is  printed as "true" or "false".
  444.           Once again, the thing returned is an object-in this case, an
  445.           object  known  as  a  boolean.   We'll  look  at  the use of
  446.           booleans later, but for now we'll just say that booleans are
  447.           nothing  more  than objects which can only either be true or
  448.           false-nothing else.  So they're very useful for  answers  to
  449.           yes  or  no  questions,  like the ones we just posed.  Let's
  450.           take a look at just one more kind of data structure:
  451.  
  452.           22..33..  DDiiccttiioonnaarriieess
  453.                A dictionary is a special kind of collection.   With  a
  454.           regular  array,  you must index it with integers.  With dic-
  455.           tionaries, you can index it with _a_n_y object  at  all.   Dic-
  456.           tionaries  thus  provide  a very powerful way of correlating
  457.  
  458.  
  459.  
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466.                                        -8-
  467.  
  468.  
  469.           one piece of information to another.  Their only downside is
  470.           that  they  are  somewhat less efficient than simple arrays.
  471.           Try the following:
  472.                x := Dictionary new.
  473.                x at: 'One' put: 1 !
  474.                x at: 'Two' put: 2 !
  475.                x at: 1 put: 'One' !
  476.                x at: 2 put: 'Two' !
  477.           This fills our dictionary in with some data.   The  data  is
  478.           actually  stored  in pairs of key and value (the key is what
  479.           you give to at:-it specifies a slot; the value  is  what  is
  480.           actually  stored  at that slot).  Notice how we were able to
  481.           specify not only integers but also strings as both  the  key
  482.           and  the  value.   In fact, we can use any kind of object we
  483.           want as either-the dictionary doesn't care.
  484.                Now we can map each key to a value:
  485.                (x at: 1) printNl !
  486.                (x at: 'Two') printNl !
  487.           which prints respectively:
  488.                 'One'
  489.                 2
  490.           We can also ask a dictionary to print itself:
  491.                x printNl !
  492.           which prints:
  493.                Dictionary (1,'One' 2,'Two' 'One',1 'Two',2 )
  494.           where the first member of each pair is the key, and the sec-
  495.           ond the value.
  496.  
  497.           22..44..  SSmmaallllttaallkk ddiiccttiioonnaarryy
  498.                If  you'll  remember from the beginning of the chapter,
  499.           we started out by saying:
  500.                Smalltalk at: #x put: 0 !
  501.           This code should look familiar-the at:put:  message  is  how
  502.           we've  been  storing  information in our own arrays and dic-
  503.           tionaries.  In a Smalltalk environment the name  "Smalltalk"
  504.           has been preset to point to a dictionary7 which both you _a_n_d
  505.           Smalltalk can use.  To see how  this  sharing  works,  we'll
  506.           first  try  to  use  a variable which Smalltalk doesn't know
  507.           about:
  508.                y := 0 !
  509.           Smalltalk complains because  "y"  is  an  unknown  variable.
  510.           Using our knowledge of dictionaries, and taking advantage of
  511.           our access to Smalltalk's dictionary, we  can  add  it  our-
  512.           selves:
  513.  
  514.  
  515.  
  516.             7 Actually,  a SystemDictionary, which is just a
  517.  
  518.  
  519.           Dictionary with some extra  hooks  to  run  things
  520.  
  521.  
  522.           when Smalltalk first starts
  523.  
  524.  
  525.  
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532.                                        -9-
  533.  
  534.  
  535.                Smalltalk at: #y put: 0 !
  536.           The only mystery left is why we're using "#y" instead of our
  537.           usual quoted string.  This is one of those simple  questions
  538.           whose  answer  runs  surprisingly deep.  The quick answer is
  539.           that "#y" and "'y'" are pretty much the  same,  except  that
  540.           the  former will always be the same object each time you use
  541.           it, whereas the latter can be a new string each time you  do
  542.           so.8
  543.                Now that we've added "y" to Smalltalk's dictionary,  we
  544.           try again:
  545.                y := 1 !
  546.           It  works!  Because you've added an entry for "y", Smalltalk
  547.           is now perfectly happy to let you use this new variable.
  548.                If you have some spare time,  you  can  print  out  the
  549.           _e_n_t_i_r_e Smalltalk dictionary with:
  550.                Smalltalk printNl !
  551.           As you might suspect, this will print out quite a large list
  552.           of names!  If you get tired of watching Smalltalk  grind  it
  553.           out,  use  your  interrupt key (control-C, usually) to bring
  554.           Smalltalk back to interactive mode.
  555.  
  556.           22..55..  CClloossiinngg tthhoouugghhttss
  557.                You've seen how Smalltalk provides you with  some  very
  558.           powerful  data  structures.   You've also seen how Smalltalk
  559.           itself uses these same facilities to implement the language.
  560.           But  this  is  only the tip of the iceberg-Smalltalk is much
  561.           more than a collection of "neat" facilities to use.
  562.                The objects and methods which are automatically  avail-
  563.           able  are  only the beginning of the foundation on which you
  564.           build your programs-Smalltalk allows you  to  add  your  own
  565.           objects and methods into the system, and then use them along
  566.           with everything else.  The art of programming  in  Smalltalk
  567.           is  the art of looking at your problems in terms of objects,
  568.           using the existing object types to good effect, and  enhanc-
  569.           ing  Smalltalk  with  new types of objects.  Now that you've
  570.           been exposed to the basics of Smalltalk manipulation, we can
  571.           begin  to look at this object-oriented technique of program-
  572.           ming.
  573.  
  574.  
  575.  
  576.  
  577.  
  578.  
  579.             8 For  more detail, please feel free to skip out
  580.  
  581.  
  582.           to chapter 12 and read the section "Two Flavors of
  583.  
  584.  
  585.           Equality"  and the following section "Checking for
  586.  
  587.  
  588.           the Two Types of Equality."
  589.  
  590.  
  591.  
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598.                                       -10-
  599.  
  600.  
  601.           33..  TThhee SSmmaallllttaallkk ccllaassss hhiieerraarrcchhyy
  602.                When programming in Smalltalk, you  sometimes  need  to
  603.           create  new  kinds  of objects, and define what various mes-
  604.           sages will do to these objects.  In the next chapter we will
  605.           create some new classes, but first we need to understand how
  606.           Smalltalk organizes  the  types  and  objects  it  contains.
  607.           Because this is a pure "concept" chapter, without any actual
  608.           Smalltalk code to run, we will keep  it  short  and  to  the
  609.           point.
  610.  
  611.           33..11..  CCllaassss OObbjjeecctt
  612.                Smalltalk  organizes all of its classes as a tree hier-
  613.           archy.  At the very top of this hierarchy is class "Object".
  614.           Following somewhere below it are more specific classes, such
  615.           as the ones we've worked with-strings, integers, arrays, and
  616.           so forth.  They are grouped together based on their similar-
  617.           ities-for instance, types of objects which may  be  compared
  618.           as  greater or less than each other fall under a class known
  619.           as "Magnitude".
  620.                One of the first tasks when creating a new object is to
  621.           figure  out  where  within this hierarchy your object falls.
  622.           Coming up with an answer to this problem is at least as much
  623.           art as science, and there are no hard-and-fast rules to nail
  624.           it down.  We'll take a look at three  kinds  of  objects  to
  625.           give you a feel for how this organization matters.
  626.  
  627.           33..22..  AAnniimmaallss
  628.                Imagine that we have three kinds of objects, represent-
  629.           ing "Animals", "Parrots", and "Pigs".  Our messages will  be
  630.           "eat",  "sing",  and  "snort".   Our first pass at inserting
  631.           these objects into the Smalltalk  hierarchy  would  organize
  632.           them like:
  633.                Object
  634.                     Animals
  635.                     Parrots
  636.                     Pigs
  637.           This  means  that  Animals, Parrots, and Pigs are all direct
  638.           descendants of "Object", and are  not  descendants  of  each
  639.           other.
  640.                Now  we  must  define  how each animal responds to each
  641.           kind of message.
  642.                     Animals
  643.                          eat--Say "I have now eaten"
  644.                          sing--Error
  645.                          snort--Error
  646.                     Parrots
  647.                          eat--Say "I have now eaten"
  648.                          sing--Say "Tweet"
  649.                          snort--Error
  650.                     Pigs
  651.                          eat--Say "I have now eaten"
  652.                          sing--Error
  653.                          snort--Say "Oink"
  654.           Notice how we kept having to indicate an action  for  "eat".
  655.  
  656.  
  657.  
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664.                                       -11-
  665.  
  666.  
  667.           An  experienced  object designer would immediately recognize
  668.           this as a clue that we haven't set  up  our  hierarchy  cor-
  669.           rectly.  Let's try a different organization:
  670.                     Animals
  671.                          Parrots
  672.                               Pigs
  673.           That  is,  Parrots  inherit from Animals, and Pigs from Par-
  674.           rots.  Now Parrots inherit all of the actions from  Animals,
  675.           and  Pigs  from  both  Parrots _a_n_d Animals.  Because of this
  676.           inheritance, we may now define a new set  of  actions  which
  677.           spares us the redundancy of the previous set:
  678.                     Animals
  679.                          eat--Say "I have now eaten"
  680.                          sing--Error
  681.                          snort--Error
  682.                     Parrots
  683.                          sing--Say "Tweet"
  684.                     Pigs
  685.                          snort--Say "Oink"
  686.           Because  Parrots and Pigs both inherit from Animals, we have
  687.           only had to define the "eat" action once.  However, we  have
  688.           made  one  mistake  in  our class setup-what happens when we
  689.           tell a Pig to "sing"?  It says "Tweet", because we have  put
  690.           Pigs  as an inheritor of Parrots.  Let's try one final orga-
  691.           nization:
  692.                     Animals
  693.                          Parrots
  694.                          Pigs
  695.           Now Parrots and Pigs inherit from Animals, but not from each
  696.           other.  Let's also define one final pithy set of actions:
  697.                     Animals
  698.                          eat--Say "I have eaten"
  699.                     Parrots
  700.                          sing--Say "Tweet"
  701.                     Pigs
  702.                          snort--Say "Oink"
  703.           The  change is just to leave out messages which are inappro-
  704.           priate.  If Smalltalk detects that a message is not known by
  705.           an  object  or  any  of its ancestors, it will automatically
  706.           give an error-so you don't have to do  this  sort  of  thing
  707.           yourself.   Notice  that  now  sending  "sing" to a Pig does
  708.           indeed _n_o_t say  "Tweet"-it  will  cause  a  Smalltalk  error
  709.           instead.
  710.  
  711.           33..33..  TThhee bboottttoomm lliinnee ooff tthhee ccllaassss hhiieerraarrcchhyy
  712.                The  goal  of  the  class  hierarchy is to allow you to
  713.           organize objects into a relationship which allows a particu-
  714.           lar  object  to _i_n_h_e_r_i_t the code of its ancestors.  Once you
  715.           have identified an  effective  organization  of  types,  you
  716.           should  find that a particular technique need only be imple-
  717.           mented once, then inherited by  the  children  below.   This
  718.           keeps  your  code  smaller, and allows you to fix a bug in a
  719.           particular algorithm in only once place-then have all  users
  720.           of it just inherit the fix.
  721.  
  722.  
  723.  
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730.                                       -12-
  731.  
  732.  
  733.                You  will find your decisions for adding objects change
  734.           as you gain experience.  As you become  more  familiar  with
  735.           the  existing  set  of objects and messages, your selections
  736.           will increasingly "fit in" with the existing ones.  But even
  737.           a  Smalltalk "pro" stops and thinks carefully at this stage-
  738.           so don't be daunted if your first choices seem difficult and
  739.           error-prone.
  740.  
  741.  
  742.  
  743.  
  744.  
  745.  
  746.  
  747.  
  748.  
  749.  
  750.  
  751.  
  752.  
  753.  
  754.  
  755.  
  756.  
  757.  
  758.  
  759.  
  760.  
  761.  
  762.  
  763.  
  764.  
  765.  
  766.  
  767.  
  768.  
  769.  
  770.  
  771.  
  772.  
  773.  
  774.  
  775.  
  776.  
  777.  
  778.  
  779.  
  780.  
  781.  
  782.  
  783.  
  784.  
  785.  
  786.  
  787.  
  788.  
  789.  
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796.                                       -13-
  797.  
  798.  
  799.           44..  CCrreeaattiinngg aa nneeww ccllaassss ooff oobbjjeeccttss
  800.                With  the  basic  techniques presented in the preceding
  801.           chapters, we're ready do our first real  Smalltalk  program.
  802.           In this chapter we will construct three new types of objects
  803.           (known as  "classes"),  using  the  Smalltalk  technique  of
  804.           _i_n_h_e_r_i_t_a_n_c_e  to tie the classes together, create new objects
  805.           belonging to these classes (known as creating  _i_n_s_t_a_n_c_e_s  of
  806.           the class), and send messages to these objects.
  807.                We'll  exercise  all  this  by implementing a toy home-
  808.           finance accounting system.  We will keep track of our  over-
  809.           all  cash,  and  will have special handling for our checking
  810.           and savings accounts.  From this point on, we will be defin-
  811.           ing  classes  which  will be used in future chapters.  Since
  812.           you will probably not be running this whole tutorial in  one
  813.           Smalltalk session, it would be nice to save off the state of
  814.           Smalltalk and resume it without having  to  retype  all  the
  815.           previous  examples.   To  save  the  current  state  of  GNU
  816.           Smalltalk, type:
  817.                Smalltalk snapshot: 'myimage.img' !
  818.           and from your shell, to later restart  Smalltalk  from  this
  819.           "snapshot":
  820.                % mst -I myimage.img
  821.           Such  a  snapshot  currently takes a little over 300K bytes,
  822.           and contains all variables,  classes,  and  definitions  you
  823.           have added.
  824.  
  825.           44..11..  CCrreeaattiinngg aa nneeww ccllaassss
  826.                Guess  how you create a new class?  This should be get-
  827.           ting monotonous by now-by sending a message  to  an  object.
  828.           The way we create our first "custom" class is by sending the
  829.           following message:
  830.                Object subclass: #Account
  831.                     instanceVariableNames: 'balance'
  832.                     classVariableNames: ''
  833.                     poolDictionaries: ''
  834.                     category: nil !
  835.           Quite a mouthful, isn't it?  Most people end up  customizing
  836.           their editor to pop this up at a push of a button.  But con-
  837.           ceptually, it isn't really that bad.  The Smalltalk variable
  838.           "Object"  is  bound to the grand-daddy of all classes on the
  839.           system.  What we're doing here is telling the "Object" class
  840.           that  we  want  to  add to it a subclass known as "Account".
  841.           The  other  parts  of  the  message  can  be  ignored,   but
  842.           "instanceVariableNames: 'balance'" tells it that each object
  843.           in  this  subclass  will  have  a  hidden   variable   named
  844.           "balance".9
  845.  
  846.  
  847.  
  848.             9 In  case  you're having a hard time making out
  849.  
  850.  
  851.           the font, the "''"'s after classVariableNames: and
  852.  
  853.  
  854.  
  855.  
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862.                                       -14-
  863.  
  864.  
  865.           44..22..  DDooccuummeennttiinngg tthhee ccllaassss
  866.                The next step is to associate a  description  with  the
  867.           class.  You do this by sending a message to the new class:
  868.                Account comment: 'I represent a place to deposit and withdraw money' !
  869.           A  description is associated with _e_v_e_r_y Smalltalk class, and
  870.           it's considered good form to add a description to  each  new
  871.           class you define.  To get the description for a given class:
  872.                (Account comment) printNl !
  873.           And your string is printed back to you.  Try this with class
  874.           Integer, too:
  875.                (Integer comment) printNl !
  876.  
  877.           44..33..  DDeeffiinniinngg aa mmeetthhoodd ffoorr tthhee ccllaassss
  878.                We  have  created a class, but it isn't ready to do any
  879.           work for us-we have to define some messages which the  class
  880.           can process first.  We'll start at the beginning by defining
  881.           methods for instance creation:
  882.                !Account class methodsFor: 'instance creation'!
  883.  
  884.                new
  885.                     | r |
  886.  
  887.                     r := super new.
  888.                     r init.
  889.                     ^r
  890.                !!
  891.           Again, programming your editor to do  this  is  recommended.
  892.           The  important  points about this are "Account class", which
  893.           means that we are defining messages which are to be sent  to
  894.           the Account class itself.  "methodsFor: 'instance creation'"
  895.           is more documentation support; it says that all of the meth-
  896.           ods  defined  will  be  to  support creating objects of type
  897.           Account.  Finally, the text starting with "new"  and  ending
  898.           with "!!" defined what action to take for the message "new".
  899.           When you enter this definition, GNU  Smalltalk  will  simply
  900.           give  you  another  prompt.  You method has been compiled in
  901.           and is ready for use.  GNU Smalltalk is pretty quiet on suc-
  902.           cessful  method  definitions--but you'll get plenty of error
  903.           messages if there's a problem!
  904.                This is also the first example where we've had  to  use
  905.           more  than  one  statement, and thus a good place to present
  906.           the statement separator-the ".".  Like Pascal, and unlike C,
  907.           statements  are  _s_e_p_a_r_a_t_e_d rather than terminated.  Thus you
  908.           need only use the "." when you have finished  one  statement
  909.           and  are  starting another.  This is why our last statement,
  910.           "^r", does not have a "." following.
  911.  
  912.  
  913.  
  914.  
  915.           poolDictionaries:  are  a pair of single quotes-an
  916.  
  917.  
  918.           empty string.
  919.  
  920.  
  921.  
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928.                                       -15-
  929.  
  930.  
  931.                The best way to describe how this method  works  is  to
  932.           step through it.  Imagine we sent a message to the new class
  933.           Account with the command line:
  934.                Account new !
  935.                "Account" receives the message "new" and looks  up  how
  936.           to  process  this message.  It finds our new definition, and
  937.           starts running it.  The first line, "| r |", creates a _l_o_c_a_l
  938.           _v_a_r_i_a_b_l_e  named  "r"  which can be used as a placeholder for
  939.           the objects we create.  "r" will go away as soon as the mes-
  940.           sage is done being processed.
  941.                The  first  real step is to actually create the object.
  942.           The line "r := super new" does this  using  a  fancy  trick.
  943.           The word "super" stands for the same object that the message
  944.           "new" was  originally  sent  to  (remember-it's  "Account"),
  945.           except  that  when Smalltalk goes to search for the methods,
  946.           he starts one level _h_i_g_h_e_r up in the hierarchy than the cur-
  947.           rent  level.   So for a method in the Account class, this is
  948.           the Object class (because the class Account inherits from is
  949.           Object-go  back  and  look  at  how  we  created the Account
  950.           class), and the Object class' methods then execute some code
  951.           in  response  to the "new" message.  As it turns out, Object
  952.           will do the actual creation of the object when sent a  "new"
  953.           message.
  954.                One  more time in slow motion: the Account method "new"
  955.           wants to do some fiddling about when new  objects  are  cre-
  956.           ated,  but he also wants to let his parent do some work with
  957.           a method of the _s_a_m_e _n_a_m_e.  By saying "r := super new" he is
  958.           letting his parent create the object, and then he is attach-
  959.           ing it to the variable "r".  So after this line of code exe-
  960.           cutes,  we  have a brand new object of type Account, and "r"
  961.           is bound to it.  You will understand  this  better  as  time
  962.           goes  on, but for now scratch your head once, accept it as a
  963.           recipe, and keep going.
  964.                We have the new object, but we haven't set it  up  cor-
  965.           rectly.  Remember the hidden variable "balance" which we saw
  966.           in the beginning of this chapter?  "super new" gives us  the
  967.           object  with  the "balance" field containing nothing-we want
  968.           our  balance field to start at 0.10 So what we need to do is
  969.  
  970.  
  971.  
  972.             10 And unlike C, Smalltalk draws  a  distinction
  973.  
  974.  
  975.           between  0  and nil.  nil is the "nothing" object,
  976.  
  977.  
  978.           and you will receive an error if you  try  to  do,
  979.  
  980.  
  981.           say,  math  on  it.  It really does matter that we
  982.  
  983.  
  984.           initialize our instance variable to the  number  0
  985.  
  986.  
  987.  
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994.                                       -16-
  995.  
  996.  
  997.           ask the object to set itself up.  By saying "r init", we are
  998.           sending  the "init" message to our new Account. We'll define
  999.           this method in the next section-for  now  just  assume  that
  1000.           sending the "init" message will get our Account set up.
  1001.                Finally, we say "^r".  In English, this is "return what
  1002.           r is attached to".  This means that whoever  sent  "Account"
  1003.           the  "new" message will get back this brand new account.  At
  1004.           the same time, our temporary variable "r" ceases to exist.
  1005.  
  1006.           44..44..  DDeeffiinniinngg aann iinnssttaannccee mmeetthhoodd
  1007.                We need to define the "init"  method  for  our  Account
  1008.           objects,  so  that our "new" method defined above will work.
  1009.           Here's the Smalltalk code:
  1010.                !Account methodsFor: 'instance initialization'!
  1011.                init
  1012.                     balance := 0
  1013.                !!
  1014.           It looks quite a bit like the  previous  method  definition,
  1015.           except  that  the  first  one  said  "Account class methods-
  1016.           For:...", and ours says "Account methodsFor:...".  The  dif-
  1017.           ference  is that the first one defined a method for messages
  1018.           sent directly to "Account", but the second one is  for  mes-
  1019.           sages  which  are sent to Account objects _o_n_c_e _t_h_e_y _a_r_e _c_r_e-
  1020.           _a_t_e_d.
  1021.                The method named "init" has only one line, "balance  :=
  1022.           0".   This  initializes the hidden variable "balance" (actu-
  1023.           ally called an _i_n_s_t_a_n_c_e _v_a_r_i_a_b_l_e  )  to  zero,  which  makes
  1024.           sense  for  an  account  balance.   Notice  that  the method
  1025.           doesn't end  with  "^r"  or  anything  like  it-this  method
  1026.           doesn't  return  a value to the message sender.  When you do
  1027.           not specify a return value, Smalltalk  defaults  the  return
  1028.           value  to  the  object  currently executing.  For clarity of
  1029.           programming, you might consider explicitly returning  "self"
  1030.           in cases where you intend the return value to be used.11
  1031.  
  1032.  
  1033.  
  1034.  
  1035.           if we wish to do math on it in the future.
  1036.  
  1037.  
  1038.             11 And  why  didn't  the  designers  default the
  1039.  
  1040.  
  1041.           return value to nil?  Perhaps they didn't appreci-
  1042.  
  1043.  
  1044.           ate  the  value  of void functions.  After all, at
  1045.  
  1046.  
  1047.           the time Smalltalk was being  designed,  C  didn't
  1048.  
  1049.  
  1050.           even have a void data type.
  1051.  
  1052.  
  1053.  
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060.                                       -17-
  1061.  
  1062.  
  1063.           44..55..  LLooookkiinngg aatt oouurr AAccccoouunntt
  1064.                Let's create an _i_n_s_t_a_n_c_e of class Account:
  1065.                Smalltalk at: #a put: (Account new) !
  1066.           Can  you  guess  what this does?  The "Smalltalk at: #a put:
  1067.           <something>"  hearkens  back  to  chapter  2-it  creates   a
  1068.           Smalltalk  variable.   And  the  "Account new" creates a new
  1069.           Account, and returns it.  So this line creates  a  Smalltalk
  1070.           variable  named "a", and attaches it to a new Account-all in
  1071.           one line.
  1072.                Let's take a look at the Account object  we  just  cre-
  1073.           ated:
  1074.                a printNl !
  1075.           It prints:
  1076.                an Account
  1077.           Hmmm... not very informative.  The problem is that we didn't
  1078.           tell our Account how to print itself, so we're just  getting
  1079.           the  default  system  "printNl"  method-which tells what the
  1080.           object _i_s, but not what it _c_o_n_t_a_i_n_s.  So clearly we must add
  1081.           such a method:
  1082.                !Account methodsFor: 'printing'!
  1083.                printOn: stream
  1084.                     super printOn: stream.
  1085.                     ' with balance: ' printOn: stream.
  1086.                     balance printOn: stream
  1087.                !!
  1088.           Now give it a try again:
  1089.                a printNl !
  1090.           which prints:
  1091.                an Account with balance: 0
  1092.           This  may  seem  a  little  strange.  We added a new method,
  1093.           printOn:, and our printNl message  starts  behaving  differ-
  1094.           ently.   It  turns out that the printOn: message is the cen-
  1095.           tral printing function-once you've defined it,  all  of  the
  1096.           other printing methods end up calling it.  Its argument is a
  1097.           place to print to-quite often it is the  variable  "stdout".
  1098.           This  variable  is usually hooked to your terminal, and thus
  1099.           you get the printout to your screen.
  1100.                The "super printOn: stream" lets our parent do what  it
  1101.           did  before-print  out  what  our type is.  The "an Account"
  1102.           part of the printout came from this.   "'  with  balance:  '
  1103.           printOn:  stream"  creates the string " with balance: ", and
  1104.           prints  it  out  to  the  stream,  too.   Finally,  "balance
  1105.           printOn: stream" asks whatever object is hooked to the "bal-
  1106.           ance" variable to print itself to the stream.  We set  "bal-
  1107.           ance" to 0, so the 0 gets printed out.
  1108.  
  1109.           44..66..  MMoovviinngg mmoonneeyy aarroouunndd
  1110.                We  can  now  create accounts, and look at them.  As it
  1111.           stands, though, our balance will always be 0-what a tragedy!
  1112.           Our  final  methods  will  let  us  deposit and spend money.
  1113.           They're very simple:
  1114.  
  1115.  
  1116.  
  1117.  
  1118.  
  1119.  
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126.                                       -18-
  1127.  
  1128.  
  1129.                !Account methodsFor: 'moving money'!
  1130.                spend: amount
  1131.                     balance := balance - amount
  1132.                !
  1133.                deposit: amount
  1134.                     balance := balance + amount
  1135.                !!
  1136.           With these methods you can now deposit and spend amounts  of
  1137.           money.  Try these operations:
  1138.                a deposit: 125!
  1139.                a deposit: 20!
  1140.                a printNl!
  1141.                a spend: 10!
  1142.                a printNl!
  1143.  
  1144.           44..77..  SSppeecciiaalliizzeedd oobbjjeeccttss
  1145.                We  now have a generic concept, "Account".  We can cre-
  1146.           ate them, check their balance, and move money in and out  of
  1147.           them.   They provide a good foundation, but leave out impor-
  1148.           tant information that particular  types  of  accounts  might
  1149.           want.  In the next chapter, we'll take a look at fixing this
  1150.           problem using _s_u_b_c_l_a_s_s_e_s.
  1151.  
  1152.  
  1153.  
  1154.  
  1155.  
  1156.  
  1157.  
  1158.  
  1159.  
  1160.  
  1161.  
  1162.  
  1163.  
  1164.  
  1165.  
  1166.  
  1167.  
  1168.  
  1169.  
  1170.  
  1171.  
  1172.  
  1173.  
  1174.  
  1175.  
  1176.  
  1177.  
  1178.  
  1179.  
  1180.  
  1181.  
  1182.  
  1183.  
  1184.  
  1185.  
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192.                                       -19-
  1193.  
  1194.  
  1195.           55..  TTwwoo SSuubbccllaasssseess ffoorr tthhee AAccccoouunntt CCllaassss
  1196.                This chapter continues from  the  previous  chapter  in
  1197.           demonstrating  how  one  creates  classes  and subclasses in
  1198.           Smalltalk.  In this chapter we will create two special  sub-
  1199.           classes  of Account, known as Checking and Savings.  We will
  1200.           continue to _i_n_h_e_r_i_t the capabilities of  Account,  but  will
  1201.           tailor  the two kinds of objects to better manage particular
  1202.           kinds of accounts.
  1203.  
  1204.           55..11..  TThhee SSaavviinnggss ccllaassss
  1205.                We create the Savings class as a subclass  of  Account.
  1206.           It  holds money, just like an Account, but has an additional
  1207.           property that we will model: it is paid  interest  based  on
  1208.           its  balance.   We create the class Savings as a subclass of
  1209.           Account:
  1210.                Account subclass: #Savings
  1211.                     instanceVariableNames: 'interest'
  1212.                     classVariableNames: ''
  1213.                     poolDictionaries: ''
  1214.                     category: nil !
  1215.           The instance variable "interest"  will  accumulate  interest
  1216.           paid.  Thus, in addition to the "spend:" and "deposit:" mes-
  1217.           sages which we inherit from our  parent,  Account,  we  will
  1218.           need  to  define a method to add in _i_n_t_e_r_e_s_t deposits, and a
  1219.           way to clear  the  interest  variable  (which  we  would  do
  1220.           yearly, after we have paid taxes).  We first define a method
  1221.           for allocating a new account-we need to make sure  that  the
  1222.           interest field starts at 0.
  1223.                !Savings methodsFor: 'initialization'!
  1224.                init
  1225.                     interest := 0.
  1226.                     ^ super init
  1227.                !!
  1228.           Recall  that  the parent took care of the "new" message, and
  1229.           created a new object of the appropriate  size.   After  cre-
  1230.           ation,  the  parent  also  sent an "init" message to the new
  1231.           object.  As a subclass  of  Account,  the  new  object  will
  1232.           receive  the  "init"  message  first;  it  sets  up  its own
  1233.           instance variable, and then passes the "init" message up the
  1234.           chain  to  let  its parent take care of its part of the ini-
  1235.           tialization.
  1236.                With our new "Savings" account created, we  can  define
  1237.           two methods for dealing specially with such an account:
  1238.  
  1239.  
  1240.  
  1241.  
  1242.  
  1243.  
  1244.  
  1245.  
  1246.  
  1247.  
  1248.  
  1249.  
  1250.  
  1251.  
  1252.  
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258.                                       -20-
  1259.  
  1260.  
  1261.                !Savings methodsFor: 'interest'!
  1262.                interest: amount
  1263.                     interest := interest + amount.
  1264.                     self deposit: amount
  1265.                !
  1266.                clearInterest
  1267.                     | oldinterest |
  1268.  
  1269.                     oldinterest := interest.
  1270.                     interest := 0.
  1271.                     ^oldinterest
  1272.                !!
  1273.           The  first  method says that we add the "amount" to our run-
  1274.           ning total of interest.  The  line  "self  deposit:  amount"
  1275.           tells  Smalltalk  to  send ourselves a message, in this case
  1276.           "deposit: amount".  This then causes Smalltalk  to  look  up
  1277.           the  method  for  "deposit:",  which it finds in our parent,
  1278.           Account.  Executing this method  then  updates  our  overall
  1279.           balance.12
  1280.                One  may wonder why we don't just replace this with the
  1281.           simpler "balance := balance + amount".  The answer  lies  in
  1282.           one of the philosophies of object-oriented languages in gen-
  1283.           eral, and Smalltalk in particular.  Our goal is to encode  a
  1284.           technique  for  doing something _o_n_c_e only, and then re-using
  1285.           that technique when needed.   If  we  had  directly  encoded
  1286.           "balance  :=  balance  + amount" here, there would have been
  1287.           _t_w_o places that knew  how  to  update  the  balance  from  a
  1288.           deposit.  This may seem like a useless difference.  But con-
  1289.           sider if later we decided to start counting  the  number  of
  1290.           deposits  made.   If  we  had  encoded "balance := balance +
  1291.           amount" in each place that needed to update the balance,  we
  1292.           would  have to hunt each of them down in order to update the
  1293.  
  1294.  
  1295.  
  1296.             12 "self"  is  much  like  "super",  except that
  1297.  
  1298.  
  1299.           "self" will start looking for a method at the bot-
  1300.  
  1301.  
  1302.           tom  of  the  type  hierarchy  for the object, but
  1303.  
  1304.  
  1305.           "super" starts looking one level _u_p from the  cur-
  1306.  
  1307.  
  1308.           rent  level.   Thus,  using "super" _f_o_r_c_e_s inheri-
  1309.  
  1310.  
  1311.           tance, but "self" will find the  first  definition
  1312.  
  1313.  
  1314.           of the message which it can.
  1315.  
  1316.  
  1317.  
  1318.  
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324.                                       -21-
  1325.  
  1326.  
  1327.           count  of  deposits.   By   sending   "self"   the   message
  1328.           "deposit:",  we  need  only  update  this  method _o_n_c_e; each
  1329.           sender of this message would then automatically get the cor-
  1330.           rect up-to-date technique for updating the balance.
  1331.                The  second  method,  "clearInterest",  is simpler.  We
  1332.           create a temporary variable "oldinterest" to hold  the  cur-
  1333.           rent  amount  of interest.  We then zero out our interest to
  1334.           start the year afresh.  Finally, we return the old  interest
  1335.           as  our  result, so that our year-end accountant can see how
  1336.           much we made.13
  1337.  
  1338.           55..22..  TThhee CChheecckkiinngg ccllaassss
  1339.                Our  second  subclass  of Account represents a checking
  1340.           account.  We will keep track of two facets:
  1341.                     - What check number we are on
  1342.                     - How many checks we have left in our checkbook
  1343.           We will define this as another subclass of Account:
  1344.                Account subclass: #Checking
  1345.                     instanceVariableNames: 'checknum checksleft'
  1346.                     classVariableNames: ''
  1347.                     poolDictionaries: ''
  1348.                     category: nil !
  1349.           We have two instance variables, but we really only  need  to
  1350.           initialize one of them-if there are no checks left, the cur-
  1351.           rent check number can't matter.  Remember, our parent  class
  1352.           Account  will send us the "init" message.  We don't need our
  1353.           own class-specific "new" function, since our  parent's  will
  1354.           provide everything we need.
  1355.                !Checking methodsFor: 'Initialization'!
  1356.                init
  1357.                     checksleft := 0.
  1358.                     ^super init
  1359.                !!
  1360.           As  in Savings, we inherit most of abilities from our super-
  1361.           class, Account.  For  initialization,  we  leave  "checknum"
  1362.  
  1363.  
  1364.  
  1365.             13 Of course, in a  real  accounting  system  we
  1366.  
  1367.  
  1368.           would never discard such information-we'd probably
  1369.  
  1370.  
  1371.           throw it into a Dictionary object, indexed by  the
  1372.  
  1373.  
  1374.           year  that  we're  finishing.  The ambitious might
  1375.  
  1376.  
  1377.           want to try their hand  at  implementing  such  an
  1378.  
  1379.  
  1380.           enhancement.
  1381.  
  1382.  
  1383.  
  1384.  
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390.                                       -22-
  1391.  
  1392.  
  1393.           alone,  but  set  the  number  of checks in our checkbook to
  1394.           zero.  We finish by letting our parent class do its own ini-
  1395.           tialization.
  1396.  
  1397.           55..33..  WWrriittiinngg cchheecckkss
  1398.                We  will  finish  this  chapter  by adding a method for
  1399.           spending money through our checkbook.  The mechanics of tak-
  1400.           ing a message and updating variables should be familiar:
  1401.                !Checking methodsFor: 'spending'!
  1402.                newChecks: number count: checkcount
  1403.                     checknum := number.
  1404.                     checksleft := checkcount
  1405.                !
  1406.  
  1407.                writeCheck: amount
  1408.                     | num |
  1409.  
  1410.                     num := checknum.
  1411.                     checknum := checknum + 1.
  1412.                     checksleft := checksleft - 1.
  1413.                     self spend: amount.
  1414.                     ^ num
  1415.                !!
  1416.           "newChecks:"  fills  our  checkbook  with checks.  We record
  1417.           what check number we're starting with, and update the  count
  1418.           of the number of checks in the checkbook.
  1419.                "writeCheck:"  merely notes the next check number, then
  1420.           bumps up the check number, and down the  check  count.   The
  1421.           message "self spend: amount" resends the message "spend:" to
  1422.           our own object.  This causes its method to be looked  up  by
  1423.           Smalltalk.   The  method  is then found in our parent class,
  1424.           Account, and our balance is  then  updated  to  reflect  our
  1425.           spending.
  1426.                You can try the following examples:
  1427.                Smalltalk at: #c put: (Checking new) !
  1428.                c printNl !
  1429.                c deposit: 250 !
  1430.                c printNl !
  1431.                c newChecks: 100 count: 50 !
  1432.                c printNl !
  1433.                (c writeCheck: 32) printNl !
  1434.                c printNl !
  1435.           For  amusement,  you might want to add a printOn: message to
  1436.           the checking class so  you  can  see  the  checking-specific
  1437.           information.
  1438.                In this chapter, you have seen how to create _s_u_b_c_l_a_s_s_e_s
  1439.           of your own classes.  You have added new methods, and _i_n_h_e_r-
  1440.           _i_t_e_d methods from the parent classes.  These techniques pro-
  1441.           vide the majority of the structure for building solutions to
  1442.           problems.   In  the following chapters we will be filling in
  1443.           details on further language mechanisms and types,  and  pro-
  1444.           viding   details   on  how  to  debug  software  written  in
  1445.           Smalltalk.
  1446.  
  1447.  
  1448.  
  1449.  
  1450.  
  1451.  
  1452.  
  1453.  
  1454.  
  1455.  
  1456.                                       -23-
  1457.  
  1458.  
  1459.           66..  CCooddee bblloocckkss
  1460.                The Account/Saving/Checking example from the last chap-
  1461.           ter  has  several  deficiencies.   It  has  no record of the
  1462.           checks and their values.  Worse, it allows you  to  write  a
  1463.           check  when  there  are no more checks-the Integer value for
  1464.           the number of checks will just calmly go negative!   To  fix
  1465.           these  problems we will need to introduce more sophisticated
  1466.           control structures.
  1467.  
  1468.           66..11..  CCoonnddiittiioonnss aanndd ddeecciissiioonn mmaakkiinngg
  1469.                Let's first add some code to keep you from writing  too
  1470.           many  checks.   We will simply update our current method for
  1471.           the Checking class; if you have entered the methods from the
  1472.           previous  chapters, the old definition will be overridden by
  1473.           this new one.
  1474.                !Checking methodsFor: 'spending'!
  1475.                writeCheck: amount
  1476.                     | num |
  1477.  
  1478.                     (checksleft < 1)
  1479.                          ifTrue: [ ^self error: 'Out of checks' ].
  1480.                     num := checknum.
  1481.                     checknum := checknum + 1.
  1482.                     checksleft := checksleft - 1.
  1483.                     self spend: amount
  1484.                     ^ num
  1485.                !!
  1486.           The two new lines are:
  1487.                (checksleft < 1)
  1488.                     ifTrue: [ ^self error: 'Out of checks' ].
  1489.           At first glance, this appears to be a completely new  struc-
  1490.           ture.   Look  again!   The  only new construct is the square
  1491.           brackets.
  1492.                The first line is a simple _b_o_o_l_e_a_n expression.  "check-
  1493.           sleft" is our integer, as initialized by our Checking class.
  1494.           It is sent the message "<", and the argument 1.  The current
  1495.           number  bound to "checksleft" compares itself against 1, and
  1496.           returns a boolean object telling whether it is less than  1.
  1497.                Now this boolean-being either true or false-is sent the
  1498.           message "IfTrue:", with an argument which is called  a  _c_o_d_e
  1499.           _b_l_o_c_k.  A code block is an object, just like any other.  But
  1500.           instead of holding a number, or a Set, it  holds  executable
  1501.           statements.
  1502.                So what does a boolean _d_o with a code block which is an
  1503.           argument to a ifTrue: message?  It depends on which boolean!
  1504.           If  the  object  is  the "true" object, it executes the code
  1505.           block it has been handed.  If it is the "false"  object,  it
  1506.           returns  without  executing  the  code block.  So the tradi-
  1507.           tional  "conditional  construct"  has   been   replaced   in
  1508.           Smalltalk  with  boolean objects which execute the indicated
  1509.           code block or not, depending on their truth-value.14
  1510.  
  1511.  
  1512.  
  1513.  
  1514.  
  1515.  
  1516.  
  1517.  
  1518.  
  1519.  
  1520.  
  1521.  
  1522.                                       -24-
  1523.  
  1524.  
  1525.                In the case of our example, the actual code within  the
  1526.           block  sends an error message to the current object.  error:
  1527.           is handled by the parent class Object, and will  pop  up  an
  1528.           appropriate  complaint when the user tries to write too many
  1529.           checks.  In general, the way you handle  a  fatal  error  in
  1530.           Smalltalk  is  to send an error message to yourself (through
  1531.           the "self" pseudo-variable),  and  let  the  error  handling
  1532.           mechanisms inherited from the Object class take over.
  1533.                As  you  might guess, there is also an ifFalse: message
  1534.           which booleans  accept.   It  works  exactly  like  ifTrue:,
  1535.           except  that  the logic has been reversed; a boolean "false"
  1536.           will execute the codeblock, and a boolean "true" will not.
  1537.                You should take a little time to play with this  method
  1538.           of  representing  conditionals.  You can run your checkbook,
  1539.           but can also invoke the conditional functions directly:
  1540.                true ifTrue: [ 'Hello, world!' printNl ] !
  1541.                false ifTrue: [ 'Hello, world!' printNl ] !
  1542.                true ifFalse: [ 'Hello, world!' printNl ] !
  1543.                false ifFalse: [ 'Hello, world!' printNl ] !
  1544.  
  1545.           66..22..  IItteerraattiioonn aanndd ccoolllleeccttiioonnss
  1546.                Now that we have some  sanity  checking  in  place,  it
  1547.           remains  for  us  to  keep a log of the checks we write.  We
  1548.           will do so by adding a Dictionary  object  to  our  Checking
  1549.           class,  logging  checks into it, and providing some messages
  1550.           for querying our check-writing history.  But  this  enhance-
  1551.           ment  brings  up  a very interesting question-when we change
  1552.           the "shape" of an object (in this  case,  by  adding  a  new
  1553.           _i_n_s_t_a_n_c_e  _v_a_r_i_a_b_l_e  to  the  Checking class-our dictionary),
  1554.           what happens to the existing class, and its objects?
  1555.                The answer is that the old objects  continue  to  exist
  1556.           with their current shape.15 New objects will  have  the  new
  1557.  
  1558.  
  1559.  
  1560.             14 It is interesting to note that because of the
  1561.  
  1562.  
  1563.           way  conditionals are done, conditional constructs
  1564.  
  1565.  
  1566.           are not part of the  Smalltalk  language-they  are
  1567.  
  1568.  
  1569.           merely a defined behavior for the Boolean class of
  1570.  
  1571.  
  1572.           objects.
  1573.  
  1574.  
  1575.             15 This  is  the  case  in GNU Smalltalk.  Other
  1576.  
  1577.  
  1578.           implementations will refuse to redefine the  class
  1579.  
  1580.  
  1581.  
  1582.  
  1583.  
  1584.  
  1585.  
  1586.  
  1587.  
  1588.                                       -25-
  1589.  
  1590.  
  1591.           shape.   As  this  can lead to _v_e_r_y puzzling behavior, it is
  1592.           usually best to eradicate all of the old objects,  and  then
  1593.           implement your changes.  If this were more than a toy object
  1594.           accounting system, this would  probably  entail  saving  the
  1595.           objects  off,  converting  to the new class, and reading the
  1596.           objects back into the  new  format.   For  now,  we'll  just
  1597.           ignore  what's currently there, and define our latest Check-
  1598.           ing class.
  1599.                Account subclass: #Checking
  1600.                     instanceVariableNames: 'checknum checksleft history'
  1601.                     classVariableNames: ''
  1602.                     poolDictionaries: ''
  1603.                     category: nil !
  1604.                This is the same syntax as the last time we  defined  a
  1605.           checking  account,  except that we have _t_h_r_e_e instance vari-
  1606.           ables-the "checknum" and "checksleft" which have always been
  1607.           there,  and our new "history" variable.  We must now feed in
  1608.           our definitions for each of the messages our object can han-
  1609.           dle,  since  we  are basically defining a new class under an
  1610.           old name.16 Go ahead and do  this  now-the  methods  are  in
  1611.           chapter 5.  We are using the same Account class, so you only
  1612.           need to do the Checking methods.
  1613.                With our new Checking instance variable, we are all set
  1614.           to  start  recording our checking history.  Our first change
  1615.           will be in the "init" message handling:
  1616.                !Checking methodsFor: 'initialization'!
  1617.                init
  1618.                     checksleft := 0.
  1619.                     history := Dictionary new.
  1620.                     ^ super init
  1621.                !!
  1622.           This provides us with a Dictionary, and hooks it to our  new
  1623.  
  1624.  
  1625.  
  1626.           until  _a_l_l  of its instances have been hunted down
  1627.  
  1628.  
  1629.           and eradicated!
  1630.  
  1631.  
  1632.             16 Technically, GNU Smalltalk has associated  us
  1633.  
  1634.  
  1635.           with  the  existing  _c_l_a_s_s methods, but with a new
  1636.  
  1637.  
  1638.           set of _i_n_s_t_a_n_c_e methods.  It is often  simpler  to
  1639.  
  1640.  
  1641.           work  as  if  you had to define everything, rather
  1642.  
  1643.  
  1644.           than trying to take advantage of this.
  1645.  
  1646.  
  1647.  
  1648.  
  1649.  
  1650.  
  1651.  
  1652.  
  1653.  
  1654.                                       -26-
  1655.  
  1656.  
  1657.           "history" variable.
  1658.                Our  next  method  records  each check as it's written.
  1659.           The method is a little more involved, as  we've  added  some
  1660.           more sanity checks to the writing of checks.
  1661.                !Checking methodsFor: 'spending'!
  1662.                writeCheck: amount
  1663.                     | num |
  1664.  
  1665.                     "Sanity check that we have checks left in our checkbook"
  1666.                     (checksleft < 1)
  1667.                          ifTrue: [ ^self error: 'Out of checks' ].
  1668.  
  1669.                     "Make sure we've never used this check number before"
  1670.                     num := checknum.
  1671.                     (history includesKey: num)
  1672.                          ifTrue: [ ^self error: 'Duplicate check number' ].
  1673.  
  1674.                     "Record the check number and amount"
  1675.                     history at: num put: amount.
  1676.  
  1677.                     "Update our next checknumber, checks left, and balance"
  1678.                     checknum := checknum + 1.
  1679.                     checksleft := checksleft - 1.
  1680.                     self spend: amount.
  1681.                     ^ num
  1682.                !!
  1683.                We  have  added  three  things to our latest version of
  1684.           writeCheck:.  First, since our routine has  become  somewhat
  1685.           involved,  we  have  added  comments.   In Smalltalk, single
  1686.           quotes are used for strings; double quotes enclose comments.
  1687.           We have added comments before each section of code.
  1688.                Second,  we have added a sanity check on the check num-
  1689.           ber we propose to use.  Dictionary objects  respond  to  the
  1690.           includesKey:  message  with  a boolean, depending on whether
  1691.           something is currently stored under the  given  key  in  the
  1692.           dictionary.  If the check number is already used, the error:
  1693.           message is sent to our object, aborting the operation.
  1694.                Finally, we add a new entry to the dictionary.  We have
  1695.           already  seen  the  at:put: message from chapter 2.  Our use
  1696.           here simply associates a check  number  with  an  amount  of
  1697.           money  spent.17  With  this,  we now have a working Checking
  1698.  
  1699.  
  1700.  
  1701.             17 You  might  start to wonder what one would do
  1702.  
  1703.  
  1704.           if you wished to associate _t_w_o pieces of  informa-
  1705.  
  1706.  
  1707.           tion  under  one  key.  Say, the value and who the
  1708.  
  1709.  
  1710.           check was written to.  There are several ways; the
  1711.  
  1712.  
  1713.  
  1714.  
  1715.  
  1716.  
  1717.  
  1718.  
  1719.  
  1720.                                       -27-
  1721.  
  1722.  
  1723.           class, with reasonable sanity checks and per-check  informa-
  1724.           tion.
  1725.                Let  us  finish the chapter by enhancing our ability to
  1726.           get access to all this information.  We will start with some
  1727.           simple print-out functions.
  1728.                !Checking methodsFor: 'printing'!
  1729.                printOn: stream
  1730.                     super printOn: stream.
  1731.                     ', checks left: ' printOn: stream.
  1732.                     checksleft printOn: stream.
  1733.                     ', checks written: ' printOn: stream.
  1734.                     (history size) printOn: stream.
  1735.                !
  1736.                check: num
  1737.                     | c |
  1738.                     c := history at: num ifAbsent: [ ^self error: 'No such check #' ].
  1739.                     ^c
  1740.                !!
  1741.           There  should  be  very  few  surprises here.  We format and
  1742.           print our information, while letting our parent classes han-
  1743.           dle  their  own  share of the work.  When looking up a check
  1744.           number, we once again take advantage of the fact that blocks
  1745.           of executable statements are an object; in this case, we are
  1746.           using the at:ifAbsent: message supported by  the  Dictionary
  1747.           class.   If the requested key value is not found in the dic-
  1748.           tionary, the code block is executed.  This allows us to cus-
  1749.           tomize  our  error handling, as the generic error would only
  1750.           tell the user "key not found".
  1751.                While we can look up a check if we know its number,  we
  1752.           have  not  yet written a way to "riffle through" our collec-
  1753.           tion of checks.   The  following  function  loops  over  the
  1754.           checks,  printing  them  out one per line.  Because there is
  1755.  
  1756.  
  1757.  
  1758.           best  would  probably  be  to create a new, custom
  1759.  
  1760.  
  1761.           object which contained this information, and  then
  1762.  
  1763.  
  1764.           store  this  object  under the check number key in
  1765.  
  1766.  
  1767.           the dictionary.  It would also  be  valid  (though
  1768.  
  1769.  
  1770.           probably  over-kill)  to store a dictionary as the
  1771.  
  1772.  
  1773.           value-and then store as many pieces of information
  1774.  
  1775.  
  1776.           as you'd like under each slot!
  1777.  
  1778.  
  1779.  
  1780.  
  1781.  
  1782.  
  1783.  
  1784.  
  1785.  
  1786.                                       -28-
  1787.  
  1788.  
  1789.           currently only a single numeric value under each  key,  this
  1790.           might seem wasteful.  But we have already considered storing
  1791.           multiple values under each check number, so it  is  best  to
  1792.           leave  some  room for each item.  And, of course, because we
  1793.           are simply sending a printing message to an object, we  will
  1794.           not  have to come back and re-write this code so long as the
  1795.           object in the dictionary honors  our  printNl/printOn:  mes-
  1796.           sages.
  1797.                !Checking methodsFor: 'printing'!
  1798.                printChecks
  1799.                     history associationsDo: [:assoc|
  1800.                          (assoc key) print.
  1801.                          ' - ' print.
  1802.                          (assoc value) printNl.
  1803.                     ]
  1804.                !!
  1805.           We  still  see  a code block object being passed to the dic-
  1806.           tionary, but ":assoc|" is something new.  A code  block  can
  1807.           optionally receive _a_r_g_u_m_e_n_t_s.  In this case, the argument is
  1808.           the key/value pair, known in Smalltalk  as  an  _A_s_s_o_c_i_a_t_i_o_n.
  1809.           This  is  the  way  that  a  dictionary  object  stores  its
  1810.           key/value pairs internally.   In  fact,  when  you  sent  an
  1811.           at:put:  message  to a dictionary object, the first thing it
  1812.           does is pack them into a new  object  from  the  Association
  1813.           class.  If you only wanted the value portion, you could call
  1814.           history with a do: message instead.
  1815.                Our code merely uses the "key" and "value" messages  to
  1816.           ask  the association for the two values.  We then invoke our
  1817.           printing interface upon them.   While  the  printNl  message
  1818.           implicitly  uses "stdout", we don't want a newline until the
  1819.           end, so the "print" message is used instead.  It  is  pretty
  1820.           much the same as "printNl", except it doesn't add a newline.
  1821.                It is important that you be clear on  the  relationship
  1822.           between an Association and the argument to a code block.  In
  1823.           this example, we passed a associationsDo: message to a  dic-
  1824.           tionary.  A dictionary invokes the passed code block with an
  1825.           Association when processing an associationsDo: message.  But
  1826.           code  blocks  can  receive  _a_n_y type of argument-the type is
  1827.           determined by the code which invokes the  code  block;  Dic-
  1828.           tionary,  in  this case.  In the next chapter we'll see more
  1829.           on how code blocks are used; we'll also look at how you  can
  1830.           invoke code blocks in your own code.
  1831.  
  1832.  
  1833.  
  1834.  
  1835.  
  1836.  
  1837.  
  1838.  
  1839.  
  1840.  
  1841.  
  1842.  
  1843.  
  1844.  
  1845.  
  1846.  
  1847.  
  1848.  
  1849.  
  1850.  
  1851.  
  1852.                                       -29-
  1853.  
  1854.  
  1855.           77..  CCooddee bblloocckkss,, ppaarrtt ttwwoo
  1856.                In the last chapter, we looked at how code blocks could
  1857.           be used to build conditional expressions, and how you  could
  1858.           iterate across all entries in a collection.18 We  built  our
  1859.           own  code  blocks,  and  handed  them  off for use by system
  1860.           objects.  But there is nothing  magic  about  invoking  code
  1861.           blocks;  your own code will often need to do so.  This chap-
  1862.           ter  will  shows  some  examples  of  loop  construction  in
  1863.           Smalltalk,  and  then demonstrate how you invoke code blocks
  1864.           for yourself.
  1865.  
  1866.           77..11..  IInntteeggeerr llooooppss
  1867.                Integer loops are constructed by telling  a  number  to
  1868.           drive the loop.  Try this example to count from 1 to 20:
  1869.                1 to: 20 do: [:x| x printNl ] !
  1870.           There's also a way to count up by more than one:
  1871.                1 to: 20 by: 2 do: [:x| x printNl ] !
  1872.           Finally, counting down is done with a negative interval:
  1873.                20 to: 1 by: -1 do: [:x| x printNl ] !
  1874.  
  1875.           77..22..  IInntteerrvvaallss
  1876.                It  is also possible to represent a range of numbers as
  1877.           a standalone object.  This allows you to represent  a  range
  1878.           of  numbers  as  a single object, which can be passed around
  1879.           the system.
  1880.                Smalltalk at: #i put: (Interval from: 5 to: 10) !
  1881.                i printNl !
  1882.                i do: [:x| x printNl] !
  1883.           As with the integer  loops,  the  Interval  class  can  also
  1884.  
  1885.  
  1886.  
  1887.             18 The  do:  message is understood by most types
  1888.  
  1889.  
  1890.           of Smalltalk collections.  It works for  the  Dic-
  1891.  
  1892.  
  1893.           tionary  class,  as well as sets, arrays, strings,
  1894.  
  1895.  
  1896.           intervals, linked lists, bags, and  streams.   The
  1897.  
  1898.  
  1899.           associationsDo: message works only with dictionar-
  1900.  
  1901.  
  1902.           ies.  The difference is that do: passes  only  the
  1903.  
  1904.  
  1905.           _v_a_l_u_e  portion,  while  associationsDo: passes the
  1906.  
  1907.  
  1908.           entire _k_e_y/_v_a_l_u_e pair in an Association object.
  1909.  
  1910.  
  1911.  
  1912.  
  1913.  
  1914.  
  1915.  
  1916.  
  1917.  
  1918.                                       -30-
  1919.  
  1920.  
  1921.           represent steps greater than 1.  It is done much like it was
  1922.           for our numeric loop above:
  1923.                i := (Interval from: 5 to: 10 by: 2)
  1924.                i printNl !
  1925.                i do: [:x| x printNl] !
  1926.  
  1927.           77..33..  IInnvvookkiinngg ccooddee bblloocckkss
  1928.                Let us revisit the checking example and  add  a  method
  1929.           for  scanning only checks over a certain amount.  This would
  1930.           allow our user to find "big" checks, by passing in  a  value
  1931.           below  which  we  will  not  invoke their function.  We will
  1932.           invoke their code block with the check number  as  an  argu-
  1933.           ment;  they  can  use our existing check: message to get the
  1934.           amount.
  1935.                !Checking methodsFor: 'scanning'!
  1936.                checksOver: amount do: aBlock
  1937.                     history associationsDo: [:assoc|
  1938.                          ((assoc value) > amount)
  1939.                               ifTrue: [aBlock value: (assoc key)]
  1940.                     ]
  1941.                !!
  1942.           The structure of this loop is much like our printChecks mes-
  1943.           sage from chapter 6.  However, in this case we consider each
  1944.           entry, and only invoke the supplied  block  if  the  check's
  1945.           value is greater than the specified amount.  The line:
  1946.                ifTrue: [aBlock value: (assoc key)]
  1947.           invokes  the user-supplied block, passing as an argument the
  1948.           association's key, which is the check  number.   The  value:
  1949.           message,  when  received  by  a  code block, causes the code
  1950.           block to  execute.   Code  blocks  take  "value",  "value:",
  1951.           "value:value:",  and  "value:value:value:"  messages, so you
  1952.           can pass from 0 to 3 arguments to a code block.19 You  might
  1953.           find  it  puzzling  that an association takes a "value" mes-
  1954.           sage, and so does a code block.  Remember, each  object  can
  1955.           do its own thing with a message.  A code block gets _r_u_n when
  1956.           it  receives  a  "value"  message.   An  association  merely
  1957.           returns the value part of its key/value pair.  The fact that
  1958.           both take the same message is, in this case, coincidence.
  1959.                Let's quickly set up a new checking account  with  $250
  1960.           (wouldn't  this  be  nice  in real life?) and write a couple
  1961.           checks.  Then we'll see if our new method does the job  cor-
  1962.           rectly:
  1963.  
  1964.  
  1965.  
  1966.  
  1967.  
  1968.             19 There is also a  valueWithArguments:  message
  1969.  
  1970.  
  1971.           which  accepts  an array holding as many arguments
  1972.  
  1973.  
  1974.           as you would like.
  1975.  
  1976.  
  1977.  
  1978.  
  1979.  
  1980.  
  1981.  
  1982.  
  1983.  
  1984.                                       -31-
  1985.  
  1986.  
  1987.                Smalltalk at: #mycheck put: (Checking new) !
  1988.                mycheck deposit: 250 !
  1989.                mycheck newChecks: 100 count: 40 !
  1990.                mycheck writeCheck: 10 !
  1991.                mycheck writeCheck: 52 !
  1992.                mycheck writeCheck: 15 !
  1993.                mycheck checksOver: 1 do: [:x| printNl] !
  1994.                mycheck checksOver: 17 do: [:x| printNl] !
  1995.                mycheck checksOver: 200 do: [:x| printNl] !
  1996.                We  will finish this chapter with an alternative way of
  1997.           writing our checksOver: code.  In this example, we will  use
  1998.           the  message  select:  to  pick  the checks which exceed our
  1999.           value, instead of doing the comparison  ourselves.   We  can
  2000.           then  invoke the new resulting collection against the user's
  2001.           code   block.    Unlike   our   previous    definition    of
  2002.           checksOver:do:,  this  one  passes the user's code block the
  2003.           association, not just a check number.  How could  this  code
  2004.           be rewritten to remedy this, while still using select:?
  2005.                !Checking methodsFor: 'scanning'!
  2006.                checksOver: amount do: aBlock
  2007.                     | chosen |
  2008.                     chosen := history select: [:amt| amt > amount].
  2009.                     chosen associationsDo: aBlock
  2010.                !!
  2011.                You  can  use  the same set of tests that we ran above.
  2012.           Notice that our code block:
  2013.                [:x| x printNl]
  2014.           now prints out an  Association.   This  has  the  very  nice
  2015.           effect--with  our  old method, we were told which check num-
  2016.           bers were above a given amount.  With this  new  method,  we
  2017.           get  the  check number and amount in the form of an Associa-
  2018.           tion.  When we print an association, since the  key  is  the
  2019.           check  number  and  the  value is the check amount, we get a
  2020.           list of checks over the amount in the format:
  2021.                CheckNum -> CheckVal
  2022.  
  2023.  
  2024.  
  2025.  
  2026.  
  2027.  
  2028.  
  2029.  
  2030.  
  2031.  
  2032.  
  2033.  
  2034.  
  2035.  
  2036.  
  2037.  
  2038.  
  2039.  
  2040.  
  2041.  
  2042.  
  2043.  
  2044.  
  2045.  
  2046.  
  2047.  
  2048.  
  2049.  
  2050.                                       -32-
  2051.  
  2052.  
  2053.           88..  WWhheenn TThhiinnggss GGoo BBaadd
  2054.                So far we've been working with examples which work  the
  2055.           first time.  If you didn't type them in correctly, you prob-
  2056.           ably received a flood  of  unintelligible  complaints.   You
  2057.           probably  ignored  the  complaints,  and  typed  the example
  2058.           again.
  2059.                When developing your own Smalltalk code, however, these
  2060.           messages  are the way you find out what went wrong.  Because
  2061.           your objects, their methods, the error  printout,  and  your
  2062.           interactive  environment  are  all contained within the same
  2063.           Smalltalk session, you can use these error messages to debug
  2064.           your code using very powerful techniques.
  2065.  
  2066.           88..11..  AA SSiimmppllee EErrrroorr
  2067.                First, let's take a look at a typical error.  Type:
  2068.                7 plus: 1 !
  2069.           This will print out:
  2070.                7 did not understand selector 'plus:'
  2071.  
  2072.                UndefinedObject>>#executeStatements
  2073.                UndefinedObject>>nil
  2074.           The  first  line  is pretty simple; we sent a message to the
  2075.           "7" object which was not understood;  not  surprising  since
  2076.           the  "plus" operation should have been "+".  The two remain-
  2077.           ing lines reflect the way the  GNU  Smalltalk  invokes  code
  2078.           which we type to our command prompt; it generates a block of
  2079.           code which is invoked via an  internal  function  "executeS-
  2080.           tatements".   Thus,  this output tells you that you directly
  2081.           typed a line which  sent  an  invalid  message  to  the  "7"
  2082.           object.
  2083.                The  last  two lines of the error output are actually a
  2084.           stack backtrace.  The most recent call is the one nearer the
  2085.           top  of  the  screen.  In the next example, we will cause an
  2086.           error which happens deeper within an object.
  2087.  
  2088.           88..22..  NNeesstteedd CCaallllss
  2089.                Type the following lines:
  2090.                Smalltalk at: #x put: (Dictionary new) !
  2091.                x at: 1 !
  2092.           The error you receive will look like:
  2093.                Dictionary new: 32 "<0x33788>" error: key not found
  2094.  
  2095.                MethodContext>>#value
  2096.                Dictionary>>#at:ifAbsent:
  2097.                Dictionary>>#at
  2098.                UndefinedObject>>#executeStatements
  2099.                UndefinedObject>>nil
  2100.                The error itself is pretty clear; we  asked  for  some-
  2101.           thing  within the Dictionary which wasn't there.  The object
  2102.           which had the error is identified as "Dictionary  new:  32".
  2103.           A  Dictionary's default size is 32; thus, this is the object
  2104.           we created with "Dictionary new".
  2105.                The stack backtrace shows us the inner structure of how
  2106.           a  Dictionary responds to the at: message.  Our hand-entered
  2107.  
  2108.  
  2109.  
  2110.  
  2111.  
  2112.  
  2113.  
  2114.  
  2115.  
  2116.                                       -33-
  2117.  
  2118.  
  2119.           command causes the usual two entries for  "UndefinedObject".
  2120.           Then  we see a Dictionary object responding to an "at:" mes-
  2121.           sage (the "Dictionary>>#at" line).   This  code  called  the
  2122.           object  with  an "at:ifAbsent:" message.  All of a sudden, a
  2123.           different object receives a "value" message,  and  then  the
  2124.           error happened.
  2125.                This  isn't  quite true; the error happened in the Dic-
  2126.           tionary object.  The mystery is where  this  "MethodContext"
  2127.           came  from.   Fortunately,  it isn't much of a mystery.  The
  2128.           answer lies in what we covered in  the  last  two  chapters:
  2129.           code blocks.
  2130.                A  very  common way to handle errors in Smalltalk is to
  2131.           hand down a block of code which will be called when an error
  2132.           occurs.   For  the Dictionary code, the "at:" message passes
  2133.           in a block of code to the at:ifAbsent:  code  to  be  called
  2134.           when "at:ifAbsent:" can't find the given key.  Thus, without
  2135.           even looking at the code for Dictionary itself, we can guess
  2136.           that  the  Dictionary "at:" message handling looks something
  2137.           like:
  2138.                at: key ifAbsent: errCodeBlock
  2139.                     ...look for key...
  2140.                     (keyNotFound) ifTrue: [ ^(errCodeBlock value) ]
  2141.                     ...
  2142.  
  2143.                at: key
  2144.                     ^self at: key ifAbsent: [^self error: 'key not found']
  2145.           The  key  is  that  we  see  in  the  stack  backtrace  that
  2146.           at:ifAbsent:  is  called  from  at:,  and a MethodContext is
  2147.           called to give the error.  Once we realize that a MethodCon-
  2148.           text  is  just  a  fancy name for a code block, we can guess
  2149.           that at: handed in a code  block  to  print  an  error,  and
  2150.           at:ifAbsent:  used  the  standard  "value" message to invoke
  2151.           this code block when it  realized  that  the  requested  key
  2152.           couldn't be found in the Dictionary.
  2153.                It  would  be nice if each entry on the stack backtrace
  2154.           included source line numbers.  Unfortunately, at this  point
  2155.           GNU  Smalltalk doesn't provide this feature.  Of course, you
  2156.           have the source code available....
  2157.  
  2158.           88..33..  SSoommee SShhoorrttccoommiinnggss iinn GGNNUU SSmmaallllttaallkk
  2159.                Unfortunately,  there  are  some   errors   which   GNU
  2160.           Smalltalk  is  not very helpful in detecting.  This informa-
  2161.           tion applies to the latest version  currently  available-GNU
  2162.           Smalltalk  1.1.1.   Try  indexing  something which isn't any
  2163.           sort of Collection:
  2164.                (7 at: 99) printNl !
  2165.           One  would  expect  to  receive  an error,20 but instead GNU
  2166.  
  2167.  
  2168.  
  2169.             20 And in fact, you _w_i_l_l  receive  an  error  in
  2170.  
  2171.  
  2172.           most Smalltalk systems.
  2173.  
  2174.  
  2175.  
  2176.  
  2177.  
  2178.  
  2179.  
  2180.  
  2181.  
  2182.                                       -34-
  2183.  
  2184.  
  2185.           Smalltalk simply returns the receiving object-7.  Similarly,
  2186.           one would expect Array bounds to be checked:
  2187.                Smalltalk at: #x put: (Array new: 10) !
  2188.                (x at: 7 put: 123) printNl !
  2189.                (x at: 11 put: 1234) printNl !
  2190.                (x at: 7) printNl !
  2191.                (x at: 11) printNl !
  2192.           But this example returns no error in GNU  Smalltalk.21  When
  2193.           an  assignment  to  an  array  slot is correct, the returned
  2194.           value is the value assigned-123  in  this  case.   When  you
  2195.           assign  outside the array bounds, you will receive the array
  2196.           object itself as the  result!   Thus,  if  you  accidentally
  2197.           index  your  array  incorrectly, you will have to figure out
  2198.           what happened from a place further in  your  code  where  an
  2199.           error  crops up because your code was trying to operate upon
  2200.           an _e_l_e_m_e_n_t of the array, but instead is working on the array
  2201.           itself.
  2202.  
  2203.           88..44..  LLooookkiinngg aatt OObbjjeeccttss
  2204.                When  you  are chasing an error, it is often helpful to
  2205.           examine the  instance  variables  of  your  objects.   While
  2206.           strategic  "printNl"s will no doubt help, you can look at an
  2207.           object without having to write all the code  yourself.   The
  2208.           "inspect"  message  works  on  any object, and dumps out the
  2209.           values of each instance variable within the object.  Thus:
  2210.                Smalltalk at: #x put: (Interval from: 1 to: 5) !
  2211.                x inspect !
  2212.           displays:
  2213.                An instance of Interval
  2214.                  start: 1
  2215.                  stop: 5
  2216.                  step: 1
  2217.                There's one thing the object inspector doesn't display-
  2218.           the  contents  of an _i_n_d_e_x_e_d _c_l_a_s_s.  Since we haven't looked
  2219.           at this kind of object yet, we'll  leave  this  to  its  own
  2220.           chapter.
  2221.                We'll  finish  this  chapter by emphasizing a technique
  2222.           which has already been covered-the use of the "error:"  mes-
  2223.           sage  in  your  own objects.  As you saw in the case of Dic-
  2224.           tionary, an object can send itself an error: message with  a
  2225.           descriptive string to abort execution and dump a stack back-
  2226.           trace.  You should plan on using this technique in your  own
  2227.           objects.   It  can  be  used  both  for explicit user-caused
  2228.           errors, as well as in internal sanity checks.
  2229.  
  2230.  
  2231.  
  2232.  
  2233.  
  2234.  
  2235.             21 Again,  it _w_i_l_l error in most other Smalltalk
  2236.  
  2237.  
  2238.           implementations.
  2239.  
  2240.  
  2241.  
  2242.  
  2243.  
  2244.  
  2245.  
  2246.  
  2247.  
  2248.                                       -35-
  2249.  
  2250.  
  2251.           99..  CCooeexxiissttiinngg iinn tthhee CCllaassss HHiieerraarrcchhyy
  2252.                The early chapters of this paper discussed  classes  in
  2253.           one of two ways.  The "toy" classes we developed were rooted
  2254.           at Object;  the  system-provided  classes  were  treated  as
  2255.           immutable entities.  While one shouldn't modify the behavior
  2256.           of the standard classes  lightly,  "plugging  in"  your  own
  2257.           classes  in  the  right  place  among  their system-provided
  2258.           brethren can provide you powerful new classes with very lit-
  2259.           tle effort.
  2260.                This  chapter  will  create  two complete classes which
  2261.           enhance the existing Smalltalk  hierarchy.   The  discussion
  2262.           will  start  with  the  issue  of  where  to connect our new
  2263.           classes, and then continue onto implementation.   Like  most
  2264.           programming  efforts,  the result will leave many possibili-
  2265.           ties for improvements.  The framework, however, should begin
  2266.           to  give  you  an  intuition  of  how  to  develop  your own
  2267.           Smalltalk classes.
  2268.  
  2269.           99..11..  TThhee EExxiissttiinngg CCllaassss HHiieerraarrcchhyy
  2270.                To discuss where a new class might go, it is helpful to
  2271.           have  a  map  of  the current classes.  The following is the
  2272.           class hierarchy of GNU Smalltalk 1.1.1.   Indentation  means
  2273.           that  the  line inherits from the earlier line with one less
  2274.           level of indentation.22
  2275.  
  2276.  
  2277.  
  2278.  
  2279.  
  2280.  
  2281.  
  2282.  
  2283.  
  2284.  
  2285.  
  2286.  
  2287.  
  2288.  
  2289.  
  2290.  
  2291.  
  2292.  
  2293.  
  2294.  
  2295.             22 This listing is courtesy of the  printHierar-
  2296.  
  2297.  
  2298.           chy  method supplied by GNU Smalltalk author Steve
  2299.  
  2300.  
  2301.           Byrne.  If you have the GNU Smalltalk source, it's
  2302.  
  2303.  
  2304.           in the samples/ directory.
  2305.  
  2306.  
  2307.  
  2308.  
  2309.  
  2310.  
  2311.  
  2312.  
  2313.  
  2314.                                       -36-
  2315.  
  2316.  
  2317.                Object
  2318.                    Autoload
  2319.                    Behavior
  2320.                        ClassDescription
  2321.                            Class
  2322.                            Metaclass
  2323.                    BlockContext
  2324.                    Boolean
  2325.                        False
  2326.                        True
  2327.                    CFunctionDescriptor
  2328.                    CObject
  2329.                    Collection
  2330.                        Bag
  2331.                        MappedCollection
  2332.                        SequenceableCollection
  2333.                            ArrayedCollection
  2334.                                Array
  2335.                                ByteArray
  2336.                                CompiledMethod
  2337.                                String
  2338.                                    Symbol
  2339.                            Interval
  2340.                            LinkedList
  2341.                                Semaphore
  2342.                            OrderedCollection
  2343.                                SortedCollection
  2344.                        Set
  2345.                            Dictionary
  2346.                                IdentityDictionary
  2347.                                SystemDictionary
  2348.                    Delay
  2349.                    FileSegment
  2350.                    Link
  2351.                        Process
  2352.                        SymLink
  2353.                    Magnitude
  2354.                        Character
  2355.                        Date
  2356.                        LookupKey
  2357.                            Association
  2358.                        Number
  2359.                            Float
  2360.                            Integer
  2361.                        Time
  2362.                    Memory
  2363.                        ByteMemory
  2364.                        WordMemory
  2365.                    Message
  2366.                    MethodContext
  2367.                    MethodInfo
  2368.                    ProcessorScheduler
  2369.                    SharedQueue
  2370.                    Stream
  2371.  
  2372.  
  2373.  
  2374.  
  2375.  
  2376.  
  2377.  
  2378.  
  2379.  
  2380.                                       -37-
  2381.  
  2382.  
  2383.                        PositionableStream
  2384.                            ReadStream
  2385.                            WriteStream
  2386.                                ReadWriteStream
  2387.                                    FileStream
  2388.                        Random
  2389.                        TokenStream
  2390.                    UndefinedObject
  2391.                While  initially  a  daunting list, you should take the
  2392.           time to hunt down the classes we've examined in  this  paper
  2393.           so  far.   Notice,  for instance, how an Array is a subclass
  2394.           below the "SequenceableCollection" class.  This makes sense;
  2395.           you  can  walk  an Array from one end to the other.  By con-
  2396.           trast, notice how a Set is at the same  level  as  Sequence-
  2397.           ableCollection.   It  doesn't  make sense to walk a Set from
  2398.           one end to the other.
  2399.                A little puzzling is the relationship of  a  Dictionary
  2400.           to  a  Set;  why  is  a Dictionary a subclass of a Set?  The
  2401.           answer lies in the basic structure of both a Set and a  Dic-
  2402.           tionary.  Both hold an unordered collection of objects.  For
  2403.           a set, they're _a_n_y objects; for a Dictionary, they are Asso-
  2404.           ciations.   Thus, Dictionary inherits some of the more basic
  2405.           mechanisms for creating itself, and then adds an extra layer
  2406.           of interpretation.
  2407.                Finally, look at the treatment of numbers-starting with
  2408.           the class Magnitude.  While numbers can be ordered by  "less
  2409.           than",  "greater  than",  and  so  forth, so can a number of
  2410.           _o_t_h_e_r objects.   Each  subclass  of  Magnitude  is  such  an
  2411.           object.  So we can compare characters with other characters,
  2412.           dates with other dates, and times with other times, as  well
  2413.           as numbers with numbers.23
  2414.  
  2415.           99..22..  TThhoossee DDaarrnn AArrrraayyss
  2416.                Imagine that you're chasing an array problem,  and  the
  2417.           lack  of  a  clear  bounds check is making it too hard.  You
  2418.           could modify the Smalltalk implementation, but perhaps  it's
  2419.           in  somebody  else's directory, so it wouldn't be practical.
  2420.           Why not add a subclass, put some sanity checks in the  array
  2421.           indexing, and use our superclass to do all the work?
  2422.  
  2423.  
  2424.  
  2425.  
  2426.  
  2427.  
  2428.  
  2429.  
  2430.  
  2431.  
  2432.  
  2433.             23 Ignore  LookupKey; its presence appears to be
  2434.  
  2435.  
  2436.           historical.
  2437.  
  2438.  
  2439.  
  2440.  
  2441.  
  2442.  
  2443.  
  2444.  
  2445.  
  2446.                                       -38-
  2447.  
  2448.  
  2449.                Array variableSubclass: #CheckedArray
  2450.                     instanceVariableNames: ''
  2451.                     classVariableNames: ''
  2452.                     poolDictionaries: ''
  2453.                     category: nil !
  2454.  
  2455.                !CheckedArray methodsFor: 'bounds checking'!
  2456.                boundsCheck: index
  2457.                     ((index < 1) | (index > (self basicSize))) ifTrue: [
  2458.                          ^self illegalIndex
  2459.                     ]
  2460.                !
  2461.                illegalIndex
  2462.                     ^self error: 'Illegal index'
  2463.                !!
  2464.  
  2465.                !CheckedArray methodsFor: 'basic'!
  2466.                at: index
  2467.                     self boundsCheck: index.
  2468.                     ^super at: index
  2469.  
  2470.                !
  2471.                at: index put: val
  2472.                     self boundsCheck: index.
  2473.                     ^super at: index put: val
  2474.                !!
  2475.                Much  of  the  machinery  of  adding  a class should be
  2476.           familiar.  Instead of our usual subclass: message, we use  a
  2477.           variableSubclass:  message.   This  reflects  the underlying
  2478.           structure of an Array object; we'll  delay  discussing  this
  2479.           until  the  chapter on the nuts and bolts of arrays.  In any
  2480.           case, we _i_n_h_e_r_i_t all of the actual knowledge of how to  cre-
  2481.           ate arrays, reference them, and so forth.  All that we do is
  2482.           intercept at: and at:put:  messages,  and  call  our  common
  2483.           function to validate the array index.  The way that we coded
  2484.           the bounds check bears a little examination.
  2485.                Making a first cut at  coding  the  bounds  check,  you
  2486.           might  have coded the bounds check in CheckedArray's methods
  2487.           twice-once for at:, and again for at:put:.  As always,  it's
  2488.           preferable to code things _o_n_c_e, and then re-use them.  So we
  2489.           instead add a method for bounds checking "boundsCheck:", and
  2490.           use  it  for  both  cases.  If we ever wanted to enhance the
  2491.           bounds checking (perhaps enhance the error message to  print
  2492.           the  offending  index  value?), we only have to change it in
  2493.           one place.
  2494.                The actual math for calculating whether the bounds have
  2495.           been  violated  is  a little interesting.  The first part of
  2496.           the expression:
  2497.                ((index < 1) | (index > (self basicSize)))
  2498.           is true if the index is less than 1, otherwise  it's  false.
  2499.           This  part of the expression thus becomes the boolean object
  2500.           true or false.  The boolean object then receives the message
  2501.           "|",  and  the  argument  "(index > (self basicSize))".  "|"
  2502.           means "or"-we want to OR together the two  possible  illegal
  2503.  
  2504.  
  2505.  
  2506.  
  2507.  
  2508.  
  2509.  
  2510.  
  2511.  
  2512.                                       -39-
  2513.  
  2514.  
  2515.           range checks.  What is the second part of the expression?24
  2516.                "index"  is  our  argument, an integer; it receives the
  2517.           message ">", and thus will compare itself to the value "self
  2518.           basicSize" returns.  While we haven't covered the underlying
  2519.           structures Smalltalk uses to build arrays,  we  can  briefly
  2520.           say  that the "basicSize" message returns the number of ele-
  2521.           ments the Array object can contain.  So the index is checked
  2522.           to see if it's less than 1 (the lowest legal Array index) or
  2523.           greater than the highest allocated slot in the Array.  If it
  2524.           is either (the "|" operator), the expression is true, other-
  2525.           wise false.
  2526.                From there it's downhill; our boolean  object  receives
  2527.           the  ifTrue:  message,  and  a code block which will send an
  2528.           error message to the object.  Why do we have a separate mes-
  2529.           sage just to print the error?  For purposes of this example,
  2530.           it's not needed.  But one could conceive, in general,  of  a
  2531.           couple of different sanity checks all sharing the same mech-
  2532.           anism for actually printing the  error  message.   So  we'll
  2533.           write it this way anyway.
  2534.  
  2535.  
  2536.  
  2537.  
  2538.             24 Smalltalk also offers an "or:" message, which
  2539.  
  2540.  
  2541.           is different in a subtle way from "|".  or:  takes
  2542.  
  2543.  
  2544.           a  code  block, and only invokes the code block if
  2545.  
  2546.  
  2547.           it's necessary  to  determine  the  value  of  the
  2548.  
  2549.  
  2550.           expression.  This is analogous to the guaranteed C
  2551.  
  2552.  
  2553.           semantic that "&&" evaluates left-to-right only as
  2554.  
  2555.  
  2556.           far  as needed.  We could have written the expres-
  2557.  
  2558.  
  2559.           sions as "((index < 1) or: [index >  (self  basic-
  2560.  
  2561.  
  2562.           Size)])".  Since we expect both sides of or: to be
  2563.  
  2564.  
  2565.           false most of the time, there isn't much reason to
  2566.  
  2567.  
  2568.           delay evaluation of either side.
  2569.  
  2570.  
  2571.  
  2572.  
  2573.  
  2574.  
  2575.  
  2576.  
  2577.  
  2578.                                       -40-
  2579.  
  2580.  
  2581.           99..33..  AAddddiinngg aa NNeeww KKiinndd ooff NNuummbbeerr
  2582.                If we were programming an application which did a large
  2583.           amount of complex math, we could probably manage it  with  a
  2584.           number  of  two-element arrays.  But we'd forever be writing
  2585.           in-line code for the math and comparisons; it would be  much
  2586.           easier to just implement an object class to support the com-
  2587.           plex numeric type.  Where in the class hierarchy would it be
  2588.           placed?
  2589.                You've probably already guessed-but let's step down the
  2590.           hierarchy  anyway.   _E_v_e_r_y_t_h_i_n_g  inherits  from  Object,  so
  2591.           that's  a  safe  starting point.  Complex numbers can not be
  2592.           compared with "<" and ">", and yet we strongly suspect that,
  2593.           since  they are numbers, we should place them under the Num-
  2594.           ber class.  But Number inherits from  Magnitude--how  do  we
  2595.           resolve  this conflict?  A subclass can place itself under a
  2596.           superclass which allows some operations the subclass doesn't
  2597.           wish to allow.  All that you must do is make sure you inter-
  2598.           cept these messages and return an error.  So we  will  place
  2599.           our  new Complex class under Number, and make sure to disal-
  2600.           low comparisons.
  2601.                One can reasonably ask whether the real  and  imaginary
  2602.           parts  of  our  complex  number  will be integer or floating
  2603.           point.  In the grand Smalltalk tradition, we'll  just  leave
  2604.           them  as objects, and hope that they respond to numeric mes-
  2605.           sages reasonably.  If they don't, the  user  will  doubtless
  2606.           receive  errors and be able to track back their mistake with
  2607.           little fuss.
  2608.                We'll define the four basic math operators, as well  as
  2609.           the  (illegal)  relationals.  We'll add printOn: so that the
  2610.           printing methods work, and that should give us  our  Complex
  2611.           class.   The  class  as  presented suffers some limitations,
  2612.           which we'll cover later in the chapter.
  2613.  
  2614.  
  2615.  
  2616.  
  2617.  
  2618.  
  2619.  
  2620.  
  2621.  
  2622.  
  2623.  
  2624.  
  2625.  
  2626.  
  2627.  
  2628.  
  2629.  
  2630.  
  2631.  
  2632.  
  2633.  
  2634.  
  2635.  
  2636.  
  2637.  
  2638.  
  2639.  
  2640.  
  2641.  
  2642.  
  2643.  
  2644.                                       -41-
  2645.  
  2646.  
  2647.                Number subclass: #Complex
  2648.                     instanceVariableNames: 'realpart imagpart'
  2649.                     classVariableNames: ''
  2650.                     poolDictionaries: ''
  2651.                     category: nil !
  2652.                !Complex class methodsFor: 'creating'!
  2653.                new
  2654.                     ^self error: 'use real:imaginary:'
  2655.                !
  2656.                new: ignore
  2657.                     ^self new
  2658.                !
  2659.                real: r imaginary: i
  2660.                     ^(super new) setReal: r setImag: i
  2661.                !!
  2662.  
  2663.                !Complex methodsFor: 'creating--private'!
  2664.                setReal: r setImag: i
  2665.                     realpart := r.
  2666.                     imagpart := i.
  2667.                     ^self
  2668.                !!
  2669.  
  2670.                !Complex methodsFor: 'basic'!
  2671.                real
  2672.                     ^realpart
  2673.                !
  2674.                imaginary
  2675.                     ^imagpart
  2676.                !!
  2677.  
  2678.                !Complex methodsFor: 'math'!
  2679.                + val
  2680.                     ^Complex real: (realpart + (val real))
  2681.                          imaginary: (imagpart + (val imaginary))
  2682.                !
  2683.                - val
  2684.                     ^Complex real: (realpart - (val real))
  2685.                          imaginary: (imagpart - (val imaginary))
  2686.                !
  2687.                * val
  2688.                     ^Complex real: ((realpart * (val real)) - (imagpart * (val imaginary)))
  2689.                          imaginary: ((realpart * (val imaginary)) +
  2690.                               (imagpart * (val real)))
  2691.                !
  2692.                / val
  2693.                     | d r i |
  2694.                     d := ((val real) * (val real)) + ((val imaginary) * (val imaginary)).
  2695.                     r := ((realpart * (val real)) + (imagpart * (val imaginary))) / d.
  2696.                     i := ((imagpart * (val real)) - (realpart * (val imaginary))) / d.
  2697.                     ^Complex real: r imaginary: i
  2698.                !!
  2699.  
  2700.                !Complex methodsFor: 'comparison'!
  2701.  
  2702.  
  2703.  
  2704.  
  2705.  
  2706.  
  2707.  
  2708.  
  2709.  
  2710.                                       -42-
  2711.  
  2712.  
  2713.                = val
  2714.                     ^((realpart = (val real)) & (imagpart = (val imaginary)))
  2715.                !
  2716.                > val
  2717.                     ^self shouldNotImplement
  2718.                !
  2719.                >= val
  2720.                     ^self shouldNotImplement
  2721.                !
  2722.                < val
  2723.                     ^self shouldNotImplement
  2724.                !
  2725.                <= val
  2726.                     ^self shouldNotImplement
  2727.                !!
  2728.  
  2729.                !Complex methodsFor: 'printing'!
  2730.                printOn: aStream
  2731.                     aStream nextPut: $(.
  2732.                     realpart printOn: aStream.
  2733.                     aStream nextPut: $,.
  2734.                     imagpart printOn: aStream.
  2735.                     aStream nextPut: $)
  2736.                !!
  2737.                There should be surprisingly little which  is  actually
  2738.           new in this example.  The printing method uses both printOn:
  2739.           as well as nextPut: to do its printing.   While  we  haven't
  2740.           covered  it, it's pretty clear that "$(" generates the ASCII
  2741.           character "(" as an object, and nextPut: puts  its  argument
  2742.           as the next thing on the stream.
  2743.                The  math  operations all generate a new object, calcu-
  2744.           lating the real and imaginary parts, and invoking  the  Com-
  2745.           plex class to create the new object.  Our creation code is a
  2746.           little more compact than earlier examples; instead of  using
  2747.           a  local  variable to name the newly-created object, we just
  2748.           use the return value and send a message directly to the  new
  2749.           object.   Our  initialization  code explicitly returns self;
  2750.           what would happen if we left this off?25
  2751.  
  2752.           99..44..  IInnhheerriittaannccee aanndd PPoollyymmoorrpphhiissmm
  2753.                This is a good time to look at what we've done with the
  2754.           two   previous   examples  at  a  higher  level.   With  the
  2755.           CheckedArray class, we _i_n_h_e_r_i_t_e_d almost all of the function-
  2756.           ality  of  arrays,  with  only a little bit of code added to
  2757.  
  2758.  
  2759.  
  2760.             25 Hint: consider what the default return  value
  2761.  
  2762.  
  2763.           is  when  no explicit value is provided.  This was
  2764.  
  2765.  
  2766.           covered in chapter 4.
  2767.  
  2768.  
  2769.  
  2770.  
  2771.  
  2772.  
  2773.  
  2774.  
  2775.  
  2776.                                       -43-
  2777.  
  2778.  
  2779.           address our specific needs.  While you may have not  thought
  2780.           to try it, all the existing methods for an Array continue to
  2781.           work without further effort-you might find it interesting to
  2782.           ponder why the following still works:
  2783.                Smalltalk at: #a put: (CheckedArray new: 10) !
  2784.                a at: 5 put: 1234 !
  2785.                a do: [:i| i printNl ] !
  2786.           The  strength of inheritance is that you focus on the incre-
  2787.           mental changes you make; the things you  _d_o_n'_t  change  will
  2788.           generally continue to work.
  2789.                In  the  Complex  class,  the value of _p_o_l_y_m_o_r_p_h_i_s_m was
  2790.           exercised.  A Complex number responds to  exactly  the  same
  2791.           set of messages as any other number.  If you had handed this
  2792.           code to someone, they would know how to do math with Complex
  2793.           numbers  without  further instruction.  Compare this with C,
  2794.           where a complex number package would  require  the  user  to
  2795.           first   find  out  if  the  complex-add  function  was  com-
  2796.           plex_plus(), or  perhaps  complex_add(),  or  add_complex(),
  2797.           or....
  2798.  
  2799.           99..55..  LLiimmiittaattiioonnss ooff tthhee CCoommpplleexx CCllaassss
  2800.                One glaring deficiency is present in the Complex class-
  2801.           what happens if you mix normal numbers with Complex numbers?
  2802.           Currently,  the  Complex  class  assumes  that  it will only
  2803.           interact with other Complex numbers.  But this is  unrealis-
  2804.           tic-mathematically,  a "normal" number is simply one with an
  2805.           imaginary part of 0.  Smalltalk was designed to  allow  num-
  2806.           bers  to  _c_o_e_r_c_e themselves into a form which will work with
  2807.           other numbers.
  2808.                The system is clever and  requires  very  little  addi-
  2809.           tional  code.   Unfortunately,  it  would  have  tripled the
  2810.           amount of explanation required.  If you're interested in how
  2811.           coercion  works  in  GNU  Smalltalk,  you  should  find  the
  2812.           Smalltalk library source, and trace back  the  execution  of
  2813.           the  retry:coercing:  messages.   You  want  to consider the
  2814.           value which the "generality" message returns for  each  type
  2815.           of  number.   Finally,  you need to examine the coerce: han-
  2816.           dling in each numeric class.
  2817.  
  2818.  
  2819.  
  2820.  
  2821.  
  2822.  
  2823.  
  2824.  
  2825.  
  2826.  
  2827.  
  2828.  
  2829.  
  2830.  
  2831.  
  2832.  
  2833.  
  2834.  
  2835.  
  2836.  
  2837.  
  2838.  
  2839.  
  2840.  
  2841.  
  2842.                                       -44-
  2843.  
  2844.  
  2845.           1100..  SSmmaallllttaallkk SSttrreeaammss
  2846.                Our examples have used a  mechanism  extensively,  even
  2847.           though  we  haven't discussed it yet.  The Stream class pro-
  2848.           vides a framework for a number of data structures, including
  2849.           input  and output functionality, queues, and endless sources
  2850.           of dynamically-generated data.  A Smalltalk stream is  quite
  2851.           similar  to  the  UNIX streams you've used from C.  A stream
  2852.           provides a sequential view to an underlying resource; as you
  2853.           read  or  write elements, the stream position advances until
  2854.           you finally reach the end of the  underlying  medium.   Most
  2855.           streams  also allow you to _s_e_t the current position, provid-
  2856.           ing random access to the medium.
  2857.  
  2858.           1100..11..  TThhee OOuuttppuutt SSttrreeaamm
  2859.                The examples in this book all work because  they  write
  2860.           their  output  to  the ssttddoouutt stream.  Each class implements
  2861.           the printOn: method, and writes its output to  the  supplied
  2862.           stream.   The  printNl  method  all objects use is simply to
  2863.           send the current object a printOn: message whose argument is
  2864.           ssttddoouutt..  You can invoke the standard output stream directly:
  2865.                 'Hello, world' printOn: stdout !
  2866.                 stdout inspect !
  2867.  
  2868.           1100..22..  YYoouurr OOwwnn SSttrreeaamm
  2869.                Unlike a pipe you might create  in  C,  the  underlying
  2870.           storage  of  a Stream is under your control.  Thus, a Stream
  2871.           can provide an anonymous buffer of data,  but  it  can  also
  2872.           provide a stream-like interpretation to an existing array of
  2873.           data.  Consider this example:
  2874.                Smalltalk at: #a put: (Array new: 10) !
  2875.                a at: 4 put: 1234 !
  2876.                a at: 9 put: 5678 !
  2877.                Smalltalk at: #s put: (ReadWriteStream on: a) !
  2878.                s inspect !
  2879.                s position: 1 !
  2880.                s inspect !
  2881.                s nextPut: 11; nextPut: 22 !
  2882.                (a at: 1) printNl !
  2883.                a do: [:x| x printNl] !
  2884.                s position: 2 !
  2885.                s do: [:x| x printNl] !
  2886.                s position: 5 !
  2887.                s do: [:x| x printNl] !
  2888.                s inspect !
  2889.                The key is the on: message; it tells a stream class  to
  2890.           create  itself in terms of the existing storage.  Because of
  2891.           polymorphism, the object specified by on: does not  have  to
  2892.           be  an  Array; any object which responds to numeric at: mes-
  2893.           sages can be used.  If you happen to have  the  CheckedArray
  2894.           class  still loaded from the previous chapter, you might try
  2895.           streaming over that kind of array instead.
  2896.                You're wondering if you're stuck with  having  to  know
  2897.           how  much  data  will  be queued in a Stream at the time you
  2898.           create the stream.  If you use the right  class  of  stream,
  2899.  
  2900.  
  2901.  
  2902.  
  2903.  
  2904.  
  2905.  
  2906.  
  2907.  
  2908.                                       -45-
  2909.  
  2910.  
  2911.           the answer is no.  A ReadStream provides read-only access to
  2912.           an existing collection.  You will receive an  error  if  you
  2913.           try  to  write to it.  If you try to read off the end of the
  2914.           stream, you will also get an error.
  2915.                By contrast, WriteStream and ReadWriteStream  (used  in
  2916.           our  example)  will  tell  the underlying collection to grow
  2917.           (using the "grow" message) when you write off the end of the
  2918.           existing  collection.   Thus,  if  you want to write several
  2919.           strings, and don't want to add up their lengths yourself:
  2920.                 Smalltalk at: #s put: (ReadWriteStream on: (String new: 0)) !
  2921.                 s inspect !
  2922.                 'Hello, ' printOn: s !
  2923.                 s inspect !
  2924.                 'world' printOn: s !
  2925.                 s inspect !
  2926.                 s position: 1 !
  2927.                 s inspect !
  2928.                 s do: [:c| c printOn: stdout] !
  2929.                 (s contents) printNl !
  2930.                In this case, we have used a String as  the  collection
  2931.           for the Stream.  The printOn: messages add bytes to the ini-
  2932.           tially empty string.  Once we've added  the  data,  you  can
  2933.           continue  to treat the data as a stream.  Alternatively, you
  2934.           can ask the stream to return to you the  underlying  object.
  2935.           After  that, you can use the object (a String, in this exam-
  2936.           ple) using its own access methods.
  2937.                There are many amenities available on a stream  object.
  2938.           You  can  ask if there's more to read with "atEnd".  You can
  2939.           query the position with "position", and set it  with  "posi-
  2940.           tion:".  You can see what will be read next with "peek", and
  2941.           you can read the next element with "next".
  2942.                In the writing direction, you can write an element with
  2943.           "nextPut:".   You  don't need to worry about objects doing a
  2944.           printOn: with your stream as a destination;  this  operation
  2945.           ends  up as a sequence of nextPut:'s to your stream.  If you
  2946.           have  a  collection  of  things  to  write,  you   can   use
  2947.           "nextPutAll:"  with the collection as an argument; each mem-
  2948.           ber of the collection will be written onto the  stream.   If
  2949.           you want to write an object to the stream several times, you
  2950.           can use "next:put:":
  2951.                Smalltalk at: #s put: (ReadWriteStream on: (Array new: 0)) !
  2952.                s next: 4 put: 'Hi!' !
  2953.                s position: 1 !
  2954.                s do: [:x| x printNl] !
  2955.  
  2956.           1100..33..  FFiilleess
  2957.                Streams can also operate on files.  If  you  wanted  to
  2958.           dump the file "/etc/passwd" to your terminal, you could cre-
  2959.           ate a stream on the file, and then stream over its contents:
  2960.  
  2961.  
  2962.  
  2963.  
  2964.  
  2965.  
  2966.  
  2967.  
  2968.  
  2969.  
  2970.  
  2971.  
  2972.  
  2973.  
  2974.                                       -46-
  2975.  
  2976.  
  2977.                Smalltalk at: #f put: (FileStream open: '/etc/passwd' mode: 'r') !
  2978.                f do: [:c| c printOn: stdout] !
  2979.                f position: 30 !
  2980.                1 to: 25 do: [(f next) printOn: stdout] !
  2981.                f close !
  2982.           and, of course, you can load Smalltalk source code:
  2983.                FileStream fileIn: '/users/myself/src/source.st' !
  2984.  
  2985.           1100..44..  DDyynnaammiicc SSttrriinnggss
  2986.                Streams  provide a powerful abstraction for a number of
  2987.           data structures.  Concepts like  current  position,  writing
  2988.           the  next  position,  and  changing  the way you view a data
  2989.           structure when convenient combine to let you write  compact,
  2990.           powerful  code.   The  last example is taken from the actual
  2991.           Smalltalk source code-it shows a general method  for  making
  2992.           an object print itself onto a a string.
  2993.                printString
  2994.                    | stream |
  2995.                    stream := WriteStream on: (String new: 0).
  2996.                    self printOn: stream.
  2997.                    ^stream contents
  2998.                !
  2999.                This  method, residing in Object, is inherited by every
  3000.           class in Smalltalk.  The first line  creates  a  WriteStream
  3001.           which  stores  on  a String whose length is currently 0.  It
  3002.           then invokes the  current  object  with  printOn:.   As  the
  3003.           object prints itself to "stream", the String grows to accom-
  3004.           modate new characters.  When the object  is  done  printing,
  3005.           the method simply returns the underlying string.
  3006.                As  we've  written  code,  the assumption has been that
  3007.           printOn: would go to the terminal.  But replacing  a  stream
  3008.           to  a  file  (/dev/tty)  with  a  stream to a data structure
  3009.           (String new: 0) works just as well.  The last line tells the
  3010.           Stream to return its underlying collection-which will be the
  3011.           string which has had all the  printing  added  to  it.   The
  3012.           result  is that the printString message returns an object of
  3013.           the String class whose contents are the printed  representa-
  3014.           tion of the object receiving the printString message.
  3015.  
  3016.  
  3017.  
  3018.  
  3019.  
  3020.  
  3021.  
  3022.  
  3023.  
  3024.  
  3025.  
  3026.  
  3027.  
  3028.  
  3029.  
  3030.  
  3031.  
  3032.  
  3033.  
  3034.  
  3035.  
  3036.  
  3037.  
  3038.  
  3039.  
  3040.                                       -47-
  3041.  
  3042.  
  3043.           1111..  HHooww AArrrraayyss WWoorrkk
  3044.                Smalltalk  provides a very adequate selection of prede-
  3045.           fined classes from which to  choose.   Eventually,  however,
  3046.           you  will  find the need to code a new basic data structure.
  3047.           Because  Smalltalk's  most  fundamental  storage  allocation
  3048.           facilities  are  arrays, it is important that you understand
  3049.           how to use them to gain efficient access  to  this  kind  of
  3050.           storage.
  3051.  
  3052.           1111..11..  TThhee AArrrraayy CCllaassss
  3053.                Our  examples  have  already shown the Array class, and
  3054.           its use is fairly obvious.  For many applications,  it  will
  3055.           fill  all  your needs-when you need an array in a new class,
  3056.           you keep an instance variable,  allocate  a  new  Array  and
  3057.           assign  it to the variable, and then send array accesses via
  3058.           the instance variable.
  3059.                This technique  even  works  for  string-like  objects,
  3060.           although  it is wasteful of storage.  An Array object uses a
  3061.           _S_m_a_l_l_t_a_l_k _p_o_i_n_t_e_r for each slot in the array; its exact size
  3062.           is  transparent  to  the  programmer,  but you can generally
  3063.           guess that it'll be roughly the word size of your machine.26
  3064.           For  storing  an  array  of  characters, therefore, an Array
  3065.           works but is inefficient.
  3066.  
  3067.           1111..22..  AArrrraayyss aatt aa LLoowweerr LLeevveell
  3068.                So let's step down to a lower level of data  structure.
  3069.           a  ByteArray is much like an Array, but each slot holds only
  3070.           an integer from 0 to 255-and each slot uses only a  byte  of
  3071.           storage.   If  you  only needed to store small quantities in
  3072.           each array slot, this would therefore be a much  more  effi-
  3073.           cient choice than an Array.  As you might guess, this is the
  3074.           type of array which a String uses.
  3075.                Aha!  But when you go back to chapter 9 and look at the
  3076.           Smalltalk hierarchy, you notice that String does _n_o_t inherit
  3077.           from ByteArray.  To see why, we must delve down yet  another
  3078.           level,  and  arrive  at  the  basic  methods for compiling a
  3079.           class.
  3080.                For most example classes, we've used the message:
  3081.                     subclass:
  3082.                     instanceVariableNames:
  3083.                     classVariableNames:
  3084.                     poolDictionaries:
  3085.                     category:
  3086.           But when we implemented our CheckedArray  example,  we  used
  3087.           "variableSubclass:" instead of just "subclass:".  The choice
  3088.           of these two kinds of class creation (and a third we'll show
  3089.           shortly)  defines  the  fundamental  structure  of Smalltalk
  3090.           objects created within a given class.   Let's  consider  the
  3091.           differences in the next three sub-sections.
  3092.  
  3093.  
  3094.  
  3095.  
  3096.             26 32 bits for most ports of GNU Smalltalk.
  3097.  
  3098.  
  3099.  
  3100.  
  3101.  
  3102.  
  3103.  
  3104.  
  3105.  
  3106.                                       -48-
  3107.  
  3108.  
  3109.           1111..22..11..  ssuubbccllaassss::
  3110.                This  kind  of  class  creation  specifies the simplest
  3111.           Smalltalk object.  The object consists only of  the  storage
  3112.           needed  to hold the instance variables.  In C, this would be
  3113.           a simple structure with zero or more scalar fields.27
  3114.  
  3115.           1111..22..22..  vvaarriiaabblleeSSuubbccllaassss::
  3116.                This type of class is a superset of a subclass:.  Stor-
  3117.           age is still allocated for any instance variables,  but  the
  3118.           objects  of  the  class must be created with a new: message.
  3119.           The number passed as an argument  to  new:  causes  the  new
  3120.           object,  in addition to the space for instance variables, to
  3121.           also have that many slots of storage allocated.  The  analog
  3122.           in  C  would be to have a structure with some scalar fields,
  3123.           followed at its end by an array of  the  requested  size  of
  3124.           pointers.
  3125.  
  3126.           1111..22..33..  vvaarriiaabblleeBByytteeSSuubbccllaassss::
  3127.                This  is a special case of variableSubclass:; the stor-
  3128.           age allocated as specified by new: is  an  array  of  _b_y_t_e_s.
  3129.           The  analog  in  C  would be a structure with scalar fields,
  3130.           followed by an array of _c_h_a_r.
  3131.  
  3132.           1111..33..  AAcccceessssiinngg TThheessee NNeeww AArrrraayyss
  3133.                You already know how to  access  instance  variables-by
  3134.           name.   But  there  doesn't  seem  to be a name for this new
  3135.           storage.  The way an object accesses it is  to  send  itself
  3136.           array-type messages-at:, at:put:, and so forth.
  3137.                The  problem is when an object wants to add a new level
  3138.           of interpretation to the at: and at:put: messages.  Consider
  3139.           a  Dictionary-it  is a variableSubclass: type of object, but
  3140.           its at: message is in terms of a _k_e_y, not an  integer  index
  3141.           of its storage.  Since it has redefined the at: message, how
  3142.           does it access its fundamental storage?
  3143.                The answer is that Smalltalk has defined  basicAt:  and
  3144.           basicAt:put:,  which will access the basic storage even when
  3145.           the at: and at:put: messages have been defined to provide  a
  3146.           different abstraction.
  3147.  
  3148.           1111..44..  AAnn EExxaammppllee
  3149.                This can get pretty confusing in the abstract, so let's
  3150.           do an example to show how it's pretty  simple  in  practice.
  3151.           Smalltalk  arrays  tend to start at 1; let's define an array
  3152.           type whose permissible range is arbitrary.
  3153.  
  3154.  
  3155.  
  3156.  
  3157.  
  3158.  
  3159.             27 C requires one or more; zero  is  allowed  in
  3160.  
  3161.  
  3162.           Smalltalk.
  3163.  
  3164.  
  3165.  
  3166.  
  3167.  
  3168.  
  3169.  
  3170.  
  3171.  
  3172.                                       -49-
  3173.  
  3174.  
  3175.                ArrayedCollection variableSubclass: 'RangedArray'
  3176.                     instanceVariableNames: 'base'
  3177.                     classVariableNames: ''
  3178.                     poolDictionaries: ''
  3179.                     category: nil !
  3180.                RangedArray comment: 'I am an Array whose base is arbitrary' !
  3181.                !RangedArray class methodsFor: 'creation'!
  3182.                new
  3183.                     ^self error: 'Use new:base:'
  3184.                !
  3185.                new: ignore
  3186.                     ^self new
  3187.                !
  3188.                new: size base: b
  3189.                     ^(super new: size) init: b
  3190.                !!
  3191.                !RangedArray methodsFor: 'init'!
  3192.                init: b
  3193.                     base := (b - 1).    "- 1 because basicAt: works with a 1 base"
  3194.                     ^self
  3195.                !!
  3196.                !RangedArray methodsFor: 'basic'!
  3197.                rangeCheck: i
  3198.                     ((i <= base) | (i > (base + (self basicSize)))) ifTrue: [
  3199.                          'Bad index value: ' printOn: stderr.
  3200.                          i printOn: stderr.
  3201.                          (Character nl) printOn: stderr.
  3202.                          ^self error: 'illegal index'
  3203.                     ]
  3204.                !
  3205.                at: i
  3206.                     self rangeCheck: i.
  3207.                     ^self basicAt: (i-base)
  3208.                !
  3209.                at: i put: v
  3210.                     self rangeCheck: i.
  3211.                     ^self basicAt: (i-base) put: v
  3212.                !!
  3213.                The code has two parts; an initialization, which simply
  3214.           records what index you wish the array to start with, and the
  3215.           at: messages, which adjust the requested index so  that  the
  3216.           underlying  storage  receives  its  1-based  index  instead.
  3217.           We've included a range check  much  like  CheckedArray;  its
  3218.           utility will demonstrate itself in a moment:
  3219.                Smalltalk at: #a put: (RangedArray new: 10 base: 5) !
  3220.                a at: 5 put: 0 !
  3221.                a at: 4 put: 1 !
  3222.           Since  4 is below our base of 5, a range check error occurs.
  3223.           But this check can catch more than just our own misbehavior!
  3224.                a do: [:x| x printNl] !
  3225.           Our  do:  message  handling  is broken!  The stack backtrace
  3226.           pretty much tells the story:
  3227.  
  3228.  
  3229.  
  3230.  
  3231.  
  3232.  
  3233.  
  3234.  
  3235.  
  3236.  
  3237.  
  3238.                                       -50-
  3239.  
  3240.  
  3241.                RangedArray>>#rangeCheck:
  3242.                RangedArray>>#at:
  3243.                MethodContext>>#value:
  3244.                Integer>>#to:by:do:
  3245.                Integer>>#to:do:
  3246.                RangedArray>>#do:
  3247.           Our code received a do: message.  We didn't define  one,  so
  3248.           we  inherited  the  existing  do:  handling.  We see that an
  3249.           Integer loop was constructed, that a code block was invoked,
  3250.           and  that  our  own  at:  code  was  invoked.  When we range
  3251.           checked, we trapped an illegal index.  Just by  coincidence,
  3252.           this  version  of  our  range  checking  code also dumps the
  3253.           index.  We see that do: has assumed that all arrays start at
  3254.           1.
  3255.                The immediate fix is obvious; we implement our own do:
  3256.                !RangedArray methodsFor: 'basic'!
  3257.                do: aBlock
  3258.                     1 to: (self basicSize) do: [:x|
  3259.                          aBlock value: (self basicAt: x)
  3260.                     ]
  3261.                !!
  3262.           But  the  issues  start  to  run  deep.  If our parent class
  3263.           believed that it knew enough to assume a starting  index  of
  3264.           1,  why  didn't  it also assume that _i_t could call basicAt:?
  3265.           Object-oriented methodology says that one object  should  be
  3266.           entirely opaque to another.  But what sort of privacy should
  3267.           there be between a higher class  and  its  subclasses?   How
  3268.           many  assumption  can  a subclass make about its superclass,
  3269.           and how many  can  the  superclass  make  before  it  begins
  3270.           infringing  on the sovereignty of its subclasses?  There are
  3271.           rarely easy answers.
  3272.  
  3273.           1111..55..  BBaassiicc AAllllooccaattiioonn
  3274.                In this chapter, we've seen the fundamental  mechanisms
  3275.           used  to  allocate and index storage.  When the storage need
  3276.           not be accessed with peak efficiency, you can use the exist-
  3277.           ing  array  classes.   When  every access counts, having the
  3278.           storage be an integral part of your own  object  allows  for
  3279.           the quickest access.  When you move into this area of object
  3280.           development, inheritance and polymorphism  become  trickier;
  3281.           each  level  must coordinate its use of the underlying array
  3282.           with other levels.
  3283.  
  3284.  
  3285.  
  3286.  
  3287.  
  3288.  
  3289.  
  3290.  
  3291.  
  3292.  
  3293.  
  3294.  
  3295.  
  3296.  
  3297.  
  3298.  
  3299.  
  3300.  
  3301.  
  3302.  
  3303.  
  3304.                                       -51-
  3305.  
  3306.  
  3307.           1122..  FFuurrtthheerr SSttuuddiieess
  3308.                The question is always how far to go in  one  document.
  3309.           At this point, you know how to create classes.  You know how
  3310.           to use inheritance, polymorphism, and the basic storage man-
  3311.           agement  mechanisms  of  Smalltalk.  You've also seen a sam-
  3312.           pling of Smalltalk's powerful classes.   The  rest  of  this
  3313.           chapter simply points out areas for further study; perhaps a
  3314.           newer version of this document might cover these in  further
  3315.           chapters.
  3316.  
  3317.           1122..11..  VViieewwiinngg tthhee SSmmaallllttaallkk SSoouurrccee CCooddee
  3318.                Depending   on  the  thoroughness  of  the  person  who
  3319.           installed GNU Smalltalk, it's possible to  view  the  source
  3320.           code  for  a system method.  For instance, to see how a Dic-
  3321.           tionary processes a do: message:
  3322.                Dictionary edit: #do: !
  3323.           The viewer is hard-coded as emacs; this may or may not  work
  3324.           at your installation.
  3325.  
  3326.           1122..22..  OOtthheerr WWaayyss ttoo CCoolllleecctt OObbjjeeccttss
  3327.                We've  seen  Array, ByteArray, Dictionary, Set, and the
  3328.           various  streams.   You'll  want  to  look   at   the   Bag,
  3329.           LinkedList,  and SortedCollection classes.  For special pur-
  3330.           poses you'll want to examine ByteMemory and WordMemory.
  3331.  
  3332.           1122..33..  FFllooww ooff CCoonnttrrooll
  3333.                GNU Smalltalk has rudimentary support  for  _t_h_r_e_a_d_s  of
  3334.           execution.  The state is embodied in a Process class object;
  3335.           you'll also want to look at the ProcessorScheduler class.
  3336.  
  3337.           1122..44..  SSmmaallllttaallkk VViirrttuuaall MMaacchhiinnee
  3338.                GNU Smalltalk is implemented as a  virtual  instruction
  3339.           set.   By invoking GNU Smalltalk with the -d option, you can
  3340.           view the byte opcodes which are generated as  files  on  the
  3341.           command  line  are loaded.  Similarly, running GNU Smalltalk
  3342.           with -e will trace the execution  of  instructions  in  your
  3343.           methods.
  3344.                You  can  look at the GNU Smalltalk source to gain more
  3345.           information on the instruction set.  A better first step  if
  3346.           you  want  to pursue this subject is to start with "A Little
  3347.           Smalltalk"" by Tim Budd.  The source code is  freely  avail-
  3348.           able,   and  the  book  provides  a  solid  introduction  to
  3349.           Smalltalk-type virtual machines.  The canonical book is from
  3350.           the original designers of Smalltalk:
  3351.                Smalltalk-80: The Language and its Implementation
  3352.                     - Adele Goldberg and David Robson
  3353.  
  3354.           1122..55..  TTwwoo FFllaavvoorrss ooff EEqquuaalliittyy
  3355.                As  first  seen in chapter two, Smalltalk keys its dic-
  3356.           tionary with things like "#word", whereas we  generally  use
  3357.           "'word'".   The  former, as it turns out, is from class Sym-
  3358.           bol.  The latter is from class String.  What's the real dif-
  3359.           ferent  between  a Symbol and a String?  To answer the ques-
  3360.           tion, we'll use an analogy from C.
  3361.  
  3362.  
  3363.  
  3364.  
  3365.  
  3366.  
  3367.  
  3368.  
  3369.  
  3370.                                       -52-
  3371.  
  3372.  
  3373.                In C, if you have a function for comparing strings, you
  3374.           might try to write it:
  3375.                strcpy(char *p, char *q)
  3376.                {
  3377.                     return (p == q);
  3378.                }
  3379.           But  clearly this is wrong!  The reason is that you can have
  3380.           two copies of a string-each with the same contents-but  each
  3381.           at  its own address.  A correct string compare must walk its
  3382.           way through the strings and compare each element.
  3383.                In Smalltalk, exactly the same issue  exists,  although
  3384.           the  details  of  manipulating storage addresses are hidden.
  3385.           If we have two Smalltalk strings, both with  the  same  con-
  3386.           tents,  we  don't  necessarily  know  if they're at the same
  3387.           storage address.  In  Smalltalk  terms,  we  don't  know  if
  3388.           they're the _s_a_m_e _o_b_j_e_c_t.
  3389.                The  Smalltalk  dictionary  is searched frequently.  To
  3390.           speed the search, it would be nice to not  have  to  compare
  3391.           the characters of each element, but only compare the address
  3392.           itself.  To do this, you need to have a guarantee  that  all
  3393.           strings  with  the  same  contents are the same object.  The
  3394.           String class, created like:
  3395.                y := 'Hello' !
  3396.           does not satisfy this.  Each time you execute this line, you
  3397.           may  well  get a new object.  But a very similar class, Sym-
  3398.           bol, will always return the same object:
  3399.                y := #Hello !
  3400.           In general, you can use strings for almost all  your  tasks.
  3401.           If  you  ever get into a performance-critical function which
  3402.           looks up strings, you can switch to Symbol.  It takes longer
  3403.           to  create  a  Symbol,  and the memory for a Symbol is never
  3404.           freed (since the class has to keep tabs on  it  indefinitely
  3405.           to  guarantee  it continues to return the same object).  You
  3406.           can use it, but use it with care.
  3407.  
  3408.           1122..66..  CChheecckkiinngg ffoorr tthhee TTwwoo TTyyppeess ooff EEqquuaalliittyy
  3409.                This paper has generally used the strcmp()-ish kind  of
  3410.           checks  for  equality.  If you ever need to ask the question
  3411.           "is this the  same  object?",  you  use  the  "=="  operator
  3412.           instead of "=":
  3413.                Smalltalk at: #x put: 0 !
  3414.                Smalltalk at: #y put: 0 !
  3415.                x := 'Hello' !
  3416.                y := 'Hello' !
  3417.                (x = y) printNl !
  3418.                (x == y) printNl !
  3419.                x := #Hello !
  3420.                y := #Hello !
  3421.                (x = y) printNl !
  3422.                (x == y) printNl !
  3423.                Using  C  terms, the former compares contents like str-
  3424.           cmp().   The  latter  compares  storage  addresses,  like  a
  3425.           pointer comparison.
  3426.  
  3427.  
  3428.  
  3429.  
  3430.  
  3431.  
  3432.  
  3433.  
  3434.  
  3435.  
  3436.                                       -53-
  3437.  
  3438.  
  3439.           1122..77..  WWhheerree ttoo ggeett HHeellpp
  3440.                The  newsgroup comp.lang.smalltalk is read by many peo-
  3441.           ple with a great deal of Smalltalk  experience.   There  are
  3442.           several  commercial  Smalltalk  implementations; you can buy
  3443.           support for these, though  it  isn't  cheap.   For  the  GNU
  3444.           Smalltalk  system  in  particular, you can try the newsgroup
  3445.           gnu.smalltalk.bug.  If all  else  fails,  you  can  try  the
  3446.           author at:
  3447.                jtk@netcom.com
  3448.           No guarantees, but the author will do his best!
  3449.  
  3450.           1122..88..  AAcckknnoowwlleeddggmmeennttss
  3451.                Thanks  to Steve Byrne for writing GNU Smalltalk in the
  3452.           first place.  Great thanks to Mark Bush  and  Bob  Roos  for
  3453.           their meticulous jobs of proofreading this document, and the
  3454.           generous amounts of input they provided  on  refinements  to
  3455.           the  contents and structure.  Thanks also to Andrew Berg for
  3456.           his comments on the early chapters of the document.
  3457.                Any remaining  errors  are  purely  the  fault  of  the
  3458.           author.   This document is provided as-is, without warranty,
  3459.           but I will happily accept reports of any  errors.   If  time
  3460.           permits, I will perhaps even release a corrected revision of
  3461.           the document.
  3462.                I release this document into  the  public  domain,  and
  3463.           simply  request  that  you  acknowledge  me  as the original
  3464.           author in any use or derivative work you make of this  docu-
  3465.           ment.
  3466.  
  3467.  
  3468.  
  3469.  
  3470.                                    Andy Valencia
  3471.                                    325 Union Ave #359
  3472.                                    Campbell, CA  95008
  3473.                                    jtk@netcom.com
  3474.                                    November 27, 1992
  3475.  
  3476.  
  3477.  
  3478.  
  3479.  
  3480.  
  3481.  
  3482.  
  3483.  
  3484.  
  3485.  
  3486.  
  3487.  
  3488.  
  3489.  
  3490.  
  3491.  
  3492.  
  3493.  
  3494.  
  3495.  
  3496.  
  3497.  
  3498.  
  3499.  
  3500.  
  3501.  
  3502.                                       -54-
  3503.  
  3504.  
  3505.                                    APPENDIX A
  3506.                      A Simple Overview of Smalltalk Syntax
  3507.  
  3508.  
  3509.  
  3510.  
  3511.                Smalltalk's  power comes from its treatment of objects.
  3512.           In this document, we've mostly avoided the issue  of  syntax
  3513.           by using strictly parenthesized expressions as needed.  When
  3514.           this leads to code which is hard to read due to the  density
  3515.           of  parentheses,   a knowledge of Smalltalk's syntax can let
  3516.           you simplify expressions.  In general, if it  was  hard  for
  3517.           you  to  tell how an expression would parse, it will be hard
  3518.           for the next person, too.
  3519.                The following presentation presents the grammar a  cou-
  3520.           ple  of  related  elements at a time.  We use a BNF style of
  3521.           grammar, with some extensions.  The form:
  3522.                [ ... ]
  3523.           means that "..." can occur zero or one times.
  3524.                [ ... ]*
  3525.           means zero or more;
  3526.                [ ... ]+
  3527.           means one or more.
  3528.                 ... | ... [ | ... ]*
  3529.           means that one of the variants must be  chosen.   Characters
  3530.           in double quotes refer to the literal characters.  Most ele-
  3531.           ments may be separated by white space;  where  this  is  not
  3532.           legal,  the  elements  are  presented  without  white  space
  3533.           between them.
  3534.  
  3535.  
  3536.                methods: "!" id ["class"] "methodsFor:" string "!" [method "!"] "!"
  3537.           Methods are introduced by first naming a class (the _i_d  ele-
  3538.           ment),  specifying  "class"  if  you're adding class methods
  3539.           instead of instance methods, and sending a  string  argument
  3540.           to  the methodsFor: message.  Each method is terminated with
  3541.           an "!"; two "!"'s in a row signify the end of the new  meth-
  3542.           ods.
  3543.  
  3544.                method: message [prim] [temps] exprs
  3545.                message: id | binsel id | [keysel id]+
  3546.                prim: "<" "primitive:" number ">"
  3547.                temps: "|" [id]* "|"
  3548.           A method definition starts out with a kind of template.  The
  3549.           message to be handled is specified with  the  message  names
  3550.           spelled  out  and  identifiers in the place of arguments.  A
  3551.           special kind of definition is the _p_r_i_m_i_t_i_v_e; it has not been
  3552.           covered  in  this  paper;  it  provides  an interface to the
  3553.           underlying Smalltalk virtual machine.  _t_e_m_p_s is the declara-
  3554.           tion  of  local variables.  Finally, _e_x_p_r_s (covered soon) is
  3555.           the actual code for implementing the method.
  3556.  
  3557.  
  3558.  
  3559.  
  3560.  
  3561.  
  3562.  
  3563.  
  3564.  
  3565.  
  3566.  
  3567.  
  3568.                                       -55-
  3569.  
  3570.  
  3571.                unit: id | literal | block | "(" expr ")"
  3572.                unaryexpr: unit [ id ]+
  3573.                primary: unit | unaryexpr
  3574.           These are the "building blocks" of Smalltalk expressions.  A
  3575.           _u_n_i_t  represents  a single Smalltalk value, with the highest
  3576.           syntactic precedence.  A _u_n_a_r_y_e_x_p_r is simply  a  _u_n_i_t  which
  3577.           receives  a  number  of unary messages.  A _u_n_a_r_y_e_x_p_r has the
  3578.           next highest precedence.  A _p_r_i_m_a_r_y is simply  a  convenient
  3579.           left-hand-side name for one of the above.
  3580.  
  3581.                exprs: [expr "."]* [["^"] expr]
  3582.                expr: [id ":="]* expr2
  3583.                expr2: primary | msgexpr [ ";" cascade ]*
  3584.           A  sequence of expressions is separated by "."'s and can end
  3585.           with a returned value ("^").  There can be  leading  assign-
  3586.           ments;  unlike  C, assignments apply only to simple variable
  3587.           names.  An expression is  either  a  primary  (with  highest
  3588.           precedence)  or  a  more  complex message.  _c_a_s_c_a_d_e does not
  3589.           apply to _p_r_i_m_a_r_y constructions, as they are  too  simple  to
  3590.           require  the  construct--since  all  _p_r_i_m_a_r_y  construct  are
  3591.           unary, you can just add more unary messages:
  3592.                1234 printNl printNl printNl !
  3593.  
  3594.                msgexpr: unaryexpr | binexpr | keyexpr
  3595.           A complex message is either a unary message (which  we  have
  3596.           already covered), a binary message ("+", "-", and so forth),
  3597.           or a keyword message ("at:", "new:", ....)   Unary  has  the
  3598.           highest precedence, followed by binary, and keyword messages
  3599.           have the lowest precedence.  Examine the two versions of the
  3600.           following  messages.   The second have had parentheses added
  3601.           to show the default precedence.
  3602.                myvar at: 2 + 3 put: 4
  3603.                mybool ifTrue: [ ^ 2 / 4 roundup ]
  3604.  
  3605.                (myvar at: (2 + 3) put: (4))
  3606.                (mybool ifTrue: ([ ^ (2 / (4 roundup)) ]))
  3607.  
  3608.                cascade: id | binmsg | keymsg
  3609.           A _c_a_s_c_a_d_e is used to direct further  messages  to  the  same
  3610.           object  which  was last used.  The three types of messages (
  3611.           _i_d is how you send a unary message) can thus be sent.
  3612.  
  3613.                binexpr: primary binmsg [ binmsg ]*
  3614.                binmsg: binsel primary
  3615.                binsel: selchar[selchar]
  3616.           A binary message is sent to an  object,  which  _p_r_i_m_a_r_y  has
  3617.           identified.   Each binary message is a binary selector, con-
  3618.           structed from one or two characters, and an  argument  which
  3619.           is also provided by a examples_p_r_i_m_a_r_y.Some
  3620.                1 + 2 - 3 / 4
  3621.           which parses as:
  3622.                (((1 + 2) - 3) / 4)
  3623.  
  3624.  
  3625.  
  3626.  
  3627.  
  3628.  
  3629.  
  3630.  
  3631.  
  3632.  
  3633.  
  3634.                                       -56-
  3635.  
  3636.  
  3637.                keyexpr: keyexpr2 keymsg
  3638.                keyexpr2: binexpr | primary
  3639.                keymsg: [keysel keyw2]+
  3640.                keysel: id":"
  3641.           Keyword expressions are much like binary expressions, except
  3642.           that the selectors are made up of identifiers with  a  colon
  3643.           appended.  Where the arguments to a binary function can only
  3644.           be from _p_r_i_m_a_r_y, the arguments to a keyword  can  be  binary
  3645.           expressions  or _p_r_i_m_a_r_y ones.  This is because keywords have
  3646.           the lowest precedence.
  3647.  
  3648.                block: "[" [[":" id]* "|" ] exprs "]"
  3649.           A code block is  square  brackets  around  a  collection  of
  3650.           Smalltalk expressions.  The leading ": id" part is for block
  3651.           arguments.
  3652.  
  3653.                literal: number | string | charconst | symconst | arrayconst
  3654.                arrayconst: "#" array
  3655.                array: "(" [number | string | symbol | array | charconst]* ")"
  3656.                number: [[dig]+ "r"] ["-"] [hexDig]+ ["." [hexDig]+] ["e"["-"][dig]+].
  3657.                string: "'"[char]*"'"
  3658.                charconst: "$"char
  3659.                symconst: "$"symbol
  3660.           We have already shown the use of many  of  these  constants.
  3661.           Although  not covered in this paper, numbers can have a base
  3662.           specified at their front, and a  trailing  scientific  nota-
  3663.           tion.   We have seen examples of character, string, and sym-
  3664.           bol constants.  Array  constants  are  simple  enough;  they
  3665.           would look like:
  3666.                Smalltalk at: #a put: #(1 2 'Hi' $x $Hello 4 5) !
  3667.  
  3668.                symbol: id | binsel | keysel[keysel]*
  3669.           Symbols  are  mostly used to represent the names of methods.
  3670.           Thus, they can hold simple  identifiers,  binary  selectors,
  3671.           and keyword selectors:
  3672.                $hello
  3673.                $+
  3674.                $at:put:
  3675.  
  3676.                id: letter[letter|dig]*
  3677.                selchar: "+" | "-" | "*" | "/" | "~" | "|" | "," |
  3678.                     "<" | ">" | "=" | "&"
  3679.                hexdig: "0".."9" | "A".."F"
  3680.                dig: "0".."9"
  3681.           These are the categories of characters and how they are com-
  3682.           bined at the most basic level.   _s_e_l_c_h_a_r  simply  lists  the
  3683.           characters which can be combined to name a binary message.
  3684.  
  3685.  
  3686.  
  3687.  
  3688.  
  3689.  
  3690.  
  3691.  
  3692.  
  3693.  
  3694.  
  3695.  
  3696.  
  3697.