• Aucun résultat trouvé

Adding a New Method

Dans le document TEKTRONIX SMALLTALK (Page 44-48)

In this tutorial, you will add a new method to class String. This method will allow it to reverse the case of any alphabetic characters in a string. You will first open a workspace to write and test your code. After the code is debugged to your satisfaction, you will then install it in the Smalltalk system using the System Browser.

Works paces are a good place to test new code, for several reasons.

• You can execute expressions one at a time, testing your new code incrementally.

• Temporary variables need not be explicitly declared, but they persist for the lifetime of the workspace and can be inspected after the code has been executed.

• You do not need to decide where, in the Smalltalk hierarchy, to place your new method until you have finished its design.

When you add code to the System Browser, you will discover a feature implemented to protect you from losing work. When you are adding text to the text pane, until the text is accepted you

Smalltalk Concepts

are unable to move around in the System Browser. If you try, the text pane flashes at you, and a notifier window pops up to warn you of loss of work if you change the view within the pane.

Therefore, if you need to see other system code as you work, use the middle button menu command spawn to spawn another browser.

If you wish to see other system code as you work, some useful template expressions are available in the System Workspace. The expression Smalltalk browseAlllmplementorsOf:

#messageSelector under the heading Inquiry is particularly useful. Select the word messageSelector and replace it with any message selector you wish to inquire about. Leave the

# sign, however. Then select the entire expression and execute do it. A new browser pops up, with two panes. The top pane contains a list of all objects that implement the message selector in question. If you select one of the lines in the top pane, the bottom pane fills with the method implemented by that object when it receives that message.

If you wish to take a break during this tutorial, or clean up your display, you can use the right button mouse menu to retitle your workspace and collapse it. Choose title and enter a new title in the window that pops up. Then choose collapse, and move the title tab out of the way for the moment. When you wish to resume your work, select the title tab and execute frame from the right button menu to get your workspace back again.

1. Open a workspace.

2. Type the following code in the workspace:

oldString f-- 'JFMamJJasonD'.

newString f-- String new: oldString size.

1 to: oldString size do:

[:index

I

aCharacter f-- oldString at: index.

aCharacter isLowercase

if True: [newString at: index put: aCharacter asUppercase]

if False: [newString at: index put: aCharacter asLowercase]].

This is the algorithm that performs the case reversal on the characters of the string. A line-by-line explanation follows.

oldString f-- 'JFMamJJasonD'.

This expression creates a string to experiment with. Type in any string you like. Be sure to enclose it within single quotation marks. It is assigned by the leftward arrow to the temporary variable oldString.

newString f-- String new: oldString size.

This expression creates a new instance of class String. It is the same size as the original string. It is assigned by the leftward arrow to the temporary variable newString.

1 to: oldString size do:

This is the beginning of an iteration loop. The loop index starts at 1 and continues until it reaches the size of the old string.

The receiver of the message to:do: is an integer. Integers understand this message because they are subclasses of Number, from which they inherit the method. If you wish to examine the code for the message to:do: in Number, go to the System Browser, select Numeric-Numbers in the class category pane, and Number in the class pane. In the bottom of the class pane, you see the words class and instance. If you select class, the two rightmost panes allow you to access messages sent to the class only. If you select instance, the two

rightmost panes allow you to select messages sent to instances of the class. Select instance, and select intervals in the message protocol pane. Select to:do: in the message selector pane and look at the code that appears in the text pane. This code evaluates the following block for the interval specified.

[:index

I

The square bracket indicates the start of a block. This block needs a block variable, an index, to go through the loop. The index is not needed after the block is executed, however, so the variable need not be declared at the beginning of the method.

aCharacter: oldString at: index.

At this point, we need another temporary variable, aCharacter, to hold each character of the string as we execute the loop.

aCharacter isLowercase if True: []

if False: [ ]

isLowercase is a message that all instances of class Character understand. The statement evaluates to a Boolean true or false. ifTrue:ifFalse: is a message which these Boolean objects understand. It requires blocks as arguments. The appropriate block is executed, depending on whether the character at that index is upper- or lowercase.

ifTrue: [newString at: index put: aCharacter asUppercase]

if False: [newString at: index put: aCharacter asLowercasell.

These lines perform the case reversal. If the character is lowercase, the corresponding element of the new string is made uppercase, and vice-versa. All instances of class Character understand the messages asUppercase and asLowercase. All instances of the class String understand the message at: put:. If you want to see the code for this message, look for it in the System Browser under the category Collections-Text, and the class String.

The second line also ends, with the second closing square bracket, the block that started after 1 to: oldString size do:.

In the System Browser, examine the methods for the messages being sent in this example until you feel comfortable with them.

3. Now test the new code. Select the entire set of expressions and execute do it.

4. If you received any error messages as you performed the last step, the system will draw your attention to the part of the code where execution was interrupted. Choose the abort command, and check to see that you have typed in the colons and periods as they appear in the code above. Then try again.

5. Type newString, select it, and execute print it to see the value stored in newString. The results of the print it command appear, selected, in your workspace. (New text appears selected to make it easy for you to cut, to clean up your workspace.)

The new string reverses the case of the alphabetic characters in your old string.

Nonalphabetic characters remain unchanged. If you look in the System Browser at the methods that implement the messages asUppercase and asLowercase, you see why.

6. Try your new code on as many strings as you wish. When you are satisfied that the code works as it should, you are ready to add the new method to the system. This is done in the System Browser.

Smalltalk Concepts

7. Keeping your workspace open, activate the System Browser.

8. In the Class Category pane, the leftmost pane of the System Browser, choose the category Collections-Text.

9. In the class pane, choose the class String.

10. Select instance in the bottom of the class pane.

11. In the message protocol pane, bring up the middle button menu. It gives you the opportunity to add a new protocol. Execute add protocol.

12. A fill-in-the-blank window pops up. Enter the new protocol name reversing case. The text pane below now fills with a code template for you to edit.

13. In the bottom text pane, select message selector and argument names and replace it with the name of your new message selector - in this case, type asReverseCase. For this method, which has a unary selector, no argument names are required.

14. Select the string comment stating purpose of message. If you double-click the left mouse button between the opening quotation mark and the first character (or between the last character and the closing quotation mark), you can replace the entire sentence, but leave the quotes. Type: Answer a string whose characters reverse the case of the receiver.

15. Select the words temporary variable names between the vertical bars. Small talk code encloses temporary variable names in this way, with one or more spaces between each variable. In the algorithm you just tested in the workspace, there were two temporary variables: newString and aCharacter. (They did not need to be specifically declared in the workspace, but they must be now that the code is being added to the system.) Type the two temporary variable names.

16. Now select the word statements and cut it. Here is where you can copy the algorithm from your workspace, but you will have to make a few changes.

17. Go back to your workspace, and select all the text in it. Choose copy from the middle button menu.

18. Go back to the text pane in the System Browser. Choose paste from the middle button menu. Paste the text after the temporary variable declarations.

19. Delete the line that assigns a string to the variable oldString. The method you are now completing is used when the message asReverseCase is sent to any string. The receiver of the message takes the place of the variable oldString.

20. In Smalltalk, the receiver of a message can be referred to within a method by using the pseudovariable self. Replace the remaining three incidences of oldString with self.

21. Put the upward arrow

i

before the last line, the line that says newString. You are specifying that your method return the value of the va"riable newString. An expression that returns a value must always be the last expression in the method or block, and must not be followed with a period. The last line now reads:

i

newString

22. From the text pane in the System Browser, execute the middle button menu command accept. When you do this, several things happen.

• The compiler evaluates the new code.

• Your new message selector asReverseCase appears in the message pane.

• Your method is now a part of the Small talk system. No distinction is made between code you have added and code that was already in the system.

• Any new instance of the System Browser you create from now on will include the new method.

If you wish to modify the method, make the desired changes and execute accept again.

You may repeat this process as many times as you require.

23. Go back to the workspace (or make a new workspace) and type a new string. Be sure to enclose it in single quotes.

24. Now send it the message asReverseCase. For example, type:

'i LIKE sMALL TALK: asReverseCase

25. Select the expression you have just typed and execute print it. The new string appears, selected, in your workspace. Try it with as many strings as you wish.

26. If you save your image now, the new method is permanently added to it. If you do not want to add this new method to your image, quit now, without saving your work.

Dans le document TEKTRONIX SMALLTALK (Page 44-48)

Documents relatifs