old-www/LDP/LG/issue60/steffler.html

779 lines
41 KiB
HTML

<!--startcut ==============================================-->
<!-- *** BEGIN HTML header *** -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML><HEAD>
<title>Making Smalltalk: Objects, Classes and Other Things LG #60</title>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" VLINK="#0000AF"
ALINK="#FF0000">
<!-- *** END HTML header *** -->
<CENTER>
<A HREF="http://www.linuxgazette.com/">
<H1><IMG ALT="LINUX GAZETTE" SRC="../gx/lglogo.jpg"
WIDTH="600" HEIGHT="124" border="0"></H1></A>
<!-- *** BEGIN navbar *** -->
<IMG ALT="" SRC="../gx/navbar/left.jpg" WIDTH="14" HEIGHT="45" BORDER="0" ALIGN="bottom"><A HREF="sipos.html"><IMG ALT="[ Prev ]" SRC="../gx/navbar/prev.jpg" WIDTH="16" HEIGHT="45" BORDER="0" ALIGN="bottom"></A><A HREF="index.html"><IMG ALT="[ Table of Contents ]" SRC="../gx/navbar/toc.jpg" WIDTH="220" HEIGHT="45" BORDER="0" ALIGN="bottom" ></A><A HREF="../index.html"><IMG ALT="[ Front Page ]" SRC="../gx/navbar/frontpage.jpg" WIDTH="137" HEIGHT="45" BORDER="0" ALIGN="bottom"></A><A HREF="http://www.linuxgazette.com/cgi-bin/talkback/all.py?site=LG&article=http://www.linuxgazette.com/issue60/steffler.html"><IMG ALT="[ Talkback ]" SRC="../gx/navbar/talkback.jpg" WIDTH="121" HEIGHT="45" BORDER="0" ALIGN="bottom" ></A><A HREF="../faq/index.html"><IMG ALT="[ FAQ ]" SRC="./../gx/navbar/faq.jpg"WIDTH="62" HEIGHT="45" BORDER="0" ALIGN="bottom"></A><A HREF="lg_backpage60.html"><IMG ALT="[ Next ]" SRC="../gx/navbar/next.jpg" WIDTH="15" HEIGHT="45" BORDER="0" ALIGN="bottom" ></A><IMG ALT="" SRC="../gx/navbar/right.jpg" WIDTH="15" HEIGHT="45" ALIGN="bottom">
<!-- *** END navbar *** -->
<P>
</CENTER>
<!--endcut ============================================================-->
<H4 ALIGN="center">
"Linux Gazette...<I>making Linux just a little more fun!</I>"
</H4>
<P> <HR> <P>
<!--===================================================================-->
<!-- END header -->
<img SRC="misc/steffler/penguinInBalloon.gif" height=230 width=200 align=right>
<center>
<h1>
<img SRC="misc/steffler/makingSmalltalk.png" ></h1></center>
<center>
<h3>Objects, Classes and Other Things</h3>
<H4>By <a href="mailto:jagwar@magma.ca">Jason Steffler</a></H4></center>
<h2>
<a NAME="abstract"></a>Abstract</h2>
&nbsp;&nbsp;&nbsp; For those who haven't read the previous articles,
be sure to read <font size=+1><a href="#statementOfPurpose">the statement
of purpose</a></font> first.&nbsp; This month, we're going to discuss objects
as well as classes, messages and encapsulation.&nbsp; For those looking
to read the whole series locally or info about upcoming articles, you can
<font size=+1><a href="http://www.magma.ca/~jagwar/makingSmalltalkForwardingPage.html">check
the MST page</a></font>.&nbsp; For those looking for further information
on learning Squeak, here are <a href="http://minnow.cc.gatech.edu/squeak/377">some
good resources</a>.
<br>&nbsp;&nbsp;&nbsp; I also need to cover another item before we get
into this article, and it's important enough to put at the top as opposed
to the <a href="#questionsAndAnswers">Q&amp;A section</a>.&nbsp; I had
a number of people ask me how I knew what code to type, and where they
can find what objects Smalltalk has.&nbsp; I plan on getting to this in
article 4.&nbsp; I'm holding off on discussing this to simplify the presentation
and concentrate on fundamental concepts first.&nbsp; I've often thought
that the message isn't the medium, but rather the volume of the medium.&nbsp;
This has a number of connotations; in this context I don't want to present
too much too fast and overwhelm the folks who are coming in with no programming
experience at all.
<br>&nbsp;&nbsp;&nbsp; As a side note, I find it humourous and sad to see
technical books that are selling by the pound these days.&nbsp; You see
things like: '1000 pages of &lt;technology X> for only $19.<sup>95</sup>!',
and the Core Java 2 <i>Fundamentals</i> book that is <i>742</i> pages!&nbsp;
It's often been said that the syntax of Smalltalk is so simple that you
can put it on a postcard, as there are 2 operators, 5 reserved words<sup><a href="#footnotes">1</a></sup>,
and 9 reserved characters.&nbsp; For those interested I'll add an interlude:
<a href="#smalltalkSyntax">all I learned about Smalltalk syntax I learned
from a postcard.</a>
<h2>
<a NAME="quoteOfTheDay"></a>Quote of the day</h2>
"Smalltalk is a wonderful language to work with - in fact, it's hard to
imagine a serious programming language being more fun than Smalltalk.&nbsp;
Certainly, I've had more fun programming in Smalltalk than any other language
I've worked with; so much fun that at times it's seemed incredible that
I've also been paid to enjoy myself."
<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; -Alec Sharp, "Smalltalk
by Example", pXIX
<h2>
<a NAME="firstLookAtObjects"></a>A first look at objects</h2>
&nbsp;&nbsp;&nbsp; Last month, we left off with describing an object as
anything you can think of that is a noun.&nbsp; We implicitly extended
this concept by talking about actions that objects can do when asked.&nbsp;
Let's extend this concept explicitly now by describing actions objects
can do when asked as verbs.&nbsp; For example, you could consider a Person
as an object.&nbsp; You could ask the Person object to do things like:
<ol>
<li>
Person, would you please sing?</li>
<li>
Person, would you please sing Mary Had A Little Lamb?</li>
<li>
Person, would you please sing Mary Had A Little Lamb, and do it loudly.</li>
<li>
Person, what is your height?</li>
</ol>
&nbsp;&nbsp;&nbsp; Notice action 1 was just an activity with no constraints
on it.&nbsp; We don't tell the person what to sing, or how fast, or how
loud, etc.&nbsp; In our 2nd request, we specify the song to sing and in
the 3rd request we also specify that it should be sung loudly.&nbsp; Action
4 shows that we can not only ask the person to do something, but also ask
them something about themselves.&nbsp; That's right, objects have properties
just like a real world thing would (we'll come back to this).&nbsp; Assuming
we had a Person object (we don't, at least not yet), the corresponding
Smalltalk code would look like:
<p><b>&nbsp;&nbsp; (Person new) sing.</b>
<br><b>&nbsp;&nbsp; (Person new) sing: 'MaryHadALittleLamb'.</b>
<br><b>&nbsp;&nbsp; (Person new) sing: 'MaryHadALittleLamb' andDoIt: 'loudly'.</b>
<br><b>&nbsp;&nbsp; (Person new) sing: 'MaryHadALittleLamb' andDoIt: 'quietly'.</b>
<br><b>&nbsp;&nbsp; (Person new) whatIsMyHeight.</b>
<p>&nbsp;&nbsp;&nbsp; Pretty easy stuff eh?<sup><a href="#footnotes">2</a></sup>&nbsp;
Notice how the Smalltalk code is very readable and is very similar to how
I initially wrote the questions in English.&nbsp; Each one of these requests
would be what we Smalltalkers call a <a href="#articleGlossary">message</a>
that the Person responds to, and the method in which they respond is determined
by what we Smalltalkers call a <a href="#articleGlossary">method</a>.&nbsp;
Again, pretty easy and intuitive stuff.
<br>&nbsp;&nbsp;&nbsp; Note on the last message, I switched the perspective
around to <b>whatIsMyHeight</b> as opposed to <b>whatIsYourHeight</b>.&nbsp;
We could easily have made a method called <b>whatIsYourHeight</b>, but
it's common practice to name methods from the perspective of the object<sup><a href="#footnotes">3</a></sup>.
<br>&nbsp;&nbsp;&nbsp; Now, you'll notice that each request has <b>(Person
new)</b> in it; you'd be correct in assuming we're asking a 5 different
people to do something - we're asking a new Person to do something each
time.&nbsp; What if we want to ask the same person to do everything?&nbsp;
There's a few ways we could do this, one of them is:
<p><b>&nbsp;&nbsp;&nbsp; | aPerson |</b>
<br><b>&nbsp;&nbsp;&nbsp; aPerson := (Person new).</b>
<br><b>&nbsp;&nbsp;&nbsp; aPerson sing.</b>
<br><b>&nbsp;&nbsp;&nbsp; aPerson sing: 'MaryHadALittleLamb'.</b>
<br><b>&nbsp;&nbsp;&nbsp; aPerson sing: 'MaryHadALittleLamb' andDoIt: 'loudly'.</b>
<br><b>&nbsp;&nbsp;&nbsp; aPerson sing: 'MaryHadALittleLamb' andDoIt: 'quietly'.</b>
<br><b>&nbsp;&nbsp;&nbsp; aPerson whatIsMyHeight.</b>
<p>&nbsp;&nbsp;&nbsp; The first line is declaring a temporary <a href="#articleGlossary">variable</a>.&nbsp;
Hmm, this is the first traditional computer term that we've used so far
in our discussion, not too bad.&nbsp; Since we don't have a name for the
person, we'll just call the person <b>aPerson</b>.&nbsp; Much better than
'<b>x</b>', '<b>y</b>', or '<b>i</b>' that you often see in other programming
languages.&nbsp; Not that you couldn't call a variable <b>x</b> in Smalltalk,
it's just that you're encouranged to name things descriptively.&nbsp; The
common convention is to run your words together with capitalizing each
successive word (IMHO, this includes acronyms too).&nbsp; For example,
you could ask the Person to <b>runToTheDmv.</b>&nbsp; So in the above code
snippet, we're creating a new person and assigning (<b>:=</b>) that person
to a temporary variable called <b>aPerson</b>.&nbsp; Then we're asking
aPerson to perform their various methods by sending them messages.
<br>&nbsp;&nbsp;&nbsp; So the question naturally arises, what is '<b>Person</b>'?&nbsp;
Thinking in terms of nouns, a Person is a specific class or subset of nouns.&nbsp;
Well, in Smalltalk <b>Person</b> is an object too, but it's a special kind
of object that is called a <a href="#articleGlossary">class</a>.&nbsp;
You can think of a class as a blueprint object for making related objects.&nbsp;
When we ask a class to make a new instance of an object, it's called <a href="#articleGlossary">instantiating</a>
an object.&nbsp; Now, coming back to the properties of an object, they
are stored in what are called <a href="#articleGlossary">instance variables</a>
of the object<sup><a href="#footnotes">4</a></sup>.&nbsp; When we were
asking <b>aPerson</b> for their height, they probably responded with what
they had stored in their instance variable (we don't know for sure, as
we don't know how the person determines their height).
<br>&nbsp;&nbsp;&nbsp; Revisting our conception of what an object is, we
can now refine it:&nbsp; <i>an object is a grouping of messages and data
that its messages can operate on.&nbsp; </i>This brings us to our next
subject:&nbsp; Encapsulation.
<h2>
<a NAME="encapsulation"></a>Encapsu-what?</h2>
&nbsp;&nbsp;&nbsp; <a href="#articleGlossary">Encapsulation</a> is a fancy
term to describe the grouping of messages and data within something we
call an object, such that other objects can't see the data and can only
get access to it via messages.&nbsp; The reason for the emphasis on this
topic is that this is a big difference from the way that procedural programming
traditionally viewed programs.&nbsp; Traditionally, the data and the methods
for changing the data were two very separate beasties.&nbsp; Often, when
these are in two different parts of your program, they get out of synch
and it's very hard to maintain the functions that manipulate the data when
the structure of the data changes or vice versa.&nbsp; This is one of the
problems that OO programming tries to address, by keeping the data and
the methods for changing the data close, it's easier to keep them in synch.&nbsp;
In fact, if you change how the data is stored in an object, or the method
by which you change that data, any other objects are none the wiser.&nbsp;
This is a Good Thing, as when you make changes, you make them in one spot,
as opposed to many spots.
<br>&nbsp;&nbsp;&nbsp; So, though we could guess at what <b>aPerson</b>'s
height is, we don't really know until we ask them <b>whatIsYourHeight</b>.&nbsp;
Now, the person could respond by remembering the last time he walked past
a height marker in the local Quick-E-Mart.&nbsp; After a number of times
of asking their height, they realize that maybe they should give a better
answer, so they change the method of their respone by checking their height
against a measuring tape.&nbsp; To us, we had no idea that how they determined
their answer changed, and that's good as we really don't care how they
determine it, we only care about the answer.
<h2>
<a NAME="responsibilities"></a>Responsibilities</h2>
&nbsp;&nbsp;&nbsp; A <b><u>Very Key</u></b> thing in OO programming, is
considering the <a href="#articleGlossary">responsibilities</a> that an
object should have.&nbsp; Just like a real world person, <b>aPerson</b>
object also has responsibilities.&nbsp; In our example, <b>aPerson</b>
is rather lucky, as they only have the responsibility of singing or answering
their height.&nbsp; They don't have the <b>changeTheStinkyBaby</b> responsibility.
<br>&nbsp;&nbsp;&nbsp; Figuring out the appropriate responsibilities for
objects is one of the key things in OO programming.&nbsp; If you don't
have appropriate responsibilites, you run into problems like <a href="#articleGlossary">object
bloat</a>.&nbsp; This is when an object does too many things and is 'spread
too thin'.&nbsp; A jack of all trades does everything pretty poorly.&nbsp;
On the other hand though, you need to strike a good balance, as a specialist
that is too specialized does nothing very well, and it takes a huge number
of specialists to do anything.
<br>&nbsp;&nbsp;&nbsp; Did I mention figuring out the appropriate responsibilities
for objects is one of the key things in OO programming?
<h2>
<a NAME="puttingItAllTogether"></a>Putting it all together</h2>
&nbsp;&nbsp;&nbsp; I've been holding off running any code thus far, as
I wanted you to concentrate on the concepts.&nbsp; In the same vein, I'm
going to hold off describing how to make a <b>Person</b> class to concentrate
on other concepts first.&nbsp; We'll get to stepping through creating a
<b>Person</b>
class in the article after next, as I want to cover inheritence, polymorphism
and abstract classes first.&nbsp; In the meantime though, I've included
the <a href="#personSampleCode">source code below</a>, if you're curious
and want to peek or if you want to compare the code against other languages
you know.
<br>&nbsp;&nbsp;&nbsp; To load the code, we need to <a href="#articleGlossary">file
it in</a> to Squeak.&nbsp; If you're reading this remotely, you need to
first download the code
<a href="misc/steffler/Person-Article2.st.txt">from here</a>, rename
it to remove
the ".txt" extension, save
it where ever you want.&nbsp; Now open the file list (<b>Menus>open...>file
list</b>), find your downloaded file (<b>Person-Article2.st)</b>, <b>left
click</b> on the file in the upper right corner to select, then <b>middle
click>fileIn.
</b>For the read-along folks, the file browser looks like:
<br><img SRC="misc/steffler/picFileListOnPerson.png" <cr >
<br>&nbsp;&nbsp;&nbsp; Now, you can go back to the above code and execute
it.&nbsp; If I was really motivated/sadistic, for the singing parts I could
have actually recorded myself singing the songs and have the commands play
them.&nbsp; However, I took the obvious shortcut and just opened windows
with the song text in them.
<br>&nbsp;&nbsp;&nbsp; To exeute code, highlight the code, <b>middle click>do
it</b>&nbsp; (or you can hit <b>Alt-d</b>).&nbsp; Try doing one line at
a time, or multiple lines at a time.&nbsp; You'll note with the second
example that uses a temporary variable, you'll have to highlight multiple
lines to get that temporary variable included in execution.&nbsp; Try commenting
out parts with&nbsp; "double quotes" - double quotes, are the Smalltalk
comment indicator.&nbsp; ie:&nbsp; "This is a comment"&nbsp; You'll notice
that when we comment out code and re-execute that we didn't need to recompile,
which is nice... compiling is so pass&eacute; and time consuming.
<br>&nbsp;&nbsp;&nbsp; For the read-along folk, when you execute, this
is what you'll see:
<p><b>(Person new) sing.</b>
<br><img SRC="misc/steffler/picPersonSing.png" height=239 width=429>
<p><b>(Person new) sing: 'MaryHadALittleLamb'.</b>
<br><img SRC="misc/steffler/picPersonSingMary.png" height=238 width=428>
<p><b>(Person new) sing: 'MaryHadALittleLamb' andDoIt: 'loudly'.</b>
<br><img SRC="misc/steffler/picPersonSingMaryLoudly.png" height=236 width=428>
<p><b>(Person new) sing: 'MaryHadALittleLamb' andDoIt: 'quietly'.</b>
<br><img SRC="misc/steffler/picPersonSingMaryQuietly.png" height=236 width=428>
<p><b>(Person new) whatIsMyHeight.</b>
<br><img SRC="misc/steffler/picPersonHeight.png" height=236 width=428>
<br>&nbsp;
<h2>
<a NAME="lookingForward"></a>Looking forward</h2>
&nbsp;&nbsp;&nbsp; The next article will cover inheritence, polymorphism,
and abstract classes as well as introducing the collection classes. <i>Note:&nbsp;
this time around, the sweet squeak is going to do some explaining, so be
sure to read that section.</i>
<h2>
<a NAME="smalltalkSyntax"></a>All I learned about Smalltalk syntax I learned
from a postcard</h2>
This is an aside really, if you're coming into Smalltalk cold and are confused
by this table, don't worry about it as we'll be covering this as we go
along.&nbsp; This is here for the curious or the folks who have other programming
experience to compare.
<ul>
<li>
<b>Operators</b></li>
<ul>
<li>
:=&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this is assignment (or a left
pointing arrow in Squeak)</li>
<li>
^&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this is return (or an
upwards pointing arrow in Squeak)</li>
</ul>
<li>
<b>Reserved Words</b><sup><a href="#footnotes">5</a></sup></li>
<ul>
<li>
nil&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this is nothing, nada, nil</li>
<li>
true</li>
<li>
false</li>
<li>
self&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this is the object itself</li>
<li>
super&nbsp;&nbsp; this is the object's parent</li>
</ul>
<li>
<b>Reserved characters</b></li>
<ul>
<li>
|&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this indicates
a temporary variable</li>
<li>
$&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this indicates a character</li>
<li>
#&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this indicates a literal</li>
<li>
!&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this is a fileout delimiter</li>
<li>
()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this indicates precedence</li>
<li>
[]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this indicates a block of code</li>
<li>
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this indicates a comment</li>
</ul>
</ul>
<h2>
<a NAME="sweetSqueak"></a>A Sweet Squeak</h2>
&nbsp;&nbsp;&nbsp; This section typically won't explore/explain code or
example, but this time we'll make an exception.&nbsp; This time, we're
going to play with numbers, as that's a common thing for introductory programming
articles/books to do and is an easy way to compare languages.&nbsp; People
with some programming experience will appreciate this more, people with
no programming experience will wonder why all languages can't do this.
<br>&nbsp;&nbsp;&nbsp; Let's start of with factorials.&nbsp; For those
not familiar with a factorial, it's most easily described by examples:
<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1 factorial = 1
<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2 factorial = 2*1
<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3 factorial = 3*2*1
<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 4 factorial = 4*3*2*1
<br>&nbsp;&nbsp;&nbsp; When you do the below snippet, you won't see anything
happen.&nbsp; That's because the below code doesn't open any windows to
report back it's results.&nbsp; To see it's results, you can do to things
instead of <b>doing it</b>:
<ul>
<li>
<b>print it</b> <b>(middle click>print it)</b></li>
<ul>
<li>
printing something will print an ASCII representation of the return object
to the workspace</li>
</ul>
<li>
<b>inspect it (middle click>inspect)</b></li>
<ul>
<li>
inspecting something will open up an object inspector on the return object.&nbsp;
This is an <b>incredibly powerful </b>feature, as you can look at and play
with objects in real time!&nbsp; If you're not sure how an object is working,
you can look at it and poke it to see how it behaves, and you can change
how it behaves in real time.</li>
</ul>
</ul>
"Try printing this, you'll see the answer '120' printed in the workspace"
<br><b>&nbsp;&nbsp; 5 factorial.</b>
<p>"Now print this, and you'll see a very large number as the result, since
it's 1067 digits long, I'm not going to paste it in here.&nbsp; <i>Note,
this takes 5.9 seconds to run on my P200, which is pretty respectable performance.</i>
<br>&nbsp;&nbsp;&nbsp; <i>Also note the size of the numbers you can work
with - you don't have the usual predefined fixed limits such as an int
that has the range from -2,147,483,648 to 2,147,483,647</i>."
<br><b>&nbsp;&nbsp;&nbsp; 1000 factorial</b>
<p>"If you want to and have the time, just for grins try 10000 factorial
(I didn't have the patience to run this on my machine, even in another
thread)"
<p>"For the curious, no I didn't count the number of digits returned from
1000 factorial, since the message factorial returns a LargeInteger, we
can just ask that LargeInteger what size it is."
<br><b>&nbsp;&nbsp;&nbsp; (1000 factorial) size</b>
<p>"If you want to check that the correct numbers are actually being computed,
try this and it should give you an answer of 1000"
<br><b>&nbsp;&nbsp;&nbsp; 1000 factorial // 999 factorial</b>
<p>"Looking for what kind of precision you can get?&nbsp; Try:"
<br><b>&nbsp;&nbsp;&nbsp; 123443/5432</b>
<br>"The interesting thing you'll note is that it returns a Fraction!&nbsp;
No rounding off to the first 5 decimal places by default.&nbsp; Instead
of printing it, try inspecting this guy, you'll see a Fraction object,
with a numerator and denominator just as you'd expect:"
<br><img SRC="misc/steffler/picFractionObject.png" height=181 width=318>
<p>"Of course, you can use floats too, in which case you do get a rounding
off - to 14 places give or take depending on the flavour of Smalltalk you're
using.&nbsp; Try this, and you'll get the answer: 22.72426793416332"
<br><b>&nbsp;&nbsp;&nbsp; 123443.45/5432.23</b>
<p>"Finally, for those curious about how long things take, to time something
in Smalltalk you can print this, which will print out the milliseconds
it took to run.&nbsp; These measurements are not even meant to be <a href="#articleGlossary">toy
benchmarks</a>, but are just presented for interest."
<br>&nbsp;&nbsp;&nbsp; <b>Time millisecondsToRun: [100 factorial]</b>
<br>&nbsp;&nbsp;&nbsp; <b>Time millisecondsToRun: [1000 factorial]</b>
<br>"On my P200, the above lines took:
<br>&nbsp;&nbsp;&nbsp; 0.020 seconds
<br>&nbsp;&nbsp;&nbsp; 5.967 seconds"
<p>&nbsp;&nbsp;&nbsp; People with some programming experience will notice
that we didn't have to fuss with what types of numbers we're working with,
(integers, large integers, floats, large floats), or type mismatches, or
predefined size limitations, or wrapping primitive types in objects then
unwrapping them or any other of this type of nonsense ;-).&nbsp; We just
naturally typed in what we wanted to do without having to do any jumping
through hoops for the sake of the computer.&nbsp; This comes from the <b>power
of P&amp;P</b>:&nbsp; Pure objects and Polymorphism (which we'll discuss
next time).
<h2>
<a NAME="questionsAndAnswers"></a>Questions and Answers</h2>
These are the answers for questions on previous articles that I could work
through in my limited time available.&nbsp; I picked out the ones I thought
most appropriate for the series.&nbsp; If you want a faster response, or
I didn't get to your question, try posting your question to the comp.lang.smalltalk
newsgroup, or the <a href="http://minnow.cc.gatech.edu/squeak/1">Swiki</a>.
<p><b>Q: Can you show how your examples can be done in Java?</b>
<br>I'll try and answer this without getting on a soapbox (language questions
are often equivalent to religous questions).&nbsp; There's three parts
to this answer:
<ol>
<li>
Over the years, I've programmed in a decent number of languages/environments<sup><a href="#footnotes">6</a></sup>.&nbsp;
I've been programming in Java off and on since '95, and like any language
it has its pros and cons.&nbsp; However, I don't find programming in Java
very fun.&nbsp; On my day job I'll work in Java, C, C++, etc as needed
since they're just tools to get a job done, but for my hobby projects I
use Smalltalk.</li>
<li>
I find Java is just redoing a lot of stuff that Smalltalk already had (garbage
collection, virtual machine, JIT VM, write once run anywhere) with the
baggage of trying to be similar to C/C++ (primitive types, large amount
of syntax, encouraging functional programming, strong typing).&nbsp; I
don't want to play around with old news for hobby projects, I like to play
with new and nifty stuff.</li>
<li>
I really like meta programming, which I just can't do in Java or Windoze.</li>
</ol>
<b>Q: What is a good beginner's Smalltalk book?</b>
<br>A: This really depends on what your motivations are.&nbsp; For Squeak,
I don't know of any good beginner's books as all the material I've seen
on it has been <a href="http://minnow.cc.gatech.edu/squeak/377">free online
resources</a> (even better than a book IMHO) Be sure to check out <a href="http://minnow.cc.gatech.edu/squeak/471">The
Squeak FAQ</a> (This is also a Wiki, so the cool thing is that you can
post your own questions to a living document).
<br>&nbsp;&nbsp;&nbsp; Personally, I've found many beginner Smalltalk books
to be written at too simple of a level.&nbsp; If pressed, I'd have to say
my favourite introductory Smalltalk book is <u>Smalltalk by Example</u>,
by Alec Sharp, ISBN 0-07-913036-4.&nbsp; It's geared towards beginner->intermediate
topics for VisualWorks Smalltalk.&nbsp; If you want you can get the NonCommercial
version of VisualWorks to play in, though many of his examples should work
in Squeak.
<p><b>Q: What is a skin?</b>
<br>A: A skin is an installable look-n-feel or theme.&nbsp; In squeak you
can install a Windoze look-n-feel, MacOS Aqua look-n-feel, etc.&nbsp; (not
sure how many skins are out there or what state they're in).&nbsp; I remember
VisualWorks Smalltalk having the skins concept back in '94 (wasn't called
a skin back then)- it's one of the things about Smalltalk that first caught
my eye.&nbsp; At the time I had just spent a year doing a very painful
port of OpenWindows to Motif for parts of a C based application, then I
stolled past a coworker's desk and they showed me how they could switch
the look-n-feel of their Smalltalk application from Windoze to Motif to
MacOS with a click of the mouse.&nbsp; Talk about a productivity boost!
<p><b>Q: Can you have Smalltalk run in web browsers?</b>
<br>A: You certainly can, in fact I thought about setting up a Squeaklet
that people could execute the snippets from this series in from the comfort
of their web browsers... yeah, you can have a development environment in
your web browser, not just runtime code.&nbsp; However, it was just one
more thing for me to do in my limited time and I decided to forgo it for
now.&nbsp; This is a possible future topic.&nbsp; BTW - most flavours of
Smalltalk have some mechanism to run thin clients in a web browser.
<p><b>Q: Where is the 'main' function?</b>
<br>A: Smalltalk doesn't have a 'main' function, this can be confusing
to Smalltalk newbies as so many other languages have this notion.&nbsp;
Conceptually, Smalltalk is an always running set of live objects which
is why there is no 'main' function - if your enviroment is always running,
having a 'main' function is nonsensical as you're not starting or ending
anywhere.&nbsp; When you want to start an application you've written, you
merely ask it to open up its window that it uses as a starting point.&nbsp;
When you deliver an application, you merely open up your application's
starting window and package your environment (this is a simplification
here).
<br>&nbsp;&nbsp;&nbsp; Realistically though, you have to have some starting
point as you need to shut down your computer sometimes.&nbsp; Well, Smalltalk
does what is called saving an image.&nbsp; It's called an image because
what you're saving is really a snapshot in time of your environment.&nbsp;
When you start it up again, everything is exactly where you left it.&nbsp;
To do this, Smalltalk has some bootstrap code to get itself going again,
which could technically be considered a 'main' function.&nbsp; However,
the point is that you do not have a 'main' function when writing an application.
<h2>
<a NAME="articleGlossary"></a>Article Glossary</h2>
This is a glossary of terms that I've used for the first time in this series,
or a term that I want to refine.&nbsp; If you don't see a term defined
here, try the ongoing glossary in the local location: <a href="../ongoingSeriesGlossary.html">[LL].</a>
<br><b>Class</b>
<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (def 1-simple)&nbsp; You
can think of a class as a blueprint object for making objects.
<br><b>Encapsulation</b>
<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; The grouping of messages
and data within something we call an object, such that other objects can't
see the data and can only get access to it via messages.
<br><b>File it in</b>
<br><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </b>The act of loading Smalltalk
code into Squeak.
<br><b>Instance Variable</b>
<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (def 1-simple)&nbsp; The
place where objects store their properties/characteristics
<br><b>Instantiate</b>
<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {In-stan-shee-ate} When
we ask a class to make a new instance of an object, we say that we're instantiating
that object.
<br><b>Message</b>
<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (def 1-simple)&nbsp; A request
you can ask of an object.
<br><b>Method</b>
<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (def 1-simple)&nbsp; Determines
how an object will respond to a message.&nbsp; The method in which an object
responds is determined by a method.
<br><b>Object</b>
<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (def 2) an object is a grouping
of messages and data that its messages can operate on.
<br><b>Object bloat</b>
<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (def1 - simple) When an
object does too many things and is 'spread too thin'.&nbsp; A jack of all
trades does everything pretty poorly.
<br><b>Responsibility</b>
<br><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </b>The things that an
object can/should do.
<br><b>Toy benchmark</b>
<br><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </b>A benchmark is a
method of measuring the performance of something, and a toy benchmark is
a trivial benchmark that doesn't give a good refection of performance as
it's too simple or too narrow.
<br><b>Variable</b>
<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (def 1-simple)&nbsp; A holding
reference for something, for example, a holding space for an object.&nbsp;
It gives you a handle to refer to that something that it is holding on
to for you.
<h2>
<a NAME="footnotes"></a>Footnotes</h2>
[1] As Eric Clayberg once pointed out in comp.lang.smalltalk, technically
speaking Smalltalk has no reserved words, since you can create methods
using these reserved names (though you sure wouldn't want to!)&nbsp; Though
I agree on this technicality, I include these words, as for practical purposes
they are reserved.
<br>[2] Does it show I'm a Canuck?
<br>[3] Actually, in practice we'd probably just name the method <b>height</b>,
with the <b>whatIsYour</b> or <b>whatIsMy</b> height implied.
<br>[4] Properties of objects can be stored in other places too, but I'm
not going into that now, this is a very common place to store things.
<br>[5] See [1]
<br>[6] Smalltalk (VisualWorks, VSE, VisualAge, Squeak), Java (VisualAge,
J++), C, C++, Tcl/Tk/Expect, sh/ksh/csh scripting, Turbo Pascal, Fortran.
/ Solaris, SunOS, HP-UX, Linux, Windows NT, 95, &amp; 3.1, Mac OS
<p>
<hr WIDTH="100%">
<h2>
<a NAME="statementOfPurpose"></a>Statement of purpose</h2>
&nbsp;&nbsp;&nbsp; When I wrote the first Making Smalltalk with the Penguin
<a href="http://www.linuxgazette.com/issue51/steffler.html">article
back in March of 2000</a> <a href="../issue0-tourOfSmalltalk/tourOfSmalltalk.html">[LL]</a>,
my target audience was experienced programmers who didn't have much exposure
to <a href="#articleGlossary">OO</a> programming or to Smalltalk.&nbsp;
The article's intent was to give an overview of my favourite programming
language on my favourite operating system.&nbsp; Since then, I've had a
fair amount of email asking introductory type questions about Smalltalk
and OO programming.&nbsp; So I thought I'd try my hand at a small series.
<br>&nbsp;&nbsp;&nbsp; The target audience for this series are people new
to OO or new to programming altogether.&nbsp; The intent is to not only
introduce OO programming, but to also spread the fun of Smalltalking.&nbsp;
Why do this format/effort when there's lots of good <a href="http://minnow.cc.gatech.edu/squeak/377">reference
material out there</a>?&nbsp; Two reasons really:&nbsp; 1) Tutorials are
great, but can be static and dated pretty quickly.&nbsp; 2) An ongoing
series tends to be more engaging and digestible.
<br>&nbsp;&nbsp;&nbsp; To help address the second reason above, my intent
is to keep the articles concise so they can be digested in under an hour.&nbsp;
Hopefully, as newbies follow along, they can refer back to the original
article and make more sense of it.&nbsp; I plan on having a touch of advanced
stuff once in a while to add flavour and as before, the articles are going
to be written for read-along or code-along people.
<br>&nbsp;&nbsp;&nbsp; Something new I'm going to try is to make the ongoing
series viewable in a contiguous fashion and downloadable in one chunk for
people who want to browse the series locally.&nbsp; To do this, click on
TOC grapic to at the top of the article.&nbsp; The articles also have 2
sets of links:&nbsp; one set for www links, another set for local links,
indicated as: <a href="#articleGlossary">[LL]</a> for downloaded local
reading.
<h2>
<a NAME="whySmalltalk"></a>Why Smalltalk?</h2>
&nbsp;&nbsp;&nbsp; I believe Smalltalk is <b><u>the best</u></b> environment
to learn OO programming in because:
<ul>
<li>
Smalltalk has a very active and very helpful community; when you post a
question to the Smalltalk newsgroups you very often get an answer, unlike
many other newsgroups</li>
<li>
is very easy to learn... one of it's original design intentions was to
be a learning environment for children</li>
<li>
is a pure OO environment and encourages OO programming (as opposed to encouraging
procedural/Object mixed programming)</li>
<li>
cutting your teeth in Smalltalk makes you a better OO programmer in any
other language, because of the previous bullet</li>
<li>
is a portable environment:&nbsp; write once, run anywhere, so people can
learn on whatever OS they're running&nbsp; (as opposed to just the M$ variety)</li>
<li>
can look at and manipulate objects in real time; I haven't seen this ability
in any other environment</li>
<li>
Smalltalk is written in Smalltalk.&nbsp; You can view how the language
is put together to learn the language, and you can change anything that
you don't like about it.</li>
<li>
has garbage collection, no manual memory management, no explicit pointers</li>
<li>
is a literate language; by this I mean the syntax is very simple and is
geared towards programmer readability.</li>
<li>
there's lots of Cool Things that you can do in it that I haven't seen anywhere
else (will have some examples along the way)</li>
<li>
...and best of all: <b><u>it's fun</u></b>.</li>
</ul>
In particular, I'm going to use <a href="http://www.squeak.org/">Squeak</a>
as the playing vehicle.&nbsp; You'll notice this is a different flavour
of Smalltalk than I used in my first article.&nbsp; I've never used Squeak
before, so this'll be a learning experience for me too.&nbsp; The reasons
for this are:
<ul>
<li>
It's a completely opensource project</li>
<li>
It has some Really Cool features that I haven't seen in other flavours
of Smalltalk</li>
<li>
It has a comparitively small footprint and it's very easy to install</li>
<li>
It has a strong <a href="http://minnow.cc.gatech.edu/squeak/1">Swiki site</a>&nbsp;
(a <a href="#articleGlossary">Wiki</a> site hosted in Squeak, hence <b>S</b>queak
<b>Wiki</b>)</li>
</ul>
<hr WIDTH="100%">
<h2>
<a NAME="personSampleCode"></a><b>Person Sample Smalltalk Code</b></h2>
This is a sample of what the Smalltalk code looks like for the curious
or for people who want to compare with known languages.&nbsp; For people
who are confused by below code, don't worry, as we'll be stepping through
how you create it and what it means in a future article.
<p><b>"This is a Class definition"</b>
<blockquote><b>Object subclass: #Person</b>
<br><b>&nbsp;instanceVariableNames: ''</b>
<br><b>&nbsp;classVariableNames: ''</b>
<br><b>&nbsp;poolDictionaries: ''</b>
<br><b>&nbsp;category: 'MakingSmalltalk-Article2'</b></blockquote>
<p><br><b>"My Characteristics is a category of methods for the class (similar
to an interface in Java (but it's not enforced))"</b>
<blockquote><b>Person methodsFor: 'My Characteristics'</b></blockquote>
<b>"The 1 method in the My Characteristics category"</b>
<blockquote><b>whatIsMyHeight</b>
<br><b>&nbsp;"Actually, in practice we'd probably just name this method
'height', with the 'whatIsMy' implied.</b>
<br><b>&nbsp;Simple example to show how a query about my characteristic
can be done.&nbsp; Ah-ha - notice that the height is not being returned
via an instance variable as we guessed at above, but is in fact hardcoded...
A BAD PRACTICE TO DO, but is fine for this example to keep things simple,
and wanted to show how to do a ' in a string"</b>
<p><b>&nbsp;(Workspace new contents: 'My height is 5'' 7"') openLabel:
'This is my height'! !</b></blockquote>
<b>"This is the singing category, it has 6 methods"</b>
<blockquote><b>Person methodsFor: 'Singing'</b></blockquote>
<b>"And the methods for singing - method 1 of 6"</b>
<blockquote><b>maryHadALittleLambLyrics</b>
<p><b>&nbsp;^'Mary had a little lamb, little lamb, little lamb, Mary had
a little lamb whose fleece was white as snow.'</b></blockquote>
<b>"singing method 2 of 6, we use the 'my' prefix convention to indicate
a private method"</b>
<blockquote><b>mySing: someLyrics inManner: anAdjective withTitle: aTitle</b>
<br><b>&nbsp;"Using simple logic here for illustrative purposes - if the
adjective is not 'loudly' or 'quietly' just ignore how we're being asked
to sing"</b>
<p><b>&nbsp;| tmpLyrics |</b>
<br><b>&nbsp;anAdjective = 'loudly'</b>
<br><b>&nbsp; ifTrue: [tmpLyrics := someLyrics asUppercase].</b>
<br><b>&nbsp;anAdjective = 'quietly'</b>
<br><b>&nbsp; ifTrue: [tmpLyrics := someLyrics asLowercase].</b>
<br><b>&nbsp;self mySing: tmpLyrics withTitle: aTitle</b></blockquote>
<b>"singing method 3 of 6"</b>
<blockquote><b>mySing: someLyrics withTitle: aTitle</b>
<p><b>&nbsp;(Workspace new contents: someLyrics) openLabel: aTitle</b></blockquote>
<b>"singing method 4 of 6"</b>
<blockquote><b>sing</b>
<p><b>&nbsp;self mySing: 'Do be do be doooooo.' withTitle: 'A bad impression
of Sinatra'</b></blockquote>
<b>"singing method 5 of 6"</b>
<blockquote><b>sing: aSong</b>
<p><b>&nbsp;aSong = 'MaryHadALittleLamb'</b>
<br><b>&nbsp; ifTrue: [self mySing: self maryHadALittleLambLyrics withTitle:
'Mary had a little lamb']</b>
<br><b>&nbsp; ifFalse: [self sing].</b></blockquote>
<b>"singing method 6 of 6"</b>
<blockquote><b>sing: aSong andDoIt: anAdjective</b>
<p><b>&nbsp;aSong = 'MaryHadALittleLamb'</b>
<br><b>&nbsp; ifTrue: [self mySing: self maryHadALittleLambLyrics inManner:
anAdjective withTitle: 'Mary had a little lamb']</b>
<br><b>&nbsp; ifFalse: [self sing].</b></blockquote>
<a href="http://www.magma.ca/~jagwar/makingSmalltalkForwardingPage.html"><img SRC="misc/steffler/toc.jpg" ALT="Series Table of Contents" align=right></a>
<H2>Previous Articles</H2>
<UL>
<LI> <A HREF="../issue51/steffler.html">A Quick Tour of Smalltalk</A>
<LI> <A HREF="../issue59/steffler.html">Spreading the OO Fun (series introduction)</A>
</UL>
<P> The image on the right links to Steffler's site.
<BR CLEAR="all">
<!-- *** BEGIN copyright *** -->
<P> <hr> <!-- P -->
<H5 ALIGN=center>
Copyright &copy; 2000, Jason Steffler.<BR>
Copying license <A HREF="../copying.html">http://www.linuxgazette.com/copying.html</A><BR>
Published in Issue 60 of <i>Linux Gazette</i>, December 2000</H5>
<!-- *** END copyright *** -->
<!--startcut ==========================================================-->
<HR><P>
<CENTER>
<!-- *** BEGIN navbar *** -->
<IMG ALT="" SRC="../gx/navbar/left.jpg" WIDTH="14" HEIGHT="45" BORDER="0" ALIGN="bottom"><A HREF="sipos.html"><IMG ALT="[ Prev ]" SRC="../gx/navbar/prev.jpg" WIDTH="16" HEIGHT="45" BORDER="0" ALIGN="bottom"></A><A HREF="index.html"><IMG ALT="[ Table of Contents ]" SRC="../gx/navbar/toc.jpg" WIDTH="220" HEIGHT="45" BORDER="0" ALIGN="bottom" ></A><A HREF="../index.html"><IMG ALT="[ Front Page ]" SRC="../gx/navbar/frontpage.jpg" WIDTH="137" HEIGHT="45" BORDER="0" ALIGN="bottom"></A><A HREF="http://www.linuxgazette.com/cgi-bin/talkback/all.py?site=LG&article=http://www.linuxgazette.com/issue60/steffler.html"><IMG ALT="[ Talkback ]" SRC="../gx/navbar/talkback.jpg" WIDTH="121" HEIGHT="45" BORDER="0" ALIGN="bottom" ></A><A HREF="../faq/index.html"><IMG ALT="[ FAQ ]" SRC="./../gx/navbar/faq.jpg"WIDTH="62" HEIGHT="45" BORDER="0" ALIGN="bottom"></A><A HREF="lg_backpage60.html"><IMG ALT="[ Next ]" SRC="../gx/navbar/next.jpg" WIDTH="15" HEIGHT="45" BORDER="0" ALIGN="bottom" ></A><IMG ALT="" SRC="../gx/navbar/right.jpg" WIDTH="15" HEIGHT="45" ALIGN="bottom">
<!-- *** END navbar *** -->
</CENTER>
</BODY></HTML>
<!--endcut ============================================================-->