Ah Ha!!

7 November, 2006

skylight

The following was origanally posted to the beginners list. If you have questions the beginners list is a good place to go for help. You can find the beginners list here.

Learning Smalltalk is definitely and experience. There is a major “Ah-ha!” moment prerequisite. It is really amazing to see people hit that “Ah-ha!”.

Some people do it quickly but most take some time. I’ve seen it come after even a years worth of practical hands on programming, so don’t get frustrated if it doesn’t come right away.

The best I can do to help you is to give you some hints on how to get there yourself.

1) Object message. Programming in Smalltalk really doesn’t get much harder then this concept. Object message.

it := Consider theConcept.
you := Person new.
you live: it.
you breathe: it.
you sleepOn: it.

What is the Object? (An instance of a class or class definition)
What is the message?

Everything is Smalltalk follows this pattern; there is an Object and a message. The message or method may have parameter.

2) Your code goes everywhere! One of the first questions I’m always asked is; “Where does my code go?” The answer is EVERYWHERE! In Smalltalk you are building objects. By that I mean you can model real things. Pick anything and think of it as a component of the rest of the system, and consider what components make up this thing. For example: aShoe.

aShoe := Shoe new.
aShoe laces: ShoeLace greenLaces.
aShoe color: Color green.
aShoe price: (USDollars dollarValue: 12).
aShoe owner: aManufacturer.

You can see that there are many different components or Objects that can make up what you are modeling. Relationships can be modeled, new components can be added, you are free to model what ever you want. So where does your code go? It goes where it is needed. It goes in the object that needs that code.

For example sell a shoe:

Manufacturer>>sell: aShoe to: aPerson
“sell a shoe to aPerson collect price, update books and decrease inventory”
aPerson collectMoney: aShoe price.
self updateMonthyBooks: (Sales item: aShoe price: aShoe price date:
Date today).
hasInventory := self removeFromInventory: aShoe.
hasInventory ifFalse: [
self backOrder: aShoe
].

You can see lots of objects that are implied in this code but look at where the code is. aPerson which is an instance of Person is responsible for paying so collectMoney: is on Person. There could be lots of ways that a person could pay so let the person object handle that. The manufacturer has its own account books so it should be able to updateMonthlyBooks: whichcould be sent to an AccountingSystem instance.

I also hear: “Once I make a really great shoe, how do I hook that into the rest of the system?” This really confuses some people. Try to see your program as more then just pieces, but instead as a whole entity. When you realize that your program could start like this: ShoeStore open. Or MyWorld turn. Or MyWorldsTime start. Or Universe explode. It’s easy to consider how a shoe might fit in your program.

3) Polymorphism and Inheritance. Do I need to understand these to understand Smalltalk? YES!! But don’t worry. They are big words for simple concepts. You are a child of your parents. You inherit certain characteristics from them, which make you like your parents, but you change some of the characteristics to allow you to be more of yourself (polymorphism).Polymorphism means having many forms.So how does that help? The concept of objects would be good enough and still be very powerful without this functionality but when you add in Inheritance and Polymorphism you really start to cook! These concepts really get things moving and allow you to do some fantastic programming.Let’s extend the shoe store example. What if we wanted to sell socks or shoe polish, or custom shoe laces?What are the things that are similar that could be modeled as a superclass so that our salesItems could inherit those behaviors?Object subclass: SalesItems
instanceVariables: ‘purchaseDate purchasePrice manufacturer’
SalesItem subclass: Shoe
SalesItem subclass: ShoePolish
SalesItem subclass: ShoeString

You can see from this example that subclasses of SalesItem inherits the instanceVariables purchaseDate purchasePrice and manufacturer.

We could implement methods on SalesItems that allow us to sell a general item without having to implement these methods on every item. That is the power of inheritance.

Now what things need to be different for each item? Since I’m making this up as I go let me apologize if this is not the best example.

Say that our store likes to make funky shoes by buying them from the manufacturer, then changing the laces. We also sell other funky laces, and we allow people to change the laces before they leave the store if they want too. How are we going to keep track of all this?

We want to be able to just sell and item without having to worry about this, so

SalesItem>>removeFromInventory: anInventory
“remove this item from anInventory”
anInventory removeFromInventory: self.

Now if you call this method on ShoePolish then anInvetory will removeFromInventory: self (self is an instance of ShoePolish since this method is called from there). This method is inherited.

Let’s change things for Shoe

Shoe>>removeFromInventory: anInventory
“remove this item and it’s shoe laces from anInventory and replace shoelace if necessary”
| lacesWereChanged theShoesLaces |
anInventory removeFromInventory: self.
lacesWereChanged := self askUserIf: ‘Were the laces changed?’.
theShoesLaces := lacesWereChanged
ifTrue: [self askUser: ‘Please select laces from list’ forItemInList: anInventory shoeLacesList]
ifFalse: [self laces].
anInventory removeFromInventory: theShoesLaces.

Now this is polymorphism. When you remove an item from inventory it will do what you want since it inherits a method from SalesItems. If it doesn’t do what you want you can give your object its own personality by changing what it does. This is polymorphism.

Go forth and Smalltalk, and if you have questions feel free to ask! This is the place to do it.

Ron Teitelbaum
President / Principal Software Engineer
US Medical Record Specialists
Ron@USMedRec.com

47 Responses to “Ah Ha!!”

  1. Greg Smith Says:

    This may constitute an “Aha!” moment for some, but not for me. In the several examples above, all kinds of syntax has been used without any explanation. The examples already assume that I know something about Smalltalk. There are described no “why”s, only “what”s. Very typical of every programming “beginner’s” guide I have ever seen.

    The only time that an “Aha!” moment will ever occur for the total novice will be when someone bothers to start at the absolute beginning and teach the total novice how to program, using Smalltalk as the vehicle – explaining the why’s for the syntax and why something needs to be phrased in a certain way and why a thing must appear in a certain order – as well as thoroughly explaining “what” the lines of code, one at a time, word for word, do precisely.

    And, the only way such instruction will ever “sink in” will be when the instructor provides specific and numerous examples of code that do precisely what the student would like to accomplish. If the student wants to learn to program so that he can manipulate things in a graphical environment, then the examples must be given which are specific to that environment. Giving this same student examples which teach how to assemble a database, for example, are not going to provide the kind of information that he needs nor will be inclined to retain.

    Greg Smith


  2. @ Greg Smith

    Hi Greg,

    I invite you to the beginners list. There are a number of Smalltalk references available even plenty of free books you can read. This post was originally for beginners that are already trying to learn Smalltalk. I copied it here because of the comments that I received. Please come and join us and if you have a specific question about Smalltalk I’m sure it will get answered there. See the link at the top of the article to join.

    Everyone’s Ah Ha comes differently. I’ve taught a number of people, and lead a very large group of developers. I’ve seen the Ah Ha many times and it’s always fun to watch. I had one person come back and tell me that he wrote down everything I said. He spent weeks trying to understand. Then after his Ah Ha! he came back and said, everything you said all makes sense now. It’s really fun. If you really want to learn Smalltalk come join the list.

    Happy coding!

    -Ron


  3. Hi Ron,

    I have to agree with Greg. Cruddy article. This[1] is better. I know BASIC,C,C++,Java, I’ve played around with Perl but it doesn’t seem to stick. I’ve never gone near Python, the indent thing seems weird. I’ve studied Prolog and Lisp. I’ve done Intel x86 assembly. All languages have cool stuff.

    Will I have an Ah Ha moment? I just did reading the link I gave you. Keyword Messages are concatenated! That’s plain weird, but cool. This means unary and binary messages (we like to call them operators in the real world) are handled differently and can’t be thought of as methods. However concatenating Keyword Messages means you have a combinatorial explosion of selectors (er, method names). Wow. But um, why? And I’ve read I don’t know how many tutorials but how the hell do you define messages. (If you say you pass a message to the message defining object then I’ll hit ya. Where are the logical operators, the syntactic sugar like if.) I don’t know. I know I’m rambling. I think ye Smalltalk peeps are weird. But I’ll keep reading and I’ll definitely play around with Squeak and OpenCroquet.

    regards,
    Anthony

    ps: ruby seems to hit the pure oop sweet spot for lots of peeps

    [1]: http://www.exept.de:8080/doc/online/english/getstart/tut_2.html

  4. Greg Smith Says:

    I really don’t want to make a sweeping generalization, but here comes one: I don’t think the evidence supports the concept that programmers – the best, most theoretically knowledgeable, practical programming masters, are very good at explaining what they know and practice. Either that, or they simply do not care to share with anyone other than their immediate peers, programming knowledge that can empower the “masses”. There might even exist an old world “guild” attitude toward those who would like to know.

    Just ask Alan Kay. We have had more than 40 years to have the concept that some programmer, any programmer has the wherewithal to demonstrate to those who don’t know what they know, in a clear, point by point, jot by jot, tittle by tittle fashion. And, I say jot by jot and tittle by tittle, because programming, by its very nature, does not allow for any other form of expression. It is, in nearly no way, similar to human language – so please don’t promote the idea that one learns by doing or “speaking” the language, with all kinds of ways to “say” the same thing – this just is not so. Programming is as unforgiving as mathematics, in terms of its syntax and logic, or nearly so.

    As Alan Kay has said with regard to mathematics, the same could be said about programming: ‘we need to train people to become something other than mere “mechanics” of technology’. Whatever happened to the notion of the computer “scientist”? Who bothers to train people to become computer scientists?

    The real computer revolution will come about when someone who truly knows cares enough, and takes sufficient time to make programming concepts, techniques and “languages” understandable to those who are NOT “in the know” – those without a prior background and education in the subject in question.

    Greg Smith


  5. @Anthony

    Hi Anthony,

    Wow! I do love the link, I’ve run across it before and it’s very nice. This article is more about the Ah Ha! moment then about teaching Smalltalk. The hints I give are intended as suggestions for places to start and some examples that may helps some people get there sooner.

    As for keyword concatenation I think you may have missed the meaning. In the example that the your link mentions: “between:” and “and:” are the keywords [snip] The messages actual selector is formed by the concatenation of all individual keywords; in the above example, it is “between:and:”.

    This does not mean that the individual messages are concatenated. It does not send #between: and then #and: it sends one message defined as #between:and: . The point was not that you can make combinations of existing messages but that if you need to send another message and you have used an argument you need a parenthesis.

    So consider the following:

    1. Object message.
    2. Object message1 message2.
    3. Object message1; message2.
    4. anObject message1; message 2; yourself
    5. Object message: argument
    6. Object message1: argument1 message2: argument2
    7. (Object message: argument1) message2: argument2

    Everything in Smalltalk is Object message. This means that for anything to work you must have an Object and you speak to that Object by sending it a message. The message returns some object. It may be the same object or another object. Like you said you can then send another message.

    This is called message chaining. You can send another message to the result of your previous message see 2.

    Now you may want to chain but instead of sending the message to the result of the previous message you want to send it to the same object as the previous message, you do that in Smalltalk by using the semicolon. See 3.

    Example 4 is a better example of this since we are more likely to be chaining messages to instances of objects then to the class itself so for 4 consider anObject to be an instance of the class Object (or anObject = Object new). Here we send the message message1 to anObject, then we chain another method message2 and send it again to anObject ignoring the result of message1. You can retrieve back anObject by sending the message yourself at the end which just returns self.

    Example 5 shows how you can send in a parameter to your method, and example 6 shows how you can send in multiple parameters. In example 6 the method is defined using both keywords. For example, if you have two methods #message1: and #message2: but do not have #message1:message2: defined then the system does what it is supposed to do! It blows up! It doesn’t do any keyword concatenation.

    The last example 7 shows how to chain messages appropriately if you want to send multiple methods using arguments. You must enclose the first method in parenthesis. Then the results of the execution inside the parenthesis returns an object that can accept the next method.

    I invite you also to the beginners list. I hope that even if this article didn’t give you that Ah Ha! moment that you visit this article again after you reach that point and see if the concepts were the right place to start or not.

    -Ron


  6. @Greg

    Hi Greg,

    I really have to disagree with you. While many languages are very unforgiving the syntax of Smalltalk is very easy to learn. The concepts of programming in general are easily translated to Smalltalk but Smalltalk does not teach you programming.

    Most of what we do in Smalltalk only requires we follow a few simple rules. The rest we just make up! Most of the code in this article was just made up on the spot.

    We get to name the objects what ever we want, we decide what questions it can answer what information it remembers. It is a very creative language. The best part of Smalltalk in my opinion is that we have the tools necessary to understand fully the behavior of objects even if they were written by someone else.

    If you start with Object references [using the menu option on the browser] it will show you every method that uses this object. You can then browse senders of that method to see everyone that uses the object and how. You can browse implementers of methods to see which objects understand the same question or request and see how they answer.

    You can make real live objects in Smalltalk and play with them using inspectors and workspaces, and you can even change code right in the debugger and continue on without even thinking about compiling your code.

    I’ve taught a lot of people about Smalltalk and I still believe that everyone learns differently, but that most people get Smalltalk by using it. Eventually if you keep slipping in the main concepts they hit that Ah Ha! moment and it’s like a light going on. All of the sudden the syntax disappears, the constraints of the language disappear, and all you are left with is pure creativity.

    Did you join the beginners list?

    -Ron

  7. Greg Smith Says:

    Ron:

    Thanks for stating the reasons for your disagreement. I’ve been on the beginners and the regular SmallTalk list for quite a while now. I keep hoping to find someone who begins stating things from the beginning, but, unfortunately, most have very specific things they are trying to accomplish and approach the problem with questions that are specific to those things. I still do not have a good overall picture of SmallTalk and what it can do. It is very vague. I know it is a language, I know it has simple syntax, but I don’t know even how to begin, with small things and develop those small things into bigger things. Very foreign to my way of thinking.

    Greg Smith


  8. @Greg

    Hi Greg,

    What are you trying to do?

    I have to tell you that I got a lot of positive feedback about this article from other people. What I didn’t do was ask you if it helped you. Which obviously it didn’t. That was insensitive considering I originally wrote the article for you! I appologize for not realizing that earlier.

    Tell me about your goals, what you are trying to do, and let’s see if we can’t do Smalltalk from the beginning. We will probably start with the three concepts above but in more detail. If you are willing to work, I’m willing to help.

    -Ron

  9. Greg Smith Says:

    Ron:

    I really appreciate your offer, but I feel for someone to put that much effort into providing learning material for someone else, it’s definitely worth some actual money. I would never expect you to offer this assistance for free. Now, the Squeak Foundation should have already provided this at some level – I mean training for the absolute beginner with no programming experience. At least I think that would have launched the project with a lot more strength. It would be unfair to everyone else for you to put out that much effort for one possible user.

    My ambitions are pretty high and my programming abilities are really low. All code reminds me way too much of algebra – which I never understood at all, (though I managed to become enough of a mechanic to get good grades in it). I have no desire to become a Squeak mechanic.

    To give you an idea how I would choose to start and then progress with mastering the theory and practice of Squeak, imagine this neat “toy” program:

    I design one “base” object, a playing “board” or “field”, which contains a plethora of underlying “forces”, pathways, 3 dimensional travel,(using the analogy of lego dots), several entrances and several exits – to the next level or “board”. Everything parallels exactly a thing that could be made in the real world, giving the user an immediate grasp of the environment. The basis for a virtual, yet highly interactive lego kind of game.

    Further imagine, building upon the functionality implied in the “board” object, simple and specific “parts” or “players” or parts that can be combined to form “players”, beautifully adapted, each and every one, to navigating in one way or the other, to different places on the board. One “part” might simply possess the ability to move forward or backward and side to side, (limited by the “board’s” dot system). It has an input “plug” and an output “plug”. When it is plugged into by another part possessing the ability to levitate vertically for a period of time, the combined parts form a player which can both move forward, backward, side to side, as well as levitating to navigate over obstacles.

    By designing each part or player to do something simple, programming should be able to be kept to a minimum for each part, and the part with its program should be an obvious example of “encapsulation”, if I’m using the right word. By plugging simple parts together with other simple parts, the idea of message sending and receiving should also be made really clear, (from part to part and part to board), if I even understand the concept, according to Squeak, at all.

    Now, coming from a totally graphical background, I would want the whole thing to look real and tangible. I would want things to move as they should and look real. This, probably, would constitute the bulk of the programming muscle, and I wouldn’t even know where to begin manipulating graphic classes – and in 3D space, to boot!

    You can see, my project is far too tall an order. I have no interest in making yet another data base, spread sheet, word processor, inventory control manager, spell checker, menu maker, monster blaster, etc. This seems to be the basic list that all programming teachers draw from when teaching beginning programming.

    Oh, I also do not wish to learn to drive a little car around. That concept, presented simply in the eToys environment does teach you, simply, how to drive a little car around in 2D space, but it does not teach you to program the same behavior in Squeak. True, you could look at the underlying Squeak code, but I don’t think a novice could learn to program based on what he sees there. The same goes for most of the other “packaged” eToy behaviors. So, there still remains a very large gap for those wanting to really understand Squeak as their first and only programming language, which is what I desire to do.

    Thanks,

    Greg Smith

    No, I think my project would explain a whole lot to a whole lot of people wishing to learn Squeak from the ground up. No spreadsheets needed.


  10. @Greg

    Hi Greg,

    Before I respond I’d like to make some comments about eToys. First I am not an eToy expert. I’ve played with eToys and I’ve answered some questions for beginners, but I do not spend very much time doing tile programming. As a programmer I can see what concepts are being used in the background. Much of what you see on eToys does translate to actual programming concepts but I agree that those concepts are hidden enough to make what you are seeing confusing once you try to look under the hood.

    What you are explaining, pluggable physical attributes of a player are very doable in Squeak. So although I can not offer a complete solution, I can help you see that what is under the hood can be understood and used to do exactly what you want to do.

    Before this first lesson you will need to visualize a virtual world. One where you can see nothing. This may be difficult because you are an artist. As you mentioned when you do not have some visual feedback it is difficult to know if what you are doing is working. So we will need to satisfy that need for something to hold and change with other tools that are available in squeak.

    First things first. Lets begin Smalltalk from the beginning.

    Object message.

    What is Object? Object is a real thing. It is not a program, it is not math. Think of an object as a physical thing you can not see.

    Before doing anything else it’s important to know that Object itself is the parent of all other Objects. There are higher levels but let’s leave these out now. Object is just what it sounds like. It is abstract. It is virtual. It is the base of everything.

    You will need to make your own object. We do this by subclassing object. By that we mean that object is a class and we want to make a class under object called something else that we can work with. A Class is a definition of our objects. It’s not the real object but instead it is the definition used to create objects and teach them what to do. Class is a definition, but they create real objects.

    For now how to subclass is not as important as understanding that you need to do it. We can talk about the tools next. First understand that you want to build an object with its own name that is a subclass of the base of everything.

    Let’s take an example

    Object subclass: Tree

    We now have a Tree which is a subclass of Object. We will move on to identify the properties of tree. First what things does a tree need to know? What things does a tree need to be able to do? How do I make a tree? These are all things that you will define. There is no limit in Smalltalk as to what you need to define, or how much detail you can put in. You are free to do what ever you want.

    So I want my tree to know what kind of tree it is. I want it to know how many branches it has. I’d like to define the leaf type, if it has edges and points.

    I want it to drink water, and take in sun to make sugar to eat. I want it to attract bacteria that feeds it nitrogen.

    You can see that the more I think this through the more I can do to build a real world of objects. This is very much like painting. The more detail I add the more real it looks.

    So

    Object subclass: Tree
    instanceVariableNames: ‘numberOfBranches leafType foodBalance waterBalance nitrogenBalance’

    Ok so these are the things that a tree knows. But I’m not happy with leafType because there is more to know so I think I’ll build a leaf.

    Object subclass: LeafType

    LeafType subclass: OakLeaf

    OakLeaf subclass: WhiteOakLeaf

    Here you can see that I want to be able to build many different types of leafs. I define a virtual or abstract LeafType. Then I get more specific by making a subclass called OakLeaf. But there are different Oaks: I have a bunch of beautiful oak trees here where I live. The WhiteOak has rounded leaves and the RedOak has points. I make a subclass to hold these difference but ultimately I end up with the object called WhiteOakLeaf. I will set my tree’s leaf type to WhiteOakLeaf.

    My intention here is to show you that you can create a world and you can add as much or as little detail as you want. We can even start to add pests, Ants, scaleBugs, or tree friendly bugs, Praying Mantis, or LadyBug.

    If from all this all you get is that Objects are real things then we are doing well. This is the what, let me know if you understand and we will move onto the tools and the how.

    If you insist on money, you can donate to Squeak. I’m happy to help spread the joy and the art of object oriented programming.

    Do you get that Object is a real thing, something from real life?

    -Ron Teitelbaum

  11. Greg Smith Says:

    Ron:

    Thank you for this nice example. I do understand that an object is a real thing, or a thing you would like to make real – it could be a fanciful object. I understand that by starting with the tree as a whole, we can then add to the exact nature of that object, tree, by defining its parts, which are also objects.

    It appears, however, that Squeak makes no distinction between subclasses. The leaf occupies the same space in hierarchy as does the tree, since both are identically identified as a direct subclass of the master class “Object”.

    This is already confusing and departs from the natural world, since, in real life, the leaf is dependent and “owes” everything about its existence to the tree, itself, and the tree to the root, the root to the ground, etc. Much dependence exists in the real world, and, at least in this example, no such dependence exists nor has it been defined.

    Then, it is not clear to me at all how you got from defining a leaf of a tree, which we already know is an object with equal “importance” as the tree itself, to other aspects of the tree which are not called objects at all, but “InstanceVariableNames”. Whoever invented this global SmallTalk terminology obviously was not trying to relate what this “language” can do with the real world, or human language, at all. They must have been thinking, “Make it as vague and mysterious as possible so only insiders will understand what we are talking about – let’s form a club – and let’s make our club have a “secret code” language.

    This may be a slight exaggeration, but the authors obviously did not want to make SmallTalk instantly palatable to just anyone.

    And, since I am just someone, not an invited or initiated member of the club, I need to know why they chose such a strange set of words to describe what is really just an adjective in human speech. The leaf is green. The tree is an oak tree. Why make it more complicated than that?

    Using a tied together phrase like, “InstanceVariableNames” does not describe anything I am familiar with, but, rather, produces a lengthy, imaginary string of possible meanings, largely leading me to the assumption that some math may be involved here.

    You see what I mean.

    But, please, go on.

    Greg Smith


  12. Greg:

    OK I see your point. There are definitely some language issues in learning Smalltalk. Hopefully you will find the concepts and the words used easy to learn.

    A Class as we saw earlier is a definition of an Object. An Object can be made of many different pieces, just as in real life there are many different parts and pieces. They may be inextricable but they exists as parts nonetheless. This is also like art. We reproduce we don’t create. So even if objects that we create all share the same parent that doesn’t limit our expressiveness. Just as marble doesn’t limit the sculpture.

    So a Class is a definition. But we can create multiple entities from that definition. Each entity is called an Instance. An Instance is the class definition made real. If I make an instance from a definition what I do to one instance, just as in real life, doesn’t effect the others. For example if I create aTree. aTree := Tree new. Then I can take that tree and do something to do. aTree water. This only waters the instance of Tree we just created, not all instances. Every time I call Tree new, I get a new instance, a new tree.

    So instanceVariableNames is just what it says it is. It is the instances of other objects that are connected to this instance. Those other instances are what this object knows. A variable is a name that can hold values, for us it is instances of things. Keep in mind that in Smalltalk everything is an object. So for example a string ‘hello there’ is an instance of the class String (ByteString to be specific) but String is a collection that holds instances of Character. And here comes the math, a number 1 is an instance of the class Integer.

    To summarize instanceVariableNames are variable names of instances of other Classes which represent what this class knows. Methods are what this class can do or does, but instanceVariables are what this class knows.

    Does that make sense?

    Ron Teitelbaum

  13. Greg Smith Says:

    Ron:

    Thanks for the quick reply. I have to say I’m having some amount of trouble with your explanation and following you from one point to the next. For me, I have to know what the total analogy is before I can know where it is trying to lead me. It appears to me that SmallTalk doesn’t bear much resemblance to anything in the real world, so, I need to know what it does resemble, so I have a reference point.

    Moving quickly in thought from Classes to Objects to Instances to Variables without much detailed explanation regarding why, and then introducing := without any explanation, followed by “do something to do. aTree water”, just doesn’t correspond to anything I know at all. Much confusion is created by the use and misuse of language, especially written language. I don’t think I understand your art analogy, either.

    Although I do understand that things are made of pieces and that pieces are unique entities though reliant and connected to others, I don’t know how SmallTalk defines that concept, and what written language it uses to do so.

    Overall I just don’t see where you’re going.

    When something is called a variable when it is really a kind of an adjective and also a kind of container makes, to me, absolutely no sense at all. Yes, it does vary, I guess.

    Just so I don’t turn this into some kind of tennis game, feel free to keep the lesson going, if you think it will be valuable to others. If I finally get it, I’ll get it. If not, others may vastly benefit, anyway. I’ll just silently follow along, at this point.

    Thanks for your help,

    Greg Smith


  14. Greg,

    I have no idea if you will get it or not at this point. I will have even less of an idea if you are getting it without feedback from you. If you want me to continue you will have to participate whether or not it feels like a tennis match.

    There is no problem asking for more clarification on things that you don’t understand. Although I am trying to make the concepts as easy as possible, doing it well is not always possible. If you like I will try to answer your last post.

    My goal in this is not to teach you the full grammer of Smalltalk, or even to teach you how to program. My goal is to help you understand the main concepts and to show you the basic framweork that you can hang your own learning and expierences on. Eventually what you learn will come from your own initiative. You will get back what you put in. Let me know if you want to continue.

    -Ron Teitelbaum

  15. Greg Smith Says:

    Ron:

    Sorry for the delay in responding. I’ve been away from home and a computer for a week. I’ll think it over and let you know.

    Greg Smith


  16. All,

    While we wait for Greg, there are a few other people following this article. Would any of you like to ask a question?

    Ron


  17. hey greg
    i am a st newbie too. i have been half hearted interested in it for about 5 years, my cousin is hardcore he programed chronos, you may not know what it is but to those who do know. long story short i am learning from him we started last week. i have all most no programming background as i do not count html and okuma lathe code, any whoo. if you want to team up let know. personally i think you are wrong i think those in the know do care but have almost no idea how to teach. i can not tell you how many times i have been told or read well in st all objects are objects, as i just blink repeatly and stare. omitted are my thoughts to that statment.
    jupiterlovejoy.com


  18. ohh
    p.s. ron i think this piece is beautifully written, the reall world example has helped me to understand some of the examples my cousin alan and i hav been going round and round with. we are using visualworks. personally my biggest mental trap is that i do not understand how to start a program or programming. i know that with st i do not have to start at the beginning but i have to start some where, create a object / class-message-symbol. i got that far in last night lesson. but here can i find all of the classes vw must have over 3000 classes and what about the messages or methods, or even about all the objects that are already written. does it even matter since i can define whatever terms i deem i need?
    jupiterlovejoy.com


  19. Hi Jupiter,

    I do know about your cousin’s work. You definitely have a very good teacher. I think your question is a very good one that does reflect real world issues of day to day programming.

    Do we really reuse code? The answer is yes and no. We have a tendency to reuse those components of base classes that are very useful, or difficult to reproduce. Programmers have a tendency to rewrite that which seems obvious or easy to reproduce. The problem is that what seems obvious and easy depends on your skill level. I’ve seen PHD’s rewrite date! (This is not a comment on chronos the guy’s I’m talking about did it wrong!) I even had someone write hundreds of lines of code to reproduce SortedCollection. Now granted “this” sorted collection could do a few extra things (very poorly and it was written in a way that was very hard to understand, blocks being executed all over the place, and hardly maintainable, plus that functionality could have been added with a few lines of code on the object that needed it since NOBODY was going to reuse this code … ok ok I’ll stop the rant).

    So to your question. What do we do with all those classes and methods? Do we have to learn them all? Do we just learn the basics, learn about programming and then go on and invent the universe by ourselves?

    The best programmers, in my opinion, are those that have a good understanding of what needs to happen. You need to ask a lot of questions and think of the many different contingencies of how a program will operate. Some problems are complicated, but most are not. The more you learn and the more experience you have the easier it all gets. The syntax changes from language to language, even from VW to Squeak, but the concepts stay the same.

    So to answer your question. You need the skills of a software archaeologist. You need to learn to dig for functionality that was developed previously. This is a very useful skill. Instead of thinking I have to learn all these classes and methods, you should be learning how to find what you need. As Greg pointed out this is not easy, and you will need to learn the concepts well enough so that you know what words to use while searching. Once you have a good idea of what you want, then by trying out and searching through smalltalk using words that kind of make sense, you may be able to find the class and method that does it. The packages, classes, hierarchy and categories make it easier to learn some high level stuff, but method finder is really the heart of your search.

    We don’t always get it right, I have submitted some code that already existed in the library. We should try to reuse as much as possible. There is nothing worse then finding two methods that do something similar. Usually the difference is not obvious by the method name and is only a result of implementation flaws not intention. This usually results in bugs that are very hard to track down.

    You will also find that large application classes rarely get reused. Usually very specific behavior has one place in an application. If your intention is to encourage reuse then special attention needs to be paid to those components that solve general problems. These are usually buried deep in the application code. Those components need to be extracted from larger classes, polished up, and then communicated to the development team, plus other areas where this problem was solved previously should be converted to this new general method (carefully).

    So my advice is: learn to dig, you don’t have to wallow.

    Hope that helps,

    Ron Teitelbaum


  20. ron- ronnie, my man.
    not to be greedy(but are you going to eat that looking down at your lunch as i lean in) since you are a teacher i was wondering if you had a class core curriculum laying around. i have poked my head at the beginnings list and it’s not a stream of flowing ideas that take a student from place to place, it’s more of suggestions on what a random set of how to’s. i relate well to your manner of talk, (my cousin is very analytical, i have a hard time trying to get him to dumb it down a bit)
    p.s.
    i have put squeak on my machine to let you know that i am game and not about to waste your time, the layout seems to be a 180 from vw so i need to play with it some to see where a few thing are at.
    p.s.s.
    etoys is dumb and severs no purpose, i have not idea what they are thinking but it was not teaching.
    p.s.s.s.
    are you going to drink all of that(as my grabbie hand reaching over to your drink)
    love ya man stay up
    jupiejupe


  21. Hi Jupiter,

    I’m actually not a teacher. I just play one on TV.

    So no course listing.

    To continue for those that are paying attention (like Jupiter), we have Object message. As a summary an Object is an instance of a Class. We create instances by sending the message #new to the class definition. In Smalltalk we can reference the class definition by it’s name alone. So as an example try this in a workspace. (if you don’t have a workspace then click on the background in Squeak to get the world menu select >open>workspace).

    Type in the following:

    SortedCollection new.

    Now highlight it (what you typed in), right(option) click (what you highlighted) and select inspect it.

    What you get back is an instance of SortedCollection. What you are seeing is a tool called an inspector. The Inspector’s job is to show you in real terms the instance of the object that you created. It works like an advanced temporary variable. It holds your object, it shows it to you and it give you a place that you can interact with the object.

    The Inspector (the window that shows up when you select: SortedCollection new. Highlight it and inspect it) has three windows in it. The left top window is a list of instance variables. The things that aSortedCollection knows. The right top window is a value window. When you select an instance variable on the left, the contents of that variable will show up on the right. The bottom window is bound to the object so if you type in: self then highlight it and inspect it you will get back another Inspector with the same object.

    Don’t let the second inspector fool you. You only sent one #new to the Class definition so there is only one instance. What ever you do in one inspector applies to both since they are both displaying the same object.

    The bottom window can be used to send messages to the object. (A secret here is that so can the right window, since it is also bound to self. The only real difference between the right and bottom window is that if you select an instance variable change the value and then select Accept it, the right window is also bound to the instance variable and will change it.)

    So on your Inspector for SortedCollection try sending a message.

    Select (click on) the self on the Inspector (the left top instance variable window). (This causes the object to update when changes are made.) Now send the following message by typing it in, highlighting it, right click and do it (do not select accept it if you are in the right top window!).

    self add: ‘hi’.

    This message sends the method #add: to the object sortedCollection and the method #add: takes a parameter. We are sending in the string ‘hi’.

    The method responds by adding the string to the sortedCollection. Try adding other strings and notice that SortedCollection sorts the strings that are being added in.

    How do we know what messages we can send to the object SortedCollection? We can browse the code to see what methods the object understands. Select self on the left side of the Inspector right click and select browse hierarchy. You will see all the methods that an instance of SortedCollection understands.

    So back to the original point. How does Smalltalk find the class definition to send the first message #new? I hope that you have noticed that messages start with a lower case letter. Class definitions start with an Upper case letter. (there are a few exceptions).

    Smalltalk has a general lookup mechanism for finding Class definitions. Highlight SortedCollection and inspect it and you will see an Inspector on the class definition. This is the instance of the class definition that you sent the message #new too! Everything in smalltalk is anObject. We communicate with objects by sending messages! Object message.

    Understanding this concept is step 1! Any questions?

    Ron Teitelbaum
    Ron@USMedRec.com


  22. There are a number of people following this thread. Before moving on I would like to know if I’ve covered the first topic: Object message, well enough for everyone to understand. Please feel free to post a comment about your level of understanding, and if any of this is helpful.


  23. check, i just got done with the lesson. holidays and all.
    jupiejupe


  24. ready for lesson two


  25. Lesson 2: Where does my code go?

    One of the things that amaze and confound most people, when they first look at Smalltalk, is the mess on the desktop. What are all those windows!

    Browser development can be very disconcerting when you first look at it and for people that really need to have a clean desk the process can seem like it is out of control. There are a number of tools and processes that a new Smalltalk developer needs to be proficient in before they can really get comfortable with the language. One of those things is being comfortable with finding things and having lots of windows open at one time.

    Now I can’t show you my desktop so what I’ll do is give you a feeling for the tools. How they are used and why sometimes during development I have to just stop and close all the windows before I can continue!

    First there is the browser. The browser allows you to see the source code and the Class definitions that we talked about previously. Remember that there are two sides to the class definition. There is the class side and the instance side. Every browser has buttons that switch you from viewing code on the class side to viewing the code on the instance side. As a reminder class side methods are those that do not involve the instance created by sending the class definition #new. In other words if you do not reference the instance of a class then you probably should be putting your code on the class side. Also if your method affects all instances of a class then your method is probably a class method. When you are writing a method that belongs to a specific instance of a class, you will be writing your methods on the instance side.

    Back to the browser. There are a number of different types of browsers that organize the code in different ways. The main browsers you should learn are: System Browser, Package Browser, and the Hierarchy Browser. There are other Browsers available that you should also look at but since this is for beginners let’s start with these. There is not much difference between System Browser and Package Browser.

    The major difference is that the package is listed separately on the package browser in the left top window. This can make it easier to find something you are looking for. This is the browser I use most when I know what I’m looking for. You can open the package pane browser by clicking on the desk top then select open…>package pane browser.

    The system browser is the Browser that will come up when you select ctrl or option b for browse. Type in or highlight the name of a class and select ctrl-b to browse. You will see the package-category on the left top window. The Class definitions in that package in the next window, then the protocol or category names which help to divide and organize your methods in the next window and finally your method names next. Please open up the browsers and poke around. See how things are organized and get a feel for how to use the browsers.

    When the class is selected and you are on the instance side you will see the class definition and class comments. This is where we define our classes, instance variables and class comments. When you select a method on the far right window you will see the method source code. This is where we write and edit methods.

    The hierarchy browser is very important for programming and understanding how the classes themselves are organized. You can get a hierarchy browser by selecting a class, then right click on the class and select> browse hierarchy (h). We will discuss the hierarchy browser in more detail later. For now the goal is to be able to open browsers, know the difference between browsers, know where the class definition is, where to find class comments, what a package and class category is, what a method protocol or method category is and how to find the method source code.

    Let’s leave this lesson here and we can pick it back up if there are no questions.


  26. oh ron,
    alan and craig latta say hello.


  27. Hi back to both Craig and Alan.

    Ok so now that we have seen the browsers we need to know how to use them. First to create a class if you bring up the browser, select a package, without selecting a class you will see a Class definition template. It looks like this:

    Object subclass: #NameOfSubclass
    instanceVariableNames: ”
    classVariableNames: ”
    poolDictionaries: ”
    category: ‘Kernel-Methods’

    Change the class name #NameOfSubclass to some other class name, remember class definitions start with a capital letter, and right click accept the definition. You have just created your first class. Something interesting is happening here and it’s a feature of all browsers. That is when the selector changes, in this case the class name, it moves off and creates a new something. I have seen this confuse some people so it is worth pointing out.

    If you select a class and change its name then accept the new definition the system creates a new class. The new class has no methods but if you didn’t change the instance variables then they are all still there on your new class. What happened? The answer is that what you are doing with this template is actually executing a message. The job of the template above is to create or modify the class name. If the name changes you get a new class. To rename a class you need to select the rename function, or copy your class.

    This also works when you are changing methods. If you select a class and a method protocol you will get a method template. It looks like this:

    message selector and argument names
    “comment stating purpose of message”

    | temporary variable names |
    Statements

    This shows you the proper format of a method. The top line is the message that you are defining, the next line is comments about what this method does, the next line (after the blank line is where you define temporary variables (holders for values with a local scope, which means they are accessible in this method only, this is not completely accurate but this is a beginners article.), the next line is the source code for your method.

    Most people get to this template, highlight everything and delete it, then write their method from scratch. They also usually leave out the comments which in my opinion is a bad thing. Get used to writing some comments about your methods.

    Here is an example of a method.

    Number >> add1

    “return to the sender the value of the receiver increased by 1”
    ^self + 1

    The Number >> part of what I’ve written here is just to make it easier for you to understand where this method goes. What you actually put in the template is.

    add1
    “return to the sender the value of the receiver increased by 1”
    ^self + 1

    Then accept the method. This writes the new method into the class Number.

    What some other people do is write the method write over another method, since changing the selector of the method, (in our case the #add1) will write a new method. So if you wanted to make an add2 then you could change the 1 in all three places accept the method and it will create a new method for you.

    So you should have learned how to create a class, how to create a method, and that renaming is a separate process from creating something new. That if you change the selector or class name you get a new class not a changed name. Next we will talk about navigating the code and finding what you need.

    Any questions?

    Ron Teitelbaum
    Ron@USMedRec.com


  28. Hello again everyone,

    We left off talking about navigating around the image. When you are doing browser development it is very important that you can find what you need. There are a number of tools available to help you do just that.

    The first part, as I said before, it to get used to how messy browser development can be. When you use a tool too find something a new browser pops up. It doesn’t care that there is a browser sitting on your desktop already. There are some ways to organize the madness. There are tools that let you see all the windows and let you pick the one you want (world menu -> windows … -> find window). This can be very useful if you lost something in your pile.

    We already talked about what a browser is, but as a review, a browser shows you the content of the class definition. It’s the place that you find all the source code. The class side of the browser shows you things that affect all instances of a class, or do things like create instances of something (remember #new). The instance methods affect each instance separately.

    You need to learn what an inspector is also. An inspector is the thing that shows you an instance of your class. (It can also show you the class definition information but for now think of it as a way to look around in an instance. We use a browser for looking around a class definition).

    So try this.

    In a workspace type the following. (To open a workspace do: world menu -> open … -> workspace)

    Date today.

    One more review. Date is the Object, in this case notice that it is capitalized. You should think to yourself Capitalized, that must be a class. You would be right!! Bonus points for you!! Now if Date is a class definition, then today must be a class side method!! Again you would be right, what do they win Johnny O!!

    Ok so if #today is a class side method then it probably returns an instance of Date. How can we see that instance? In an inspector! So highlight the statement and right click > inspect it. What you should see is an inspector with an instance of date.

    There are a number of places where you will be able to bring up an inspector, there are inspectors embedded into the debugger, and like you just saw you can play with your code on a workspace. Expect to have a few open.

    Ok so now we can see an instance.

    You should also be able to find methods that you want to use. For example say I want to get the day of the week from my birthday. How are we going to do that? Well we know that we will use a date. My birth date. How do we create a date?

    Well to get an instance of date we should go and look at the class date and figure out how we create an instance. If you type in Date in the workspace then highlight it and hit

    ctrl-B (on some systems it is alt-B)

    The browser for Date will come up. You could also open up the browser of your choice and then right click on the package window and do find class. Type in Date and enter. One way or another get yourself to the Date class in a browser. Now let’s take a look, remember to look on the class side.

    We find a method #fromString: . We that’s good cause we know how to type a string. (In Smalltalk a string is anything surrounded by single quotes). Let’s give it a try.

    My birth date is: ‘1/1/1901’. I’m really really old! Ok so it’s not. You know I’m also the Squeak Cryptography Team Leader, so I know better then to give out personal information! Ok so let’s find out instead what day of the week it was on Jan first 1901.

    So to create an instance of Date we will use the #fromString: method. So

    Date fromString: ‘1/1/1901’.

    Now we know that somewhere in the code the class date is sent the method #new. Ok in this class it is sent the method #basicNew. For very advanced beginners or highly motivated Smalltalkers to be I’m going to leave it to you to find it! It is actually in a very interesting place and it’s very hard to find! For everyone else, take my word for it.

    What you get back is an inspector with (after you highlight and inspect it) with the date in it. So now what day of the week is it? You could write a method yourself but that would be pretty difficult. Well this is Smalltalk. Smalltalk has been around for a long time and the class library is very comprehensive. Some say too much so, which makes things hard to find.

    In our case we have some options. We need to find a method, on the instance side for day of week. Why the instance side? Because we want to send the method to the instance so that we can ask it, “Date what day of the week are you?”. We could go to the instance side of the browser and look for it.

    We could also open up the method finder (world menu->open … -> method finder). On the method finder the top left window is where you type in. Make some guesses about the words you would expect to see in a method name. Then press enter. Under that is the window that shows you all the methods that have what you typed in somewhere in the selector of the method. The right top window shows you the classes that implement the method you are trying to find.

    On the method finder type in: week. Then press enter. Underneath notice that we have the method #dayOfWeekName. That sounds good so highlight that. On the right window notice that dayOfWeekName is not implemented on Date. (Actually it is but we haven’t learned yet how to tell that). If you keep looking down you will find #weekday. If you click on that you will see Date weekday. Click on that and another browser will open up. (I warned you, you will have plenty of them). Notice the method actually uses #dayOfWeekName, hmmmmmm how does it do that?? (Stay tuned and you will find out).

    Ok so now that we know what method we want to use, go back to your inspector of the date. In the right window type in: self weekday. The keyword self is bound to the instance of date because you are typing self in the inspector window. We can talk more about self as we go but for now self is how we reference the instance in the inspector. So highlight your code and select print it. What do you see?

    Ok so you should have learned what a class definition is (AGAIN). What an instance is. How to see an instance in an inspector. How to send messages to your instance using self. How to find methods using the method finder or hunt and peck. That it’s not always easy to find #new! And that my birth date is not 1/1/1901!

    Next we will learn about senders and implementers of methods.

    Ron Teitelbaum
    http://www.usmedrec.com


  29. Once again I encourage you to participate. If you have any questions now is a good time to ask.

    Ron


  30. Hello Everyone,

    What is an implementer, what is a sender, and what is a class reference? To be able to get around in Smalltalk you need to be able to understand these concepts.

    Another review. Everything in Smalltalk is Object message. You have either a class definition or an instance of a class (your object) and you send it messages.

    Think of your object as a real thing. We used to try this in a group of people. Everyone was handed an object note card. On the card was everything the object could do. Then we would start the messages by having someone ask a question from their card. If the person could answer the question they did and if they needed to ask someone else, they looked to see if they knew the other person and if they did they asked them. To be able to talk to other objects they needed to be attached to the other objects by instance variables, or have access to some other form of instance lookup.

    Messages can include access to instance variables which are direct links to other objects. Instance variables are what the instance knows. It was fun to bounce around messages, and when we got stuck it was fun to try and figure out who in the room should answer the question.

    One of the most important aspects of browser development is figuring out this question. Where does my code go? If you pick the wrong object you will find that to answer a question you are sending in a lot of variables or you are storing a lot of information about something else. Many times the method is really long and just feels plan wrong. When you move your code to the right place it just seems to work the way you would expect it too.

    For example: (Warning I’m making this up as I go so please excuse any errors).

    Object subclass: DogToy

    Object subclass: Squeaker

    Ok so Dog sends the message #bite to an instance of DogToy

    aDogToy := DogToy new.
    aDog := Dog new.

    aDog bite: aDogToy.

    Now you should be saying, “Wait a minute. The message is being sent to aDog, not to the toy”. You are right. So we double dispatch the message back to the toy by implementing the message #byte: on Dog.

    Dog>>bite: aSomething
    “the receiver masticates the argument aSomething”
    aSomething bite

    ok so now the toy is sent the message #bite.

    What happens now? Well we want the squeaker to squeak.

    How about:

    DogToy
    instanceVariableNames: ‘squeaker’

    We need to set the instance variable to an instance of a squeaker. When new is sent to any object the message that is really sent in the superclass (if it is not overridden) is

    #new
    ^self basicNew initialize.

    So if we add a method on the instance side of our class a method called initialize then we can set our instance variables to some initial values.

    So

    DogToy>>initialize
    super initialize.
    self squeaker: Squeaker new.

    Now when the toy is created it has a new squeaker in its instance variable.

    So now we can bite it.

    DogToy>>bite
    self squeaker bite.

    And on the Squeaker we implement bite.

    Squeaker>>bite
    “play a squeaking sound”
    self squeak.

    Let’s assume that our squeak method makes a squeaking sound in our application.

    Well so far so good. I don’t know about you but my dog toys only get so many squeaks! So what if we wanted to keep track of the damage done to the squeaker? What do we do?

    Hmmmm! Ok let’s keep track of it on the toy.

    This is where we start to go wrong! Watch what happens.

    DogToy
    instanceVariableNames: ‘squeaker squeakCount’

    DogToy >> initialize
    super initialize.
    self squeaker: Squeaker new.
    self squeakCount: 0.

    DogToy class >> maxSqueakCount
    “return the number of squeak that this dog toy can squeak before the squeaker runs out!”
    ^100

    DogToy >> bite
    “send bite to squeaker unless we have exceeded our maxSqueakCount”
    self squeakCount: self squeakCount + 1.
    self squakCount > self class maxSqueakCount ifFalse: [
    self squeaker bite
    ].

    Ok well at first glance this looks ok but, notice a few things. First, what if our dogToy didn’t have a squeaker do we need to track all this information anyway? What if we make new squeakers that last longer, what if we want to change the bite so that larger dogs bite harder? Shouldn’t the properties of the squeaker be managed on the squeaker itself? Just because the squeaker doesn’t make sound does it me that the dog doesn’t bite it?

    DogToy subclass: DogToySqueaky
    instanceVariableNames: ‘squeaker’

    DogToySqueaky >> bite
    “send a bite to the squeaker”
    self squeaker bite

    Object subclass: Squeaker
    instanceVariableNames: ‘squeakCount’

    Squeaker subclass: SqueakerMax
    Squeaker subclass: SqueakerEconomy

    SqueakerMax class >> maxSqueakCount

    “return the number of squeak that this dog toy can squeak before the squeaker runs out!”
    ^1000

    Now we can build some toys.

    SqueakerMax class >> pricePremium

    “return to the sender a multiple to be applied to the base price”
    ^0.1 “10% Premium”

    SqueakerEconomy class >> pricePremium
    “return to the sender a multiple to be applied to the base price”
    ^0.01 “1% Premium”

    We remove the setting of the squeaker from the initialize method and then create our new toys.

    DogToy class >> newMax
    “return a new max toy”
    ^self new
    squeaker: SqueakerMax new;
    yourself.

    DogToy class >> newEconomy
    “return a new economy toy”
    ^self new
    squeaker: SqueakerEconomy new;
    yourself.

    Ok so now the squeakers can handle themselves.

    Squeaker >> bite
    “receive bite”
    self addToSqueakCount.
    self squeak.

    Squeaker >> addToSqueakCount
    “add to the count of squeak”
    self squeakCount := self squeakCount + 1.

    Squeaker >> squeak
    “squeak if you can”
    self canSqueak ifTrue: [
    self makeSqueakSound
    ].

    Squeaker >> canSqueak
    ^self squeakCount < self class maxSqueakCount

    Ok Ok I know what you are thinking. There is a lot of stuff there that is fun but you didn’t explain everything! Like how come you are writing methods on Squeaker when you only have toys with instances of SqueakerMax or SqueakerEconomy? What’s this yourself stuff? Why did you do super initialize? What’s a double dispatch? Why didn’t you implement maxSqueakCount on SqueakerEcomony? You will learn about most of this in lesson 3. I will answer these questions now but only if one of you asks it! So this is your chance to get involved.

    What does this have to do with senders and implementers and class references? Plenty but you will have to wait till next post to find out.

    Ron Teitelbaum
    President / Principal Software Engineer
    US Medical Record Specialists
    http://www.usmedrec.com


  31. It would seem that interest in this thread has diminished, I will continue monitoring comments. If you happen to run into this thread and have questions or would like to have me continue with lesson 2 or move onto lesson 3 please let me know. Baring new comments we will stop here.

    Thanks everyone that participated, and thank you to the number of people that followed this thread.

    -Ron

  32. Paul Bennett Says:

    Hi Ron,

    The interest in this thread just picked up again! 🙂

    First off – thanks for your efforts here. I’m a programming newbie lost in the web of information trying to learn Smalltalk on Squeak DIY style. So I feel the pain that Greg expressed. You know – these tutorials could be turned into movies! Hint hint!

    Getting back to Lesson 2 ( 2007.01.08) in the 4 para. you opened a can of worms for me. You started talking about putting methods on the class side or on the instance side before jumping back into the browser. But it was too late – I already had questions.

    First one was .. What? Could you explain this more – perhaps using SortedCollection as an example? Trying to figure out what you meant I went back to look at the SortedCollection class and I see two class methods… #new & #sortBlock. I understand the purpose of #new as that is what sets up the instance of sortedCollection. But when I dug a little deeper I had no idea what I was looking at. I thought most #new methods simply referenced ^super new. I just fell deeper into the rabbit hole.

    Thanks
    Paul

  33. Paul Bennett Says:

    Next Question…

    In you post of 2007.01.10 you use the notation… Number >>. Could you expand on this a bit? I’ve seen it used elsewhere so I am suspecting it is a standard way to reference something – but in your example I don’t understand it’s usage.

    Are your saying this is a Number class? Or only numbers are accepted?

    Thanks
    Paul

  34. Paul Bennett Says:

    Re: your post 2007.01.19…

    As a motivated Smalltalker I – think – I located the #basicNew method. I searched for it with the world>search method tool. It is in the Behavior class.

    So I have two questions…
    1) I clicked on hierarchy to see if Date inherited this method, and it is not part of the Behavior hierarchy. So how does it know to execute this method?

    2) There are two #basicNew methods. One ending in : and one not. Am I correct in presuming a method ending in : is accessable outside of the class and the one NOT ending in : is an internal message? I tried reading the methods to understand them but I’m not quite “there” yet.

    Thanks
    Paul


  35. Hi Paul,

    Welcome to the Ah Ha!! thread. I’ve been thinking about separating this thread into articles, but haven’t had the time to do it. I hope that it helps.

    To your first question; What’s up with class side methods.

    Before answering think of self. No you are not looking for inner peace (well I guess you might be) instead think of #self in smalltalk. In smalltalk #self is an instance of a Class. A Class is an object definition, it’s like a mold that we use to stamp out instances of something. It defines what the instance remembers (instance variables) and what it does, or how it responds to messages (instance methods).

    Ok so this gets confusing so bear with me. The keyword #self on the class side refers to the class definition so you will find self on both sides the class side and the instance side but they give you very different results. #self on the class side returns the Class definition where #self on the instance side returns an instance of the class that you created in your program with some form of #new.

    Ok so I want to create a sculpture. I carve the masterpiece out of wood. I then pack the wood in sand and compact it so that I can create a mold. The mold is an example of our class definition. But the mold doesn’t do anything by itself so you need to add behavior to the mold. That behavior concerns the mold not the sculpture that comes out of it. In smalltalk we put that behavior on the class side.

    So you may do something like: #cleanMold, #lubricate, #stabilize, #fillWithMoltenBrass … The last one is really cool, there’s nothing like seeing hot molten metal fill a mold. It’s cool the way it fills up and runs out of the escape holes.

    Anyway I hope you get the idea that these are all behaviors that affect the mold not the statue. They are Class methods.

    Now once we call #new, which creates an instance of your class you get an instance. This is like getting a statue from the mold above. The instance is special in that there is only one unique statue. It may need to be cleaned and buffed, if it is older then the other statues, or has been in places that other statues have not then it can take on other properties. You only have as many statues as you call #new (or poor new ones).

    You need to hold on to your statue or the sweeper in your foundry comes through and cleans them up and throws them away. In Smalltalk we have something called a garbage collector which does the same thing. This keeps your image from being overwhelmed with unused instances. You hold onto instances in a number of ways, the most common is in an instance variable on another object but this is a different question.

    You can sometimes tell you are putting your method in the wrong place when the method you are writing doesn’t include the method #self. There are a lot of reasons to write methods like this but if they don’t directly affect the statue (have the word #self) then they are probably class side methods. You can access the class side methods from the instance by sending the message: self class someClassSideMethodName. The class does not usually call instances. This would be like the mold keeping track of all statues, seems odd.

    Ok but we should mention that if there is something that needs to happen to all instances of a class then you can get all the instances by sending the message from the Class: #allInstances. You will get back all of the instances you created that have not been garbage collected.

    So I hope that explains Class and Instance side. For SortedCollection notice that SortedCollection is a subclass of OrderedCollection. This is an example of inheritance.

    When you see:

    SortedCollection >> new: anInteger
    (super new: anInteger) …

    what this means is that the method #new: is not written on the class SortedCollection but on the superClass or somewhere up the line of superclasses in the class hierarchy. To find what new: is doing you need to move up the classes. (Browse the hierarchy to see the classes that make up SortedCollection)

    Happy Coding!

    Ron Teitelbaum
    President / Principal Software Engineer
    US Medical Record Specialists
    http://www.usmedrec.com


  36. Hi Again Paul,

    You asked if I could explain how I used Number. This notation is very important so let’s spend a minute on it.

    Number >> add1

    This means that there is a class named Number in the system. You can find this by going to a browser and right click and select: find class… in the class list window.

    You could also type in the class name Number highlight it and press ctrl-b or alt-b or function-b depending on the image, your settings, or your platform.

    This will bring up a browser on the class Number.

    Class names are Capitalized. If I separate the class with >> what I mean is a method on the instance side of the class. So

    Number >> add1

    means on the class Number on the instance side a method named #add1.

    If I was talking about a class method I would write

    Number class >> add1

    which means there is a class Number on the class side a method named #add1.

    I will also indicate a method is a method when typing in a sentence by putting the # symbol on it.

    So in that example I was suggesting that you practice creating a method #add1 by putting it on Number.

    Number is a superclass of all the numerical constructs of Smalltalk, so no matter what number you use, Float, SmallInteger, LargePositiveInteger … it will still work since each of these classes will have access to method written on a superclass.

    Hope that helps!

    -Ron


  37. Hello again Paul,

    To answer your questions about basicNew. You did good!!

    Remember that there is a difference between Class and Instance? Well there is a bit of a problem with that distinction. If you are a real newbie and are already overwhelmed with this thread, skip this answer, come back when it all starts to go Ah Ha!! later.

    In Smalltalk everything is a object. When we say Object Oriented we are not fooling around! Look at a string. A string is a collection of Characters. Well here’s the answer. Shhh don’t tell anyone. A Class definition is an instance of Class!!! Have a look at the hierarchy of Class. That should answer you question about basicNew and Date. The class definition inherits the method basicNew from Behavior.

    Now the difference between basicNew and basicNew: is the type of class that it creates. One is a basic class the other is a variable subclass. So a collection would call basicNew: anInteger to set how many indexable ivars it should have.

    Very nice questions!

    -Ron

  38. Paul Bennett Says:

    Ron, thanks for the reponses – and yes, splitting this into articles would be great. And perhaps the documentation team can use this over at the Squeak Wiki?

    Ok – back to class.
    Class V Instance methods
    Your statue mold example helped me visualise the differences. But I still don’t think I’m getting it as further up on 2007.01.08 you say “if your method affects all instances of a class then your method is probably a class method”. And at that point I THOUGHT I got it. But now I’m wondering why in the Date example of 2007.01.18 you are passing data to the Class. I thought that in OO you created instances of classes to handle data. I’m not sure if I’m confusing different subjects here but it feels like they are related and I think I’m missing something key – but I’m having trouble putting my finger on it.
    Next on this subject you mention a reason for writing Class side methods and I’ll write it another way here to see if I have understood it: Class side methods are available to all instances. If you change a Class side method it effects all instances that call on that method. Instance side methods live with the instance until it gets garbage collected – so changing an Instance side method does NOT effect current live instances, it will only effect instances created from that point on. …?

    Date hierarchy
    I looked at the hierarchy of Class – and I see what you mean. Are you saying that there are two hierarchies at work? One which is a direct relationship created by design (EG: a decision was made to subclass Timespan to create Date) and a second one that is there because ALL classes are really a “hidden” subclass of Class? Are there any more of these not-so-obvious hierarchies?

    : v no :
    So a method with no : is a basic class and a method with : is a variable subclass. Yes – I am quite lost with this. It sounds like something I’ll learn further along, however, this sounds like “typing” a class and I thought Smalltalk was un-typed. Such that I would expect and class to be either variale or fixed.

    I trust I’m not being frustrating!
    Paul


  39. Hi Paul,

    Class vs. Instance Side method.

    Think of talking to a class definition. What kinds of things would you ask the definition? One thing you might say is make me an instance of the class you define. You might also say make me an instance with these things in it. If you think of it that way it makes sense to pass things to the class that will be used for creating an instance.

    For example.

    LibraryCard for: aPerson

    Let’s step this through one piece at a time. LibraryCard is a class definition. It is not an instance of a class. If you highlight the name LibraryCard and you select alt-b (or ctrl or func) to browse the class the class definition comes up. Notice also that the class is Capitalized. This is a very good way of determining the difference between an Class definition and an instance.

    In this case the #for: is a class side method. It takes an argument which is an instance of class Person. Notice that aPerson begins in lowercase. (There is no class Person in your system you would have to create one to actually make this work)

    So why would we be sending an instance of person into the class side of Library card? The answer is we want to get an instance back. We don’t have the instance and we don’t know if the instance exists. So what things might we do?

    How about we check to see if aPerson already has a card. We could check to see if the card in the system is expired, in which case we need to issue a new one. We could see if the old card was revoked or if there are fees due, in which case we could refuse to issue a new one until the fees are paid. We could find out that this person never had a card in which case we will just issue a new one.

    so

    LibraryCard class >> for: aPerson
    “check for existing card. Return a new card if needed and allowable”
    needsNewCard := false.
    oldCard := self selectFor: aPerson.
    oldCard ifNil: [^self newFor: aPerson].
    oldCard isExpired ifTrue: [
    needsNewCard := true
    ].
    oldCard isRevoked ifTrue: [
    ((aPerson balanceDueOn: oldCard) > 0)
    ifTrue: [^RevokedCard signal: ‘Balance Due on Revoked Card’]
    ifFalse: [needsNewCard := true].
    ].
    needsNewCard ifTrue: [^self newFor: aPerson].
    ^oldCard

    LibraryCard class >> newFor: aPerson
    “return to sender an instance for aPerson, should be called from LibraryCard class >> for: only”
    ^self new
    person: aPerson;
    yourself

    So you can see that we used a method to create an instance and we set the person on the instance we created in #newFor: we also used the person passed to the class side to query for existing cards and we raised an error of the customer is severely past due and had their card revoked.

    You can see that even though we are passing data to the class side we are using that data to query and then eventually to fill the instance that we created.

    We also had a method that does affect all instance in that we check all instances in the query for aPerson. It doesn’t change any of the instances. We could come up with reasons to change all or some instances. Say when we are revoking cards.

    LibraryCard class >> revokeSeverlyPastDueCards
    “revoke all cards that are severly past due”
    self allInstances do: [:aCard |
    aCard isSeverlyPastDue ifTrue: [
    aCard revoke
    ]
    ].

    You can see that since we want to check all cards we really need a class side method.

    Instance side methods are thing things that instances know or can do. If you change the methods on the instance side these changes effect all instances, those already created and those that will be created in the future.

    for example

    LibraryCard >> revoke
    “set the revoked date on the card”
    self revokedDate: Date today.

    Now we want to change something. Instead of just setting a date we also want to store the balance due when the card was revoked.

    LibraryCard >> revoke
    “set the revokedDate and the balance due on the card”
    self revokedDate: Date today.
    self balanceDueWhenRevoked: (self person balanceDueOn: self).

    Now we have the balance due when it was revoked and we can add more rules about how the card works in the future. (For example maybe we don’t issue new cards to people that had huge balances in the past or maybe we forgive smaller revoked balances automatically).

    Does this happen automatically for all created instances? No, not unless we call this new method again. Notice that if we do we change the revoked date on already revoked instances to today so maybe we don’t want to do that. Also if the customer paid some of the balance due then the new data would be wrong. So in these cases it is best not to just run this method again on all revoked cards but instead to write a new upgrade method that calculates the balance at the time of the revocation and sets it.

    But all new cards that are revoked will have this new data. So you are right and wrong. It does effect all new instances, but it effects all old ones too if for any reason this method is called on those old instances.

    I’ll separate your next question into the next post.

    Happy coding,

    Ron Teitelbaum
    President / Principal Software Engineer
    US Medical Record Specialists
    http://www.USMedRec.com


  40. Hi Paul,

    Your question about hierarchy is difficult. You will find very interesting relationships in a lot of places depending on what code is loaded. Some things are not very obvious. The newest wrinkle is Traits. Traits are a way for Smalltalk to implement multiple inheritance. You can compose some behavior and share that behavior with different classes. This makes things harder to follow.

    There are also programming patterns in smalltalk that allow for interesting behavior. One is a wrapper. Instead of having the method look up the hierarchy for its implementation a wrapper passes the method down to instances that it holds onto. Some complicated wrappers can follow some interesting rules as to which instance it sends methods too.

    There is also a programming pattern called roles. This is like a wrapper but it is a more general implementation. A role is a way of adding behavior to an instance based on some criteria.

    For example lets say you have a person. That person wants to prescribe a medication.

    So we need to check the roles of a person to find out if this is ok or not.

    We can add roles to person to accomplish this.

    First we send the message #canPrescribe: aMedication.

    We pass the method to the roles and look for an answer of true. In this case we define success as any yes. This should not be taken lightly since how you handle having multiple roles responding to methods can be very complicated.

    So we define roles, say a Doctor role, a Nurse role, a Physician Assistant, a LVN …

    We can now implement our method on all of the roles and then have each one respond in an appropriate manner. For example only Doctors can prescribe a C2 med, aPhysician Assistant can prescribe some meds but only in some states …

    We change aPerson by adding roles for example aPerson addDoctorRole. This adds an instance of Doctor to the role ivar in aPerson.

    These programming patterns can be hard to spot, which makes it hard to figure out who is implementing the method you are calling.

    Another issue that comes up frequently is performed methods. I’ve seen some pretty funky code written that concatenates strings to build methods and then lets the compiler perform the method. This can make things really difficult because now your methods have no senders. Tracing them can be very difficult.

    The lesson here is never assume that because a method has no senders it isn’t used. It helps sometimes to write a method that calls these performed methods just to add a placeholder: something like,

    MyClass>>performedMethods
    self error: ‘Do not use this method, and do not delete this method’.
    self myPerformedMethod.

    Now it has senders. What a hack!!

    Hope that answers your question.

    -Ron


  41. Hi Paul,

    Methods in smalltalk consist of keywords. You can have multiple keywords if the method you are sending has parameters. The : in a method is an indication that a parameter is being sent.

    MyTalkingClass >> sayHello
    “print a greeting to the transcript”
    Transcript cr; show: ‘Hi there, nice to meet you’.

    MyTalkingClass >> sayHelloTo: aName
    “print a greeting for aName to the transcript”
    Trancript cr; show: ‘Hi ‘, aName, ‘! It is very nice to meet you.’.

    MyTalkingClass >> sayHelloTo: firstName lastName: lastName
    “print a greeting for name supplied to the transcript”
    Transcript cr; show: ‘Hi Mr./Ms. ‘, lastName, ‘! It is very nice to meet you. Can I call you ‘, firstName, ‘?’.

    The first method is a single keyword with no parameters. The second method is a single keyword with one parameter. The third method is a double keyword, double parameter method.

    Does that help?

    -Ron


  42. Nice article, haven’t read the whole thread yet but for people who want a basic, from-the-ground-up introduction to smalltalk syntax, the new Dolphin Smalltalk free download has a very nice tutorial. Most of it would apply to Squeak as well.

  43. Paul Bennett Says:

    Hi Ron,

    The past week I’ve been completing the book “Squeak – A quick Trip to Objectland” and although it’s brought me no closer to writing code it did help with understanding the Squeak environment.

    Re:Class vs. Instance Side method.
    Thanks. The LibraryCard example seems to have made it click for me – at least at the philosophical level. Your example here was a small ah-ha for me.

    Re: Hierarchies
    Interesting – so Traits allows multiple parent classes. That sounds like an excellent arguement for people commenting their code! And I understand the complexity of Roles – again at a philosophical level. I think that I’ll get it more when I actually get my hands dirty coding.

    Re: : v no : (or “Parameters”)
    Yes – that explanation totally clears it up for me.

    Thanks
    Paul


  44. Hi Paul,

    You are welcome! Have fun coding!! Thanks for getting the thread moving again. If anyone else wants to get involved, now is a good time to speak up!

    Ron


  45. Hello Everyone,

    Just to let you know I’m still watching this post. There were quite a number of hits this month and last month so I know some people are still reading it. I suppose the problem is that the comments are way to long for most people to get all the way down to here. If you do get to here and have a question, feel free!

    Ron


Leave a Reply to jupiter lovejoy Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: