232
1 REALbasic Curriculum REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic . . . . . . . . . . . . . . . . . . 11 Lesson 2: Expressions, Assignments & Types. . . . . . . . . . . . . 11 Lesson 3: Conditionals and the Debugger . . . . . . . . . . . . . 11 Lesson 4: Variables and Loops . . . . . . . . . . . . . . . . . . . 12 Lesson 5: Modules, Methods and Recursion . . . . . . . . . . . . . 12 Lesson 6: Arrays & Strings . . . . . . . . . . . . . . . . . . . . . 12 Lesson 7: Algorithms . . . . . . . . . . . . . . . . . . . . . . . 12 Lesson 8: Abstract Data Types . . . . . . . . . . . . . . . . . . . 12 Lesson 9: Polymorphism . . . . . . . . . . . . . . . . . . . . . 12 Lesson 10: Eliza . . . . . . . . . . . . . . . . . . . . . . . . . 12 Lesson 11: Events & Controls . . . . . . . . . . . . . . . . . . . 12 Lesson 12: Interfaces . . . . . . . . . . . . . . . . . . . . . . . 12 Lesson 13: Bubble Sort . . . . . . . . . . . . . . . . . . . . . . 13 Lesson 14: Insertion Sort . . . . . . . . . . . . . . . . . . . . . 13 Lesson 15: Refining the Insertion Sort . . . . . . . . . . . . . . . 13 Lesson 16: Quicksort . . . . . . . . . . . . . . . . . . . . . . . 13 Lesson 17: Exceptions, Constructors, Overloading . . . . . . . . . . 13 Lesson 18: File Enumerator . . . . . . . . . . . . . . . . . . . . 13 Lesson 19: Data Structures . . . . . . . . . . . . . . . . . . . . 13 Lesson 20: File Enumerator 2 . . . . . . . . . . . . . . . . . . . 14 Lesson 21: Hashing . . . . . . . . . . . . . . . . . . . . . . . . 14 Lesson 22 (Optional): Cyclic Redundancy Check . . . . . . . . . . . 14 Lesson 23: RPN Calculator Example . . . . . . . . . . . . . . . . 14 Lesson 24: Programmable RPN Calculator Example . . . . . . . . . 14 Lesson 25: Graphics I . . . . . . . . . . . . . . . . . . . . . . . 14 Lesson 26: Communications . . . . . . . . . . . . . . . . . . . . 14 Lesson 27: Simulation & Animation . . . . . . . . . . . . . . . . 15

s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

  • Upload
    phamnhi

  • View
    225

  • Download
    3

Embed Size (px)

Citation preview

Page 1: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

REALbasic Curriculum Project Contents

REALbasic Teaching Curriculum Overview 11

Lesson 1: Introducing REALbasic . . . . . . . . . . . . . . . . . . 11

Lesson 2: Expressions, Assignments & Types. . . . . . . . . . . . . 11

Lesson 3: Conditionals and the Debugger . . . . . . . . . . . . . 11

Lesson 4: Variables and Loops . . . . . . . . . . . . . . . . . . . 12

Lesson 5: Modules, Methods and Recursion . . . . . . . . . . . . . 12

Lesson 6: Arrays & Strings . . . . . . . . . . . . . . . . . . . . . 12

Lesson 7: Algorithms . . . . . . . . . . . . . . . . . . . . . . . 12

Lesson 8: Abstract Data Types . . . . . . . . . . . . . . . . . . . 12

Lesson 9: Polymorphism . . . . . . . . . . . . . . . . . . . . . 12

Lesson 10: Eliza . . . . . . . . . . . . . . . . . . . . . . . . . 12

Lesson 11: Events & Controls . . . . . . . . . . . . . . . . . . . 12

Lesson 12: Interfaces . . . . . . . . . . . . . . . . . . . . . . . 12

Lesson 13: Bubble Sort . . . . . . . . . . . . . . . . . . . . . . 13

Lesson 14: Insertion Sort . . . . . . . . . . . . . . . . . . . . . 13

Lesson 15: Refining the Insertion Sort . . . . . . . . . . . . . . . 13

Lesson 16: Quicksort . . . . . . . . . . . . . . . . . . . . . . . 13

Lesson 17: Exceptions, Constructors, Overloading . . . . . . . . . . 13

Lesson 18: File Enumerator . . . . . . . . . . . . . . . . . . . . 13

Lesson 19: Data Structures . . . . . . . . . . . . . . . . . . . . 13

Lesson 20: File Enumerator 2 . . . . . . . . . . . . . . . . . . . 14

Lesson 21: Hashing . . . . . . . . . . . . . . . . . . . . . . . . 14

Lesson 22 (Optional): Cyclic Redundancy Check . . . . . . . . . . . 14

Lesson 23: RPN Calculator Example . . . . . . . . . . . . . . . . 14

Lesson 24: Programmable RPN Calculator Example . . . . . . . . . 14

Lesson 25: Graphics I . . . . . . . . . . . . . . . . . . . . . . . 14

Lesson 26: Communications . . . . . . . . . . . . . . . . . . . . 14

Lesson 27: Simulation & Animation . . . . . . . . . . . . . . . . 15

1REALbasic Curriculum

Page 2: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 1 Introducing REALbasic 17

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

Creating the Project . . . . . . . . . . . . . . . . . . . . . . . 17

A program consists of lines of code . . . . . . . . . . . . . . . . 25

A program also consists of objects with properties . . . . . . . . . 27

Behind the scenes: What is a Compiler? . . . . . . . . . . . . . . 27

A Final Note . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

LESSON 2 Expressions, Assignments and Types 29

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

A Better Greeter . . . . . . . . . . . . . . . . . . . . . . . . . 29

About Expressions . . . . . . . . . . . . . . . . . . . . . . . . 30

About Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

Experiment . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

An Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

Another Example . . . . . . . . . . . . . . . . . . . . . . . . 32

More Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

Experiment . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

LESSON 3 Conditionals and the Debugger 37

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

A simple extension of the previous program . . . . . . . . . . . . 37

A smarter + . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

Boolean Expressions . . . . . . . . . . . . . . . . . . . . . . . 40

ElseIf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

Experiment . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

LESSON 4 Variables and Loops 47

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

Repeat a Beep . . . . . . . . . . . . . . . . . . . . . . . . . . 47

Dim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

For… Next . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

Repeating a String . . . . . . . . . . . . . . . . . . . . . . . . 50

A Couple of Easy Improvements. . . . . . . . . . . . . . . . . . 52

Experiment . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

2 REALbasic Curriculum

Page 3: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 5 Modules, Methods and Recursion 55

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

Repeat a String . . . . . . . . . . . . . . . . . . . . . . . . . 55

How REALbasic Executes a Method or Function . . . . . . . . . . . 60

About Scope for Local Variables . . . . . . . . . . . . . . . . . . 60

Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

When to use Recursion . . . . . . . . . . . . . . . . . . . . . . 62

Trace it . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63Experiment . . . . . . . . . . . . . . . . . . . . . . . . . . 63

LESSON 6 Arrays and Strings 65

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

Say It Once . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

About Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 67

Add a Function to the Window . . . . . . . . . . . . . . . . . . 67

Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

Pre- and Post-Conditions . . . . . . . . . . . . . . . . . . . . . 70

Return Statements Act as Exit Points . . . . . . . . . . . . . . . . 70

Accessing the Array . . . . . . . . . . . . . . . . . . . . . . . 70

Finish the program . . . . . . . . . . . . . . . . . . . . . . . . 71

Run the Program . . . . . . . . . . . . . . . . . . . . . . . . . 71

More on Arrays . . . . . . . . . . . . . . . . . . . . . . . . . 72

Experiment . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

LESSON 7 Algorithms 73

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

What is an algorithm? . . . . . . . . . . . . . . . . . . . . . . 73

Algorithms and Computer Science . . . . . . . . . . . . . . . . . 74

An example of an algorithm: Counting words . . . . . . . . . . . 74

Starting with a Flow Chart . . . . . . . . . . . . . . . . . . . . 76

Pseudocode . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

A Word-Counting Algorithm . . . . . . . . . . . . . . . . . . . 79

How to Write an Algorithm . . . . . . . . . . . . . . . . . . . . 80

Our algorithm as a flowchart . . . . . . . . . . . . . . . . . . . 81

Exercise: Translate the flowchart into pseudo-code . . . . . . . . . 81The actual code . . . . . . . . . . . . . . . . . . . . . . . . 82

Run It . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

3REALbasic Curriculum

Page 4: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Experiment . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

LESSON 8 Abstract Data Types 87

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

What is an Abstract Data Type? . . . . . . . . . . . . . . . . . . 87

Pre- and Post-Conditions . . . . . . . . . . . . . . . . . . . . . 88

‘Object-oriented’ means built-in support for ADTs . . . . . . . . . 88

Improving The Word Counter with ADTs . . . . . . . . . . . . . . 88

Object References versus Scalars . . . . . . . . . . . . . . . . . . 89

The While Loop . . . . . . . . . . . . . . . . . . . . . . . . . 92

How is the ADT Code an Improvement? . . . . . . . . . . . . . . 92

The ADT Advantage . . . . . . . . . . . . . . . . . . . . . . . 93

An Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

LESSON 9 Polymorphism 95

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

How To Use This Lesson. . . . . . . . . . . . . . . . . . . . . . 95

What is Polymorphism? . . . . . . . . . . . . . . . . . . . . . . 95

An Example of a Class Hierarchy . . . . . . . . . . . . . . . . . . 96

Our Class Hierarchy. . . . . . . . . . . . . . . . . . . . . . . . 96

The Polymorphic Word Counter . . . . . . . . . . . . . . . . . . 97

Inheritance, Polymorphism, and Abstract Classes . . . . . . . . . . 97

Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97

Classes vs. Objects . . . . . . . . . . . . . . . . . . . . . . . .102

Polymorphism in Action . . . . . . . . . . . . . . . . . . . . .102

More on Events . . . . . . . . . . . . . . . . . . . . . . . . .103

The File Counter . . . . . . . . . . . . . . . . . . . . . . . . .103

A Minor Issue . . . . . . . . . . . . . . . . . . . . . . . . . .104

File Types . . . . . . . . . . . . . . . . . . . . . . . . . . . .105

Try It . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .106

Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . .106

Object-Oriented Design. . . . . . . . . . . . . . . . . . . . . .106

Explanations/References . . . . . . . . . . . . . . . . . . . . .107

Further Exercise . . . . . . . . . . . . . . . . . . . . . . . . .107

4 REALbasic Curriculum

Page 5: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 10 Eliza 109

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .109

What is Eliza? . . . . . . . . . . . . . . . . . . . . . . . . . .109

Planning the Program . . . . . . . . . . . . . . . . . . . . . .109

Loading the Phrases from a File . . . . . . . . . . . . . . . . . .110

ASCII Characters and Unicode . . . . . . . . . . . . . . . . . . .110

StringResponder . . . . . . . . . . . . . . . . . . . . . . . . .111

Scope of Identifiers. . . . . . . . . . . . . . . . . . . . . . . .116

Test It . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .116

Further Exercises . . . . . . . . . . . . . . . . . . . . . . . . .117

LESSON 11 Events and Controls 119

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119

Events and Controls . . . . . . . . . . . . . . . . . . . . . . .119

A Further Subclass . . . . . . . . . . . . . . . . . . . . . . . .121

More on Events . . . . . . . . . . . . . . . . . . . . . . . . .122

Further Exercises . . . . . . . . . . . . . . . . . . . . . . . . .124

Explanations/References: . . . . . . . . . . . . . . . . . . . . .124

LESSON 12 Class Interfaces 125

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .125

The Essence of Type . . . . . . . . . . . . . . . . . . . . . . .125

Multiple Types . . . . . . . . . . . . . . . . . . . . . . . . . .126

Only One Superclass . . . . . . . . . . . . . . . . . . . . . . .126

An Even Better Word Counter . . . . . . . . . . . . . . . . . . .127

Give Objects High-Level Behavior (or ‘Think Twice About Accessor Methods’) . . . . . . . . . . . . . . . . . . . . . . . . . . . .130

Questions and Conclusions . . . . . . . . . . . . . . . . . . . .133

Further Exercises . . . . . . . . . . . . . . . . . . . . . . . . .133

A Final Comment . . . . . . . . . . . . . . . . . . . . . . . .133

Take-home assignment: Writing to a File . . . . . . . . . . . . . .134

LESSON 13 Bubble Sort 135

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .135

About Efficiency . . . . . . . . . . . . . . . . . . . . . . . . .136Programmer’s Time vs. User’s Time . . . . . . . . . . . . . . .136

5REALbasic Curriculum

Page 6: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Programmer Time is Scarce . . . . . . . . . . . . . . . . . . .136User’s Time vs. Computer Time . . . . . . . . . . . . . . . . .136Why you should probably write a lot of quick and dirty programs .137When you should spend more time writing a program . . . . . .137Don’t Waste Time on Wasteful ‘Efficiency’. . . . . . . . . . . .137Different Parts of a Program Often Require Different Attention . .138

Four Lessons on Sorting. . . . . . . . . . . . . . . . . . . . . .138

The Bubble Sort . . . . . . . . . . . . . . . . . . . . . . . . .138How the Bubble Sort Works . . . . . . . . . . . . . . . . . .138

The Narrow Definition of Efficiency . . . . . . . . . . . . . . . .139

Best and Worst Cases . . . . . . . . . . . . . . . . . . . . . . .140

Further Exercises . . . . . . . . . . . . . . . . . . . . . . . . .140

LESSON 14 Insertion Sort 141

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .141

The Insertion Sort . . . . . . . . . . . . . . . . . . . . . . . .141

Examine the Results . . . . . . . . . . . . . . . . . . . . . . .142

Further Exercises . . . . . . . . . . . . . . . . . . . . . . . . .143

LESSON 15 Refining the Insertion Sort 145

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .145

About Testing . . . . . . . . . . . . . . . . . . . . . . . . . .145

Many Ways of Improving the Insertion Sort . . . . . . . . . . . .146

Commenting and Uncommenting Code . . . . . . . . . . . . . .147

Why is the New Algorithm Slower? . . . . . . . . . . . . . . . .148

Further Exercises . . . . . . . . . . . . . . . . . . . . . . . . .148

LESSON 16 Quicksort 149

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .149

How the Quicksort works . . . . . . . . . . . . . . . . . . . . .149

The Project . . . . . . . . . . . . . . . . . . . . . . . . . . .151

Further Exercises . . . . . . . . . . . . . . . . . . . . . . . . .152

LESSON 17 Exceptions, Constructors, Overloading 153

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .153

Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . .153

6 REALbasic Curriculum

Page 7: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Default Exception Handling . . . . . . . . . . . . . . . . . . . .158

Exceptional Eliza . . . . . . . . . . . . . . . . . . . . . . . . .159

Constructors and Destructors . . . . . . . . . . . . . . . . . . .160

Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . .160Limits on Overloading . . . . . . . . . . . . . . . . . . . . .161

Private Methods . . . . . . . . . . . . . . . . . . . . . . . . .161

Back to Exceptions . . . . . . . . . . . . . . . . . . . . . . . .162

Further Exercises . . . . . . . . . . . . . . . . . . . . . . . . .162

LESSON 18 File Enumerator 165

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .165

A Useful Class: A File Enumerator . . . . . . . . . . . . . . . . .165

Design Issues . . . . . . . . . . . . . . . . . . . . . . . . . .165

Depth First vs. Breadth First . . . . . . . . . . . . . . . . . . . .166

The Project . . . . . . . . . . . . . . . . . . . . . . . . . . .166

TrueItem . . . . . . . . . . . . . . . . . . . . . . . . . . . .167

Concepts We’ve Used In This Project . . . . . . . . . . . . . . . .167

Further Exercises . . . . . . . . . . . . . . . . . . . . . . . . .168

LESSON 19 Data Structures 169

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .169

The Project . . . . . . . . . . . . . . . . . . . . . . . . . . .170

Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . .170

About Binary Trees . . . . . . . . . . . . . . . . . . . . . . . .171

Other Approaches . . . . . . . . . . . . . . . . . . . . . . . .174

Other Improvements . . . . . . . . . . . . . . . . . . . . . . .174

Further Exercises . . . . . . . . . . . . . . . . . . . . . . . . .174

Appendix: About Memory Management . . . . . . . . . . . . . .176

LESSON 20 File Enumerator 2 177

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .177

Analyze the Problem . . . . . . . . . . . . . . . . . . . . . . .177

The Project . . . . . . . . . . . . . . . . . . . . . . . . . . .178

Further Exercises . . . . . . . . . . . . . . . . . . . . . . . . .179

7REALbasic Curriculum

Page 8: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 21 Hashing 181

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .181

About Hash Tables . . . . . . . . . . . . . . . . . . . . . . . .181

Activities and Procedures . . . . . . . . . . . . . . . . . . . . .182

Further Exercises . . . . . . . . . . . . . . . . . . . . . . . . .183

LESSON 22 Cyclic Redundancy Check 185

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .185

Learn Basic Binary Math . . . . . . . . . . . . . . . . . . . . .186

What is a Cyclic Redundancy Check? . . . . . . . . . . . . . . . .186

Math with Polynomials Modulo 2 . . . . . . . . . . . . . . . . .186

An Example . . . . . . . . . . . . . . . . . . . . . . . . . . .188

Speeding it Up . . . . . . . . . . . . . . . . . . . . . . . . . .190

The Project . . . . . . . . . . . . . . . . . . . . . . . . . . .191

Using CRCs . . . . . . . . . . . . . . . . . . . . . . . . . . .192

Further Exercises . . . . . . . . . . . . . . . . . . . . . . . . .192

Appendix 1: Polynomials Modulo 2 . . . . . . . . . . . . . . . .193Math Modulo n . . . . . . . . . . . . . . . . . . . . . . . .193Polynomial Math . . . . . . . . . . . . . . . . . . . . . . .193Polynomials Modulo 2 . . . . . . . . . . . . . . . . . . . . .193

Appendix 2: Boolean Operators . . . . . . . . . . . . . . . . . .194

Bitwise Boolean Operators . . . . . . . . . . . . . . . . . . . .194

Hexadecimal, Octal, and Binary Constants . . . . . . . . . . . . .195

LESSON 23 RPN Calculator Example 197

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .197

Model-View-Controller . . . . . . . . . . . . . . . . . . . . . .197

The Stack Data Structure . . . . . . . . . . . . . . . . . . . . .198

Reverse Polish Notation. . . . . . . . . . . . . . . . . . . . . .199

The Project . . . . . . . . . . . . . . . . . . . . . . . . . . .200The Classes and Interfaces . . . . . . . . . . . . . . . . . . .200The StackDisplay Class and the Stack Interface . . . . . . . . . .200The StackEntry Interface . . . . . . . . . . . . . . . . . . . .200The StackOperationButton Class . . . . . . . . . . . . . . . .201The StackOperation Interface . . . . . . . . . . . . . . . . .201The NumEdit Class. . . . . . . . . . . . . . . . . . . . . . .201The StackEntryBox class . . . . . . . . . . . . . . . . . . . .201

The CalcWindow . . . . . . . . . . . . . . . . . . . . . . . . .201

8 REALbasic Curriculum

Page 9: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Object Event Handlers in a Window. . . . . . . . . . . . . . .201The Open Event Handler in the CalcWindow. . . . . . . . . . .201

Further Exercises . . . . . . . . . . . . . . . . . . . . . . . . .202

LESSON 24 Programmable RPN Calculator 203

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .203

About RBScript . . . . . . . . . . . . . . . . . . . . . . . . .203

The Challenge . . . . . . . . . . . . . . . . . . . . . . . . . .204

The Project . . . . . . . . . . . . . . . . . . . . . . . . . . .204

Further Exercises . . . . . . . . . . . . . . . . . . . . . . . . .206

LESSON 25 Graphics I 207

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .207

Prereading . . . . . . . . . . . . . . . . . . . . . . . . . . .207

The Project . . . . . . . . . . . . . . . . . . . . . . . . . . .207

Pixels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .208

Coordinates . . . . . . . . . . . . . . . . . . . . . . . . . . .208

The Trigonometry . . . . . . . . . . . . . . . . . . . . . . . .208

DirectedChevron.GenerateFrame . . . . . . . . . . . . . . . . .208

REAL, basic Trigonometry . . . . . . . . . . . . . . . . . . . . .210

Which Image Points Here? . . . . . . . . . . . . . . . . . . . .212

Further Exercises . . . . . . . . . . . . . . . . . . . . . . . . .212

LESSON 26 Communications 215

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .215

TCP/IP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .215

The Project . . . . . . . . . . . . . . . . . . . . . . . . . . .217

Further Exercises . . . . . . . . . . . . . . . . . . . . . . . . .218

LESSON 27 Simulation and Animation 219

Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .219

Prereading . . . . . . . . . . . . . . . . . . . . . . . . . . .219

A Physics Simulation . . . . . . . . . . . . . . . . . . . . . . .219

The Math . . . . . . . . . . . . . . . . . . . . . . . . . . . .220MultiplyBy . . . . . . . . . . . . . . . . . . . . . . . . . .220Normalized . . . . . . . . . . . . . . . . . . . . . . . . . .220

9REALbasic Curriculum

Page 10: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Add and Operator_Add . . . . . . . . . . . . . . . . . . . .220

The First Project . . . . . . . . . . . . . . . . . . . . . . . . .221More Comments . . . . . . . . . . . . . . . . . . . . . . .222

AnimatedSpriteFlock . . . . . . . . . . . . . . . . . . . . . . .223

Fixing the Speed . . . . . . . . . . . . . . . . . . . . . . . . .223

Further Exercises . . . . . . . . . . . . . . . . . . . . . . . . .223

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . .225

General . . . . . . . . . . . . . . . . . . . . . . . . . . . . .225

Pre- and Post-conditions . . . . . . . . . . . . . . . . . . . . .226Precondition . . . . . . . . . . . . . . . . . . . . . . . . .226Postcondition . . . . . . . . . . . . . . . . . . . . . . . . .226

Loop invariants . . . . . . . . . . . . . . . . . . . . . . . . .226Introduction . . . . . . . . . . . . . . . . . . . . . . . . .229

Programs have (up to) three parts . . . . . . . . . . . . . . . . .229

The advantages of MVC . . . . . . . . . . . . . . . . . . . . .230

Implementation by Class and Interface . . . . . . . . . . . . . . .230

A detailed example: A Reverse Polish Notation Calculator . . . . . .231View Classes or Interfaces . . . . . . . . . . . . . . . . . . .232

Final Notes . . . . . . . . . . . . . . . . . . . . . . . . . . .232

10 REALbasic Curriculum

Page 11: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

REALbasic Teaching Curriculum Overview

Lesson 1: Introducing REALbasic

You will learn the minimum you need to create and run a simple REALbasic applica-tion. You will also learn a little of what goes on behind the scenes in REALbasic.

Remember: the REALbasic curriculum project is concerned with teaching you com-puter science, so we will not be covering REALbasic’s capabilities in detail. There are many other places where you can get that information (starting with REALbasic’s doc-umentation).

Lesson 2: Expressions, Assignments & Types

You will learn how to perform simple calculations; how to shift information around, and a little about REALbasic’s different data types.

Lesson 3: Conditionals and the Debugger

You will learn how to get REALbasic to make simple decisions, and how to follow as REALbasic executes code by using the debugger.

11REALbasic Curriculum

Page 12: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

REALbasic Teaching Curriculum Overview

Lesson 4: Variables and Loops

You will learn to store information and to repeat actions.

Lesson 5: Modules, Methods and Recursion

You will learn the basics of using modules, methods, and recursion. Modules and Methods are ways of breaking a complex project into manageable pieces. Methods also allow us to re-use code. Recursion is a way of repeating actions within a program.

Lesson 6: Arrays & Strings

You will learn how to use arrays and the basics of manipulating strings. You will also see a simple example of an algorithm.

Lesson 7: Algorithms

You will begin developing and writing algorithms.

Lesson 8: Abstract Data Types

You will begin looking at object-oriented programming. We begin this by examining how and why we should create our own data types.

Lesson 9: Polymorphism

You will start learning to use polymorphism, which lets us take advantage of similari-ties between objects to simplify code.

Lesson 10: Eliza

You will put together a program, to exercise our new programming muscles. We’re going to stick mostly to things we’ve been using for a while, not venturing into the new ADT and polymorphism material. We’re just trying to see what a slightly more com-plex program looks like.

Lesson 11: Events & Controls

You will continue to explore REALbasic’s Object Oriented Programming (OOP) fea-tures.

Lesson 12: Interfaces

You will examine our last major OOP feature in REALbasic: the Class Interface.

12 REALbasic Curriculum

Page 13: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

REALbasic Teaching Curriculum Overview

Lesson 13: Bubble Sort

We take a break from object-oriented programming to return to algorithms. Over the next few lessons, we will examine a number of different ways of sorting.

In doing this, you will achieve a few things:

n You will begin learning about the rich and complex notion of efficiency in computer programming;

n You will see an example of how many ways there usually are to solve a given problem (even an apparently simple one) with a computer, and

n You will look at more code. It is important to read a broad range of code.

Lesson 14: Insertion Sort

You will look at another sorting algorithm. We will also build a program that lets us easily compare different sorting algorithms.

Lesson 15: Refining the Insertion Sort

You will look at a variation on the insertion sort. We will build a framework that allows us to compare different sorting algorithms’ speed, and use it to see if the new variation is faster.

Lesson 16: QuicksortYou will learn about the Quicksort, one of the fastest general-purpose sorting algo-rithms known. We will learn how it works, code it up in REALbasic, and then com-pare it to the other sorting algorithms we’ve developed.

Lesson 17: Exceptions, Constructors, Overloading

You will take a bit of a breather from complex algorithms. We’re going to look at one major subject (Exceptions), and along the way, we’ll pick up a couple of simple extras (Constructors and Overloading).

Lesson 18: File Enumerator

You will take a breather from learning new programming concepts, and putting some of these concepts together in a useful project.

Lesson 19: Data Structures

You will crate a version of the File Enumerator that can handle folder aliases without getting trapped in loops that can be caused by aliases.

13REALbasic Curriculum

Page 14: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

REALbasic Teaching Curriculum Overview

Lesson 20: File Enumerator 2

You will pull the results of the last project into the file enumerator project from the previous lesson and refine the file enumerator a bit as well.

Lesson 21: Hashing

You will combine a simple data structure called a hash table with the simple linear list from an earlier lesson. The result is a data structure that is much faster than the binary-searched array.

Lesson 22 (Optional): Cyclic Redundancy Check

You will explore the strange world of binary arithmetic through the implementation of a very important algorithm, the Fast Cyclic Redundancy Check.

This lesson is declared to be optional. Of course, all the lessons are optional, but this one has more unusual theory than the other lessons do.

Lesson 23: RPN Calculator Example

You will build a simple Reverse Polish Notation (RPN) calculator. As well as being good practice, this project will get you to think about implementing and using a stack data structure. We also introduce the Model-View-Controller software design para-digm.

Lesson 24: Programmable RPN Calculator Example

We make the calculator from the last lesson programmable with RBScript. This is an interesting exercise, since RBScript’s ability to communicate with other parts of the same program is fairly limited.

Lesson 25: Graphics I

We are working up toward some fun stuff with sprites. Consistent with the develop-ment techniques we’ve discussed, we are going to start with one small part and test it. This part is a picture that can point in different directions.

Lesson 26: Communications

You will develop a very simple yet useful application to demonstrate the use of TCP ports. The application sends a text message to another computer running the same application.

14 REALbasic Curriculum

Page 15: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

REALbasic Teaching Curriculum Overview

Lesson 27: Simulation & Animation

You will do a reasonably significant exercise in simulation and animation. We’ll pro-duce a SpriteSurface with a collection of the chevrons from our earlier lesson, and we’ll have them chase the mouse pointer. Then we’ll see a little of the advantages of object orientation when we see how easy it is to animate the sprites.

15REALbasic Curriculum

Page 16: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

REALbasic Teaching Curriculum Overview

16 REALbasic Curriculum

Page 17: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 1 Introducing REALbasic

Aim

In this lesson, you will learn how to create and run a simple REALbasic application. You will also learn a little of what goes on behind the scenes in REALbasic.

Remember: The REALbasic curriculum project is concerned with teaching you com-puter science, so we will not be covering REALbasic’s capabilities in detail. There are many other places where you can get that information, starting with REALbasic’s doc-umentation.

Creating the Project1 Double-click the REALbasic icon to start the software.

REALbasic opens the main Integrated Developer Environment (IDE) window:

17REALbasic Curriculum

Page 18: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Introducing REALbasic

Figure 1. The Project Window.

This window contains all the elements of your project. The first screen you see con-tains the Project Editor. The REALbasic IDE consists of several editors that are pre-sented in tab panels.

The Project Editor opens automatically when you create a new project or open an existing one. You can have more than one such window for a single project, and you can open multiple projects at once if you like, but you will often do all your REALba-sic work in just this one window.

You can work in one window because you can open many different tabs (much as with a tabbed web browser) to view different parts of your project. Because you have just launched REALbasic without opening an existing project, REALbasic has helped you out by creating a new project with some starter items already in it. The tab you see right now is the Project Editor, from which you can access all the parts of your REAL-basic project.

2 Double-click on the Window1 item in the Project Editor. This opens a new Window1 tab showing the Window Editor, ready to add controls to it.

18 REALbasic Curriculum

Page 19: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Introducing REALbasic

Figure 2. The Window Editor

Notice that you can still see the Project Editor tab below the toolbar, and you can click on it and the Window1 tab to switch between them. Notice also that the Window1 tab has a close widget on its right side. Closing a tab only closes the editor; all the objects in your program remain until you delete them from the Project Editor. You can always re-open an editor by finding the object you want to edit in the Project tab and double-clicking on it.

In the center of the Window Editor, you see a blank window, ready to edit. To its left, you will see the Controls list, from which you can drag any of the controls you can add to the window, such as buttons, labels, text boxes in which the user can enter informa-tion, and so on:

19REALbasic Curriculum

Page 20: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Introducing REALbasic

Figure 3. The Controls list.

The pop-up menu above the Controls list lets you switch between REALbasic’s built-in controls, ones you've added through Plugins, ones you’ve created yourself, and Favorites.

We will use only a few of the many controls from this list in our lessons, but we will explain how each of these works as we get to it. Consult the User’s Guide for details on what the other controls do and how to create customized controls of your own.

3 Drag a StaticText control into the top left of the window (you will probably have to scroll the Controls list to find it).

Figure 4. The StaticText Control.

Once you've dropped it, drag it around a little. Notice that REALbasic displays guide lines and ‘snaps’ the control to the right spot, to help you place things according to your platform's User Interface Guidelines1.

1. Note that REALbasic Professional can create programs for Macintosh, Windows, or Linux from one set of code. And you don’t have to run REALbasic on the platform for which you want to create a program (although you should test it there). We won’t discuss this further in these lessons; consult the User’s Guide for more information.

20 REALbasic Curriculum

Page 21: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Introducing REALbasic

User interface guidelines are available from the following sources:

n Windows: Microsoft’s User Interface guidelines at: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwue/html/welcome.asp

n Macintosh: Apple Human Interface guidelines: http://developer.apple.com/documentation/UserExperience/Conceptual/OSXHIGuidelines/

n Linux KDE Desktop: KDE user interface guidelines: http://developer.kde.org/documentation/design/ui/KDE is one of the most popular Linux desktops and is used by default in several major Linux distributions. However, there are others. Linux supports a greater degree of desktop customization than Windows and Macintosh.

The Properties pane, which is on the right of the Window Editor, lets you manage the settings for the control that is currently selected in the window or the window itself:

Figure 5. The Properties pane.

Most of these settings are obvious; don’t worry for now about those that aren’t. Click on the Text: property and change it to read ‘Name:’ (without the quotes, just as you see in Figure 5 on page 21). Note that you can click in an area of the window that doesn’t contain a control to manage the properties of the window itself. Note also that you can resize the window when it is selected.

4 Drag an EditField control into the window to the right of the StaticText control:

21REALbasic Curriculum

Page 22: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Introducing REALbasic

Figure 6. The EditField Control.

5 Change its Name: to ‘UserName’ (one word, no spaces, and no quote marks).

6 Drag a PushButton control into the bottom right corner of the window:

Figure 7. The PushButton Control.

Horizontal and vertical guidelines appear as you drag it toward the corner of the win-dow.

7 Change its Caption property to ‘Greet Me’. You’ll probably need to make the button a little wider to get its label to fit. Note that you can change the location and size of the things in the window using the same tech-niques you would use in any drawing program.

8 Double-click on the PushButton. This switches the Window Editor from editing its layout to editing its objects. You can also switch between the Layout editor and the Code Editor by clicking the unse-lected Edit Mode button. In Figure 8, the Code Editor mode is selected.

Figure 8. The Edit Mode buttons.

The Edit Mode buttons switch from the layout editing mode (highlighting the right side of the widget) to the code editing mode (highlighting the left side). You can also switch between the two by clicking on the control. On the Windows platform, the selected mode is depressed instead of highlighted.

The Code Editor lets you see all the code you’ve added directly to the window or the controls in it (we will see later that usually, some or even most of the code governing the behavior of the window and the controls will be elsewhere, but don’t concern your-self with that for now). The Code Editor opens to the most likely Event for the control you just double-clicked on.

22 REALbasic Curriculum

Page 23: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Introducing REALbasic

Figure 9. The Code Editor pane.

Note how the Code Editor lets you edit the program code for every control in the window, as well as other things belonging to the window, through the browser to the left of the code editing area. On Windows, you expand items by clicking the plus signs and, on Macintosh and Linux, you click disclosure triangles. Try clicking on some of the little plus signs or disclosure triangles in the browser and you’ll see.

For now, you only need to understand that all the controls in the window can contain REALbasic code to tell them what to do when particular things happen. In the exam-ple shown, the button has been told what to do when it is clicked on (that is, when its Action event occurs). Type in the code exactly as you see it in the picture:

As you start typing the word MsgBox, REALbasic will try to anticipate what you are typing, and will fill in the rest of the word:

Figure 10. Code completion.

Whenever REALbasic does this, you can press the Tab key to accept REALbasic’s highlighted suggestion, or to choose from a list if there is more than one possible way to complete what you have typed so far.

Note that there is only one space in that line, between MsgBox and UserName.Text (in particular, only a period and no space between UserName and Text).

MsgBox UserName.Text

23REALbasic Curriculum

Page 24: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Introducing REALbasic

A note: REALbasic program code is not case-sensitive. This means you can use upper-case, lowercase, or any mixture of these, and things will work just fine.

And one final thing: If you click in the grey area to the left of the line of code, you will see a red dot appear. This sets a breakpoint in your code. Until we discuss breakpoints in Lesson 3, just click on the red dot and it will go away again.

9 Save your project, just as you would save a file in any other program.If you run the program after modifying it and without saving it, REALbasic automati-cally saves a hidden copy, just in case something goes wrong while running the pro-gram (if REALbasic does crash on you1, just fire up REALbasic and it will offer to restore the hidden copy for you). But it is a little easier if you remember to save your projects yourself. Besides, we’re going to be using this project again — so make sure you remember where you put it.

10 Click the Run button in the toolbar:

Figure 11. The toolbar.

11 REALbasic will open a new Run tab, which will show you the progress as REALbasic compiles your application. It also lets you interact with your program while it runs through REALbasic’s debug-ger. We will discuss the debugger in Chapter 3.If REALbasic is unable to compile the application, it shows you the errors it encoun-ters that prevented it from compiling. If REALbasic shows you any errors, it will switch back to the Run tab and highlight the line where the error occurred. Check what you typed against what we have above, fix the problem, and try again. When the application has no errors, REALbasic will compile and launch the program in its own window. Meanwhile, the Run tab in the IDE lets you monitor execution in the debugger.

1. Any programming tool of REALbasic’s complexity will inevitably ‘crash’ from time to time. This is both because no program of any complexity is ever completely bug-free, and also because REALbasic gives you access to the system in such a way that it can’t always pro-tect you from crashing your program when you do something wrong. Don’t be too alarmed about this; it shouldn’t happen very often.

24 REALbasic Curriculum

Page 25: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Introducing REALbasic

Figure 12. Your first REALbasic program.

When the program runs, type something into the EditField box, and click the Greet Me button. It will display exactly what you typed, in a dialog box. Click OK to close the dialog box, then choose Exit from the File menu (Quit on Mac OS X and Linux). This will return you to REALbasic’s programming environment (in fact, the program and REALbasic are just two separate running programs, so you can switch between the two at any time, just as you can between any programs on your operating system).

A program consists of lines of code

Now let’s see how that worked. Choose Language Reference from the Help menu. This will open REALbasic’s Help system, which provides fairly complete information about REALbasic’s programming language and its class library1:

1. A class library is a collection of ready-made tools. All the items in the Controls list, along with the other objects listed in the Language Reference form REALbasic’s class library.

25REALbasic Curriculum

Page 26: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Introducing REALbasic

Figure 13. The Language Reference window.

A REALbasic program consists of one or more lines of code. Each line tells the com-puter to do one thing.

Those lines can take a few different forms, but the most common is like the one in this program: it consists of a command (in this case, MsgBox) at the beginning of the line, usually (but not always) followed by a space and then one or more pieces of informa-tion needed for the command to make sense. These pieces of information are called the arguments to the command. In this case, the MsgBox command needed a single argument, which provides the text for it to display.

Any particular line of code can be caused to take effect (we say the code is run or exe-cuted) in any of a fair number of ways. In this case, the code formed an event handler for a control, so it ran when an event occurred (in this case, when the button was clicked). By clicking on the disclosure triangles on the list of objects on the left side of the code editor that events are provided for just about anything happening you can think of (the mouse button going up over the object, the mouse button going down over the object, the mouse pointer moving over the object, something being dropped onto the object, and so on). We will use many of these events in later projects. Again, there is full documentation on all of the events available in every type of control, in the built-in Language Reference.

26 REALbasic Curriculum

Page 27: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Introducing REALbasic

A program also consists of objects with properties

The string (meaning the words) we wanted the MsgBox command to display has to be obtained from a property of the object in the window called UserName (remember when we set the name of the EditField?). The term property here means pretty much what it means in the real world: It is an attribute of some object (in this case, the text that the user entered into it). To fetch whatever a property is at the moment, we put the name of the object, a period, and then the name of the property (all with no spaces, as in UserName.Text in our program). When REALbasic runs a command and sees an argument written like this, it looks up what the value of the property is at the moment and then uses that value to complete the command.

If this is confusing right now, don’t worry too much; we’ll be discussing how a line like that works in some detail in the next lesson.

Behind the scenes: What is a Compiler?

It is helpful to understand a little of what is going on when you click Run.

Computers are immensely complex arrangements of millions upon millions of transis-tors in very complex circuits. These circuits are designed so that the things they can do include such tasks as storing and retrieving numbers very quickly, and treating those numbers not just as information, but also as simple instructions to compare other numbers, perform calculations on those numbers, move them around, and so on. It is possible to instruct the computer to do anything it is capable of, using these simple numeric instructions (creating programs this way is called writing machine code), but this is immensely inefficient and frustrating for people to do. Nevertheless, programs written in this way can generally be made to run about as fast as the computer is capa-ble of. When speed is important, people will write even quite complex code this way: important parts of computer games, for example, are often written in machine lan-guage.

Two major ways have been devised to make it more efficient for humans to program computers. Both involve devising an artificial language that provides a more expres-sive, human-friendly way of representing what the computer should do1. The differ-ence between the two approaches lies in how the computer winds up doing what this ‘high level’ language commands:

n An interpreter just reads the code and immediately does whatever the program commands; while

1. Representing the program in this way provides another benefit as well: the program is less tied to the particular machine language of a particular type of computer. This is why you can take a REALbasic program that runs on a Macintosh, and (using the Professional version of REALbasic) compile that same program to run on Microsoft Windows, with minimal or no changes, even though the machine language for the two computers is very different.

27REALbasic Curriculum

Page 28: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Introducing REALbasic

n A compiler reads the code for the program in the high level language and produces a machine language program that does the same thing.Each is suitable for a different purpose. For various reasons, interpreted programming languages tend to be a bit easier for humans to write, but the programs they run are considerably slower than compiled programs. Compiled programming languages usu-ally impose a few more restrictions on the programmer, in order to let the compiler produce faster code. Modern computers are so fast that the easier interpreted pro-gramming languages are better for simpler tasks because they make it as easy as possi-ble on the programmer.

REALbasic is a compiler, but the REALbasic language is a very friendly one, particu-larly for a compiler. Nevertheless, there are a few restrictions imposed on you as a pro-grammer, in order to permit REALbasic’s compiler to produce faster machine language programs. In practice, not only do these restrictions result in fairly fast pro-grams, but in complex programs, most of these restrictions also help to catch logical errors.

A Final Note

Finally: this course is a course in computer science that happens to use REALbasic. It teaches you just enough about REALbasic to learn the computer science. You should certainly read about more of REALbasic’s features in the User’s Guide and other docu-mentation. In particular, you should probably read Chapter 2 of that guide, which describes more about how the IDE works, right now.

28 REALbasic Curriculum

Page 29: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 2 Expressions, Assignments and Types

Aim

In this lesson, you will learn how to perform simple calculations; how to shift informa-tion around, and a little about REALbasic’s different data types.

A Better Greeter

Open the project from Lesson 1. We’re going to make it do a better job of greeting someone.

1 Open Window1, and double click on the button, so that REALbasic displays the Action event handler for the button again. This was where we put our code in the last lesson.

2 Change the Action event handler to read:

Notice that there is a space after the comma, before the double quote.3 Save the project again, and run it.

Much better.

MsgBox "Hello, " + UserName.Text

29REALbasic Curriculum

Page 30: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Expressions, Assignments and Types

What we’ve done is to provide REALbasic with a more sophisticated Expression as the argument for the MsgBox command. This expression puts some text in front of the text from the UserName box.

About Expressions

You have seen expressions many times, in math class. Something like this:

is an expression. It tells you to do various things (adding and multiplying, in this case), and provides all the information you need to do those things (the numbers you are going to add and multiply), and after you have done those things, you will have a result. Working out the result of an expression is called evaluating the expression.

All of this also applies to expressions in computer programs, except that there are many more operations available than you use in mathematics, and they can work on a much bigger variety of things than just numbers (as we can see in our program, which has an expression that contains pieces of text).

So here is the general principle:

Anywhere in a computer program where you are supposed to supply some piece of information, you can put an expression instead.

Actually, it’s a little more complicated than that; here’s the full version:

Anywhere in a computer program where you are supposed to supply some piece of information, you can put an expression instead — as long as when that expression is evaluated, the result is of the correct type.

About Types

Every piece of information in a computer program has a type. This is because you can only do certain things with certain kinds of information. It doesn’t make sense to mul-tiply two strings together, for example.

The important thing about a type is the operations you can perform on something of that type.

For now, you just need to know that any description of a command or operation1 in the REALbasic documentation will specify what types the arguments to the command

3 + 4 x 5

1. An operation is something like + or * in mathematics. The + in our program, that puts two strings together, is another example.

30 REALbasic Curriculum

Page 31: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Expressions, Assignments and Types

or operation should be, and what type the result should be. REALbasic will show you an error message if you try to run a program that breaks these rules.

The expression in our program uses the + symbol you are familiar with from mathe-matics, but in this case it doesn’t mean addition (it does mean addition if you use it with numbers). If you put strings1 on either side of it, when the computer evaluates this expression, it will form a new string by putting the second string right after the first (this is formally known as concatenating the strings). Notice that in the expression in our program, we had to tell REALbasic which part of the program line was a string by enclosing it in quotes. If we don’t do that, REALbasic will try to interpret that part of the line as a command, and will produce an error when you try to run the program (we’ll see what happens when you do that in a moment).

It is important to understand that spaces are characters just like letters and numbers. In our example, we put a space after the comma, inside the quotes, because if we hadn’t, the computer would have very obediently produced a result like:

rather than

Experiment

Try experimenting with the expression. For example, you can make a longer sentence. How would you get the computer to produce a result like this (hint: you can use the + operator more than once in an expression)?

An Error

Let’s see what happens if we deliberately introduce an error into our program. Change the code to read:

When you try to run this, REALbasic will put a little bug to the left of the problematic line and show a message at the bottom of the window.

1. String is the computer programming term for bits of text; it’s short for “strings of charac-ters.”

Hello,Guy

Hello, Guy

Hello, Guy. How are you?

MsgBox "Hello, " + UserName.Text + 2

31REALbasic Curriculum

Page 32: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Expressions, Assignments and Types

Figure 14. The Code Editor, showing a compiler error.

An type mismatch is when you can’t perform the operation you’ve asked for with the particular types of things you’ve provided. In this case, REALbasic expects that if you’re adding a number to something, that thing should also be a number. And if you’re adding a string to something, it should be a string. If you wanted to append a 2 to a string, you must put it in quotes, like this:

Again, the quotes tell REALbasic that the thing inside them is a string.

By the way, did you notice that as you’ve been working in REALbasic, whenever you point at something with the mouse pointer, that line at the bottom of the window pro-vides useful information about it?

Another Example

Let’s try a more complicated example. We’ll build a program that will add numbers together:

1 Choose New Project from the File menu.

2 Open Window1’s Window Editor, and drag three EditFields, a line and a PushButton into it. Rearrange them and set the button’s caption so the window looks like this:

MsgBox "Hello, " + UserName.Text + "2"

32 REALbasic Curriculum

Page 33: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Expressions, Assignments and Types

Figure 15. Drag three EditFields, a line, and a PushButton into Window1.

It’s generally a good idea to give meaningful names to every important object in your program. You set the name by clicking on the object, then changing the Name: in the Properties palette. From top to bottom, name the EditFields Source1, Source2 and Result. Name the PushButton EvaluateButton.

3 Double-click on the Pushbutton and set its Action handler to:

Don’t forget to save the project at this point. We’ll be using it again in the next lesson.

To understand the expression here, you need to know a few things:

n As well as operations and commands as we’ve seen so far, REALbasic has functions. When evaluated, a function supplies a value of some kind, such as a string or a number. Functions are written as a name followed by any arguments to the function between parentheses. CDbl is a function which has a single string argument, and turns that string into a number. Conversely, Str has a single argument that is a number, and turns that into a string.

n Since you can put an expression anywhere you are supposed to supply some piece of information’, one place you can put an expression is inside an expression. The computer will evaluate such expressions from the inside out.1

Result.text = Str(CDbl(Source1.text) + CDbl(Source2.text))

1. This may sound intimidating, but it’s something you’re probably already very familiar with. A numeric expression like 3*(4+5) consists of an expression (4+5) inside of a larger expression, and it all works exactly the same way in REALbasic, even down to using paren-theses to control the order in which things are evaluated.

33REALbasic Curriculum

Page 34: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Expressions, Assignments and Types

Now we have enough information to understand what the expression above means. Let’s look at it from the inside out:

Notice how we had to be sure about the type of what we had at each step of the way: the Editfields contain strings, so we had to turn these into numbers in order to add them together (2 is not the same thing as "2", because 2 + 2 = 4, while "2" + "2" = "22"); then we had to turn the result back into a string, because the MsgBox command doesn’t accept a number.

More Errors

Even the professionals type things in wrong; here are some errors you might acciden-tally introduce, the error message REALbasic displays when you try to run the pro-gram, and an explanation of what is wrong:

Experiment

Try changing the project so it multiplies two numbers together. The symbol for multi-plication in REALbasic is * (so we would write two times two as 2* 2). You can also do division with the / symbol. Subtraction is the symbol you expect.

Expression(s) Meaning

Source1.text and Source2.text Whatever has been typed into the top two boxes in Window1.

CDbl(Source1.text) and CDbl(Source2.text)

The numeric value of whatever was typed into the box (these will be 0 if whatever was typed in can’t sensibly be interpreted as a number).

CDbl(Source1.text) + CDbl(Source2.text)

Adding together the numbers in the two boxes.

Str(CDbl(Source1.text) + CDbl(Source2.text))

Turning the result back into a string.

Code Error Message What’s wrong

MsgBox Username. Error: Parameters are not compatible with this function

The argument to the command, function or operator is of the wrong type; in this case, Username is an EditField, and you can’t display an EditField — you have to display its text property: Username.Text

MsgBox "hello," Username.text

Syntax Error You left out the +

MsgBox "hello," +Usernametext

Error: this method or property does not exist

You forgot the period between Username and text.

MsgBox "Hello, + Username"

No error This one runs, but displays Hello, + Username. This shows you the importance of putting quotes in the right place.

34 REALbasic Curriculum

Page 35: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Expressions, Assignments and Types

If you haven’t tried it, see if the program works with numbers with a decimal point and a fraction part, or a negative number.

What happens if you convert the project to do division, and then you ask it to divide by zero?

35REALbasic Curriculum

Page 36: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Expressions, Assignments and Types

36 REALbasic Curriculum

Page 37: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 3 Conditionals and the Debugger

Aim

In this lesson, you will learn how to program REALbasic to make simple decisions, and how to use the debugger to watch REALbasic execute code line by line.

A simple extension of the previous program

Lets get right to it.1 Open the program we saved in the second example in the previous lesson.

2 As before, with the Project Editor in front of you, open Window1’s Window Editor and expand its list of events in the Code Editor browser, so we are taken to its Action event handler.

3 Change the event handler to this:

If Source1.text="quit" thenBeepQuit

ElseResult.text = Source1.text + Source2.text

End if

37REALbasic Curriculum

Page 38: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Conditionals and the Debugger

4 Run the application. Type various things in and click the button, then try typing quit into the top box.There are a couple of new commands here (beep and quit), whose effects should be obvious. The interesting thing is the If-Then-Else-End If construction that gave us the special behavior when you typed in quit. We will go into If-Then-Else-End If in more detail below. For now, we’re going to use REALbasic’s built-in debugger to watch the code executing.

5 Click on the grey dash to the left of the first line (the if command). Notice the red dot this creates next to that line.

6 Run the program, type something into the boxes, and click the button.REALbasic will start running the program, but as soon as it is about to execute the line on which we put the breakpoint, it will bring the REALbasic IDE to the front, switch to the Run tab showing that line, and highlights the line. The highlighting shows the line that REALbasic is about to execute:

Figure 16. REALbasic’s debugger.

You will also see a new Variables pane (as well as a pop-up menu we won’t worry about for the moment):

Figure 17. The Variables pane.

The Variables pane shows all the information that is available from this part of the program. For reasons we will get into in a later lesson, Self refers to the window, while Me refers to the object in which the code is running (that is, the PushButton). So if you click on one of these links, REALbasic will switch the variables pane to show the current properties of the window or the button:

38 REALbasic Curriculum

Page 39: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Conditionals and the Debugger

Figure 18. The Object Viewer pane for the Pushbutton.

The pop-up menu above the variables pane tells you which object you’re viewing the properties of at the moment. If you pop it up, lets you back out to view the properties you started from to get to these properties (since properties can be objects which themselves have properties, you can “drill down” through quite a few layers of objects; the menu lets you back out the way you came).

We’ll look into using these features more closely in later lessons, but for now, we’re going to look at how we can step through the code.

7 Click the Step button in the Debugger’s toolbar. The highlighting is now over the next line to be executed (which line this is depends on what you’ve typed into the EditFields in the running program).In this program, there is no difference between Step and Step Into. Either command will let you step one line at a time through the running program. You can also Stop the running program or choose Resume, which stops the debugger and runs the program normally (until the program gets to a line with a Breakpoint again). You can also add and remove Breakpoints from the debugger, by clicking one of the dashes to the left of the code. If a line of code does not have a dash to its left, you cannot put a breakpoint there.

You can switch between REALbasic and the running program at any time, although if the program is stopped in the debugger, you’ll find it amazingly unresponsive when you switch to it.

Make sure you use the debugger liberally throughout all of our lessons, to help you see what is going on.

39REALbasic Curriculum

Page 40: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Conditionals and the Debugger

A smarter +

We’re not done with If-Then yet. Let’s look at a richer example.

Since + can be made to work with either strings or numbers, let’s make our project do either one automatically: if whatever has been typed into each box is a number, we will add them together; if not, we will concatenate the two strings together (concatenation is the name of what + does with strings).

1 Change the event handler to this1:

Again, we’re interested in the new if-then structure for making decisions, which in its full form looks like this:

As indicated by the … here, there are three places to enter REALbasic expressions and commands, to put together an If-Then in REALbasic:

n On the first line, between If and Then, is a Boolean expression (more on that below);

n After that line, you can have as many lines as you like of REALbasic commands;

n If you wish, you can have a line with the word Else, followed by some more REALbasic commandsAnd it all ends with End If.

Boolean Expressions

We’ve looked at string expressions and numeric expressions in previous lessons. Bool-ean2 expressions are very similar, except that Boolean expressions deal only with the

1. An important point: REALbasic program lines can be as long as you need; the code editor window will scroll sideways to accommodate. But this is not easy to read in the code editor, and impossible to represent in print. You can break a single line of code into multiple lines of text in the code editor by putting an underscore: _ at the end of the physical line that is “log-ically” continued on the next.

If (CDbl(Source1.text)=0 and Source1.text<>"0") or _ (CDbl(Source2.text)=0 and Source2.text<>"0") then

Result.text = Source1.text + Source2.textElse

Result.text = Str(CDbl(Source1.text) + CDbl(Source2.text))End if

If … Then…

Else…

End If

40 REALbasic Curriculum

Page 41: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Conditionals and the Debugger

values True and False. True and False are values that REALbasic can manipulate, just as it does numbers and strings.

There are two types of Boolean expressions:

n Simple: Boolean expressions state something about a value in the program, generally using operators like = (equals), <> (not equals), <= (less than or equal), or >= (greater than or equal). Sometimes a property or something else in the program will actually just be a Boolean value. The checkboxes you see in the property palette when you click on a control are good examples. Source1.Bold is a valid Boolean expression, since there is a Bold checkbox in the Properties palette when you click on one of the EditFields — so the expression Source1.Bold would evaluate to True when Source1’s Bold checkbox is checked; and

n Compound: Boolean expressions are made out of other Boolean expressions (which can themselves be either simple or compound), using Boolean Operators Not, And or Or.As with other types of expressions, you will often need to use parentheses in Boolean expressions to make it clear in what order operations should be carried out. Also, as with other types of expressions, REALbasic works out the final value from the inside out. Let’s see how REALbasic evaluates the expression in our program:

2. Boolean logic was invented by George Boole (1815-1864), and was first presented in An Investigation of the Laws of Thought (1854). It is a very simple system, and any computer pro-grammer should study its basics.

(CDbl(Source1.text)=0 and Source1.text<>"0") Or (CDbl(Source2.text)=0 and Source2.text<>"0")

41REALbasic Curriculum

Page 42: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Conditionals and the Debugger

Notice how we put parentheses in to make the order of the operations clear. There are rules for how REALbasic any expression if you leave out the parentheses:

but it is much simpler and clearer to just put in the parentheses.

You may find it helpful to look at the evaluation of that expression in a kind of dia-gram called a syntax tree:

Figure 19. A syntax tree.

REALbasic evaluates the expression from the bottom of the syntax tree up. At the bot-tom of each line in the diagram is a Boolean expression that has a Boolean value, and at

Expression(s) Meaning

Source1.text The contents of Source1.

CDbl(Source1.text) The numeric value of Source1.text if it is a number, or 0 if it is anything else.

CDbl(Source1.text)=0 True if CDbl(Source1.text) comes out 0; False otherwise.

Source1.text<>"0" True if Source1.text is anything other than "0" (note that <> means not equal to).

(CDbl(Source1.text)=0 And Source1.text<>"0")

True if CDbl(Source1.text) comes out 0, when the text in Source1 isn’t "0". In other words, True if the user typed in something that wasn’t a number (remember: something that isn’t a number supplied as the argument to Cdbl evaluates to 0).Note that And between two expressions comes out True if both the expressions on either side of it are True.

(CDbl(Source2.text)=0 and Source2.text<>"0")

The same, just looking at what was typed into Source2.

(CDbl(Source1.text)=0 and Source1.text<>"0") Or (CDbl(Source2.text)=0 and Source2.text<>"0")

True if either Source1 or Source2 has something other than a number entered into it.

CDbl(Source1.text)=0 and Source1.text<>"0" Or CDbl(Source2.text)=0 and Source2.text<>"0"

(val(Source1.text)=0 Source1.text<>"0"

and

(val(Source2.text)=0 Source2.text<>"0

and

or

42 REALbasic Curriculum

Page 43: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Conditionals and the Debugger

the top of each line is a Boolean operator to combine these Boolean values, forming a larger Boolean expression.

So now you can see how the whole if-then-else construct works in our code. If the user didn’t enter numbers into both boxes, REALbasic concatenates the strings:

Otherwise, the computer adds together the values typed into the boxes (the part after Else):

By the way, the other Boolean operator we haven’t looked at, Not, is very easy to use: When you put Not in front of a Boolean value x, the Not expression comes out True if x is False, and comes out False if x is True. So an equivalent form of our event handler would be:

We did a couple of things here:We applied the Not operator to the entire expression between If and Then. Notice that we put parentheses around that entire expression, so that Not would be applied to the results of the entire expression, rather than just the first part of it; and

n We swapped the commands between Then and Else with those between Else and End If.Finally, you need to know that the Else part of an If-Then is optional. So we could just add numbers and ignore anything else with this code:

Result.text = Source1.text + Source2.text

Result.text = Str(CDbl(Source1.text) + CDbl(Source2.text))

If Not((CDbl(Source1.text)=0 and Source1.text<>"0") or _ (CDbl(Source2.text)=0 and Source2.text<>"0")) then

Result.text = Str(CDbl(Source1.text) + CDbl(Source2.text))Else

Result.text = Source1.text + Source2.textEnd if

If Not((CDbl(Source1.text)=0 and Source1.text<>"0") or (CDbl(Source2.text)=0 and Source2.text<>"0")) then

Result.text = Str(CDbl(Source1.text) + CDbl(Source2.text))End if

End Sub

43REALbasic Curriculum

Page 44: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Conditionals and the Debugger

ElseIf

If you need to make a sequence of decisions, you could put if-then statements inside other if-then statements, like this:

This is perfectly legitimate and will work as you would expect. However, if you need to do a whole sequence of these, it will all get a bit hard to read, and indented a long way to the right.

REALbasic provides a different way of saying this same thing, with the ElseIf com-mand, that moves the next If up onto the same line as the Else, and only requiring one EndIf at the end. In other words, the code immediately above could be written:

REALbasic executes the first If or Elseif part whose Boolean expression evaluates to True, and skips the rest.

Experiment

Make sure you understand how to build different types of Boolean expressions, and don’t be afraid to use parentheses to control the order in which REALbasic does things. A couple of things you might like to try are:

n Make the program beep and show an error message if the user types in a negative number, or concatenate what they typed in otherwise;

If (CDbl(Source1.text)=0 and Source1.text<>"0") or _ (CDbl(Source2.text)=0 and Source2.text<>"0") then

Result.text = Source1.text + Source2.textElse

If Result.text = “quit” ThenQuit

ElseResult.text = Str(CDbl(Source1.text) + CDbl(Source2.text))

End IfEnd if

End Sub

If (CDbl(Source1.text)=0 and Source1.text<>"0") or _ (CDbl(Source2.text)=0 and Source2.text<>"0") then

Result.text = Source1.text + Source2.textElseIf Result.text = “quit” Then

QuitElse

Result.text = Str(CDbl(Source1.text) + CDbl(Source2.text))End if

End Sub

44 REALbasic Curriculum

Page 45: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Conditionals and the Debugger

n Make the program quit if the user types quit into both boxes, but add the values if they don’t.

45REALbasic Curriculum

Page 46: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Conditionals and the Debugger

46 REALbasic Curriculum

Page 47: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 4 Variables and Loops

Aim

In this lesson, we will learn to store information and to repeat actions.

Variables

In order to do something a fixed number of times, we need a way of keeping track of our count as we go. This count will be a whole number, or integer in mathematical terms. The thing in which we keep this information is called a variable. Think of it as a piece of paper we can write information on. The piece of paper has a name so we can refer to it. When we use the name of a variable in an expression, REALbasic evaluates that name to whatever information is kept in the variable with that name at that moment.

Repeat a BeepWe’re going to create a new project that will repeat an action a certain number of times.

1 Create a new project, and open Window1 in its Window Editor so we can set up our user interface.

2 Drag a Label, a PushButton and a Slider into the window, and set it up so it looks like Figure 20 on page 48:

47REALbasic Curriculum

Page 48: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Variables and Loops

Figure 20. The user interface for the project.

3 Click on the Slider in Window1. In the Properties pane and set the slider's Initial State properties to the following:

4 Double-click on the Pushbutton, and set its Action event handler to:

If you’re doing this on Mac OS X, multiple beeps all come out at the same time, so change this code to read:

5 Run the project, click the button, move the slider, click the button again.Read about the Slider control in the built-in help if you wish.

Property Value

Minimum 1

Value 0

Maximum 10

Dim counter as IntegerFor counter = 1 to slider1.Value

BeepNext

Dim counter as IntegerFor counter = 1 to slider1.Value

MsgBox "Beep"Next

48 REALbasic Curriculum

Page 49: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Variables and Loops

Dim

We mentioned in an earlier lesson that REALbasic is a compiled programming lan-guage, and that this occasionally meant that we had to do things to help the resulting program run faster (these things also help us to catch our own programming errors).

One of the things we have to declare to REALbasic is what type of information a vari-able will contain1. If we try to put the wrong type of information into a variable, REALbasic will produce an error.

If we could just use any variable to store any type of information, every time REALba-sic wanted to use a value we’d stored in a variable, it would first have to check what type of information that variable contained, and this would slow everything down.

Declaring the type is a kind of contract between you and REALbasic: you promise not to put the wrong type of data into the variable, and REALbasic can rely on this assumption to make the code run faster.

The command to do this is called Dim for historical reasons: REALbasic is based on an older programming language called BASIC (short for Beginner’s All-Purpose Sym-bolic Instruction Code). REALbasic is much more advanced than the older BASIC lan-guage, but it shares its design goal of making things simple for beginners. It also supports the main commands that made BASIC what it is. Also, most old BASIC code will run with simple modifications in REALbasic.

One of those old commands was dim, short for dimension. In those older program-ming languages, dim was reserved for declaring arrays (we’ll get to arrays in a later les-son), for which the command name made sense. So the name is a little weird now because it has grown out of an older, narrower sense.

You can Dim as many variables in your code as you wish, using as many separate Dim commands as you wish. You can declare a variable anywhere within the code that you wish, but note that you will only be able to use it below the point where you declare it and also, that if you declare it within a loop, you can only use it within that loop (this is actually useful, since if you just need a variable within a small piece of code, you can have it automatically spring into existence and be removed after you’re done with it).

1. One exception: there is a type of variable called a variant that can contain any data type REALbasic can store. It is mostly there to make it easy to use code written for Microsoft’s Visual Basic. REALbasic was designed to be similar to Visual Basic, and some surprisingly complex Visual Basic projects can transfer with little change to REALbasic.The other use of the variant is if we are writing simple code quickly, without regard to how fast it runs: if you just need to automate a simple task without messing about, by all means use variants to store the information. Variants make the code run slower, and they can hide programming errors, but in simple projects, this may not matter.For everything else, though, avoid variants like the plague.

49REALbasic Curriculum

Page 50: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Variables and Loops

For… Next

The other new element in our code is the For… Next loop, that repeats an action. A For loop has this basic structure:

n A line that begins with For, followed by a variable name, an = sign, a start value, the word to and a finish value.

n As many REALbasic commands as you wish, each on a separate line (called the body of the loop); and.

n The word Next on a separate line.

In our example (For counter=1 to Slider1.value), the variable is named Counter, the start value is 1, and the finish value is the Value property of Slider1.

When REALbasic encounters a For-Next loop, it sets the variable to the start value, then repeatedly checks to see if the variable is greater than the finish value, and until it is, it runs the code in the body of the loop, then adds 1 to the variable.

If you look in the built-in Language Reference, you will see that you can add a Step command to the end of the For line, to get it to add a value other than 1 to the variable each time around. There is also a DownTo keyword for counting backward.

We didn’t need to do it in this case, but you are free to use the value of the variable within the body of the loop, anywhere you need a numeric value. You can also just change the value of the variable, perhaps to make the loop end early. We will see in a moment how to access and change the value of a variable.

Finally, note that the variable must be of a numeric type (integer is the only numeric type we’ve seen so far, and will be the most common control variable in for loops).

Repeating a String

Let’s try something a little more complex:1 Change Window1 so it looks like Figure 21 on page 51:

50 REALbasic Curriculum

Page 51: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Variables and Loops

Figure 21. Window1 in the second project.

Remember: to change the name of a control, click on it and edit its name in the Prop-erties pane. In this case, the small EditField is named SourceString ; the larger one ResultString. Also, check the Multiline checkbox for the ResultString box in the Prop-erties pane.The slider has the same settings we gave it before.

2 Put the following code in the PushButton’s Action event handler:

The Dim statement creates a string variable so we have somewhere to build a new string. The Counter variable that is used in the For loop is declared as an Integer inside the For statement.Within the For loop is a single command,

This is an assignment command. It is written as the name of a variable or property, an = sign, then an expression. The result of the expression must be of the same type as the variable or property on the left of the equals sign.

Dim store as StringFor counter as Integer = 1 to slider1.Value

store = store + SourceString.textNextResultString.text = store

store = store + SourceString.text

51REALbasic Curriculum

Page 52: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Variables and Loops

Notice in this case that the variable itself is mentioned in the expression. This is important, so we’ll put it in a box:

So in this case, we take the current string in the store variable, put the text from the SourceString EditField after it, and then put the result back into the store variable.

In other words, we attach the text in the SourceString EditField to the end of store. And we do this as many times as the current value of the slider (because that’s how many times we run the For loop).

Since when we create a variable, it has an empty kind of value (strings have no charac-ters; numbers are 0), what we get is a number of copies of the string entered into the SourceString EditField.

The final line of the code is another assignment, but this time it is an assignment to a property. In this case, we put the string we just built up into the text of the bottom EditField.

Run the code, so you can see that this is indeed what happens. Don’t forget to type something into the top box before you click on the button.

A Couple of Easy Improvements.

This isn’t really the subject of this lesson, but it’s so easy to do, it’s hard to resist:1 Copy the code from the PushButton’s Action event handler, and put it in

the slider’s ValueChanged event handler.

2 Run the program again. This time, you don’t need the button. You can even go into the window editor, click on it and press the Delete key.

3 Now, go to the window again, click on the slider, and turn on its LiveScroll property, then try it all again. This changes the way the slider calls its event handler. Before, it called the event han-dler only when you released the mouse button. But with LiveScroll set to True, the event handler is called as you move the slider. Much more satisfying, although if the handler takes too long to run, it might be too slow, so you need to decide when to use this feature.

Experiment

There are many things you could do from here, combining the things we’ve learned so far:

n Make a program that does what this last one did, unless you type the word ‘beep’ into the SourceString EditField. In that case, it beeps as many times as the slider indicates.

The right-hand side of an assignment is fully evaluated, and then it is assigned to the variable or property on the left.

52 REALbasic Curriculum

Page 53: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Variables and Loops

n Make a program that has a slider and an EditField, and it displays the numeric value of the slider in the EditField. Note that you can turn on the ReadOnly property of an EditField, to stop the user from being able to type into it.

n Have a program with a button and a slider, in which the slider makes the button move around. (This is surprisingly easy: you can modify anything you can see in the Properties palette in code, by assigning to a property of the button with the same name you see in the palette. If you click on a PushButton control, you’ll see it has a Left property. All you need to is to say something like:

n Take a look at the other properties you see for the controls. You can do all sorts of weird and wonderful things by changing them now.

PushButton1.Left = Slider1.Value * 5).

53REALbasic Curriculum

Page 54: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Variables and Loops

54 REALbasic Curriculum

Page 55: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 5 Modules, Methods and Recursion

Aim

In this lesson, we will learn the basics of using Modules, Methods and Recursion. Mod-ules and Methods are ways of breaking a complex project into manageable pieces. Methods also allow us to re-use code in a special way. Recursion is a way of repeating actions within a program.

Repeat a String

We’re going to create a project that repeats a string a certain number of times.1 Launch REALbasic, if it is not already running. If it was already running,

choose New Project from the File menu. You should now have a new project.

2 Click on the Add Module button in the Project Editor.A module is a place to put variables and program code you can use from anywhere in the program.

3 Change the module’s name in the Properties pane to “StringLibrary”.Whenever you’re naming something in REALbasic, remember that you can never have any spaces in the name.

55REALbasic Curriculum

Page 56: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Modules, Methods and Recursion

4 Double-click on the module to open its code editor window, and click on the Add Method button.REALbasic will display a Code Editor in which you can provide the information about the method:

Figure 22. The Method Editor.

A method must have a Method Name.

You may also provide a list of arguments for the method in the Parameters box (param-eters is another name for arguments). If there is more than one argument, you must separate the arguments with commas. The definition of each argument takes exactly the same form you would use with a Dim command. In this case, this method has two arguments: the first is a string called s, and the second is an integer called n.

Finally, you can turn the method into a function by declaring a single Return Type. In this case, this method is a function that returns a String.

As you will see in a moment, functions in REALbasic are exactly like functions in mathematics: they have a Domain (the set of possible arguments to the function — in this case, the set of pairs of string and integer values) and a Range (the set of possible results — in this case, the set of all strings).

Once you have created a method or function in a Module like this, you can call it just as you called the built-in methods or functions like the CDbl function we used in pre-vious lessons.

5 Name the function RepeatString and give it the parameters s as String and n as Integer. Set the Return Type to String.

56 REALbasic Curriculum

Page 57: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Modules, Methods and Recursion

6 After you declare the new method, enter the following code:

This is similar to other code we have seen before, except for the return command, which ends the method and sends a value out to whatever expression the function was called from.

Your code editor window should now look like this.

Figure 23. The RepeatString function.

The data type that you used as the Return Type in the declaration must match the data type of the variable ‘result’.

7 Open the default Window1, and add two Editfields and a slider like Figure 24 on page 58.

Dim resultText As StringDim counter As Integer

For counter = 1 to nresultText = resultText + s + EndOfLine

next

Return resultText

57REALbasic Curriculum

Page 58: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Modules, Methods and Recursion

Figure 24. The String Repeater window.

8 Set the names of the objects, from top to bottom, to: Source, Repetitions and Result. Set the other properties to:

As well as adding methods to modules, we can add methods to the objects in our pro-gram. In this case, we’re going to add a method to the window.

9 Switch to Window1’s Code Editor and click on the Add Method button in the Code Editor toolbar. Name the Method Update and leave its Parameters and Return Type blank. Notice how the new Method is listed in the Methods group in the left pane of the win-dow.

Figure 25. The Code Editor, showing Window1’s Update method.

10 Enter the code shown:

Note that there must be no spaces on either side of the periods.

The Code Editor should now look like Figure 25 on page 58.

Control Properties

Source Width=224, Height = 22

Repetitions Width=224, Height=16, Minimum = 0, Value = 0, Maximum = 100

Result Width=224, Height=182, Multiline = True (checked)

Result.Text = RepeatString(Source.Text, Repetitions.Value)

58 REALbasic Curriculum

Page 59: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Modules, Methods and Recursion

Figure 26. The Update method.

11 Expand the Controls item in the browser and then expand the Repetitions item. Enter the following code into the ValueChanged event handler of Repetitions:

This calls the Update method of the window whenever the value of the slider changes. That is, whenever the user slides the slider to the left or right.

12 Run the program, type something into the top EditField, and move the slider around.

13 Put a Breakpoint in the ValueChanged event handler, and run the program again.

14 By clicking on the Step button, follow through as the program executes the event handler, which calls Update, which calls RepeatString. Notice how each method eventually exits back to the method that called it. You might also like to examine the pop-up menu above the code in the debugger, which shows the methods that haven’t yet exited, in order. If you select one of these, the debugger will switch to showing the code in that method, which lines is being executed there, and the variables for that method.You will probably find the Step Out button helpful. This finishes running the current method and then re-activates the debugger as soon as it gets back to the calling method. The Step Over command is also useful: it runs a method without stepping through any of it, and resumes debugging on the next line past the method.

Update

59REALbasic Curriculum

Page 60: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Modules, Methods and Recursion

How REALbasic Executes a Method or Function

It is important to understand what is going on when REALbasic executes (we also say ‘calls’) a method:

n REALbasic finds some unused memory to hold the arguments to the method and any variables you Dim inside the method. The variables declared as arguments to the method are allocated and named just as if they’d been Dimmed inside the method.

n REALbasic copies the values of the arguments from the calling method into the argument variables inside the method.

n REALbasic makes a note of the line of the calling method it needs to execute after the method is called.

n REALbasic executes the code inside the method.When the method is finished, if the method is a function, the result is copied back out to the expression from which the function is called. After exiting from a method, before it resumes the calling method, REALbasic marks the space empty that was allo-cated for the variables and arguments of the method that just finished.

About Scope for Local Variables

It is important to understand that any variables you Dim or declare as arguments in a method exist only within the method. It will be quite common for one method to Dim a variable called, say, counter and for this method to call another method which also Dims a variable called counter. These are two separate variables, and neither can see the other’s variable. So if either method modifies their counter variable, it will have no effect on the other one.

These local variables are destroyed when the method finishes running. By ‘destroyed’ we mean that any values these variables held are lost, and the space those variables occupied is reclaimed and available for re-use to store a different variable.

Since the local variables a method will use are allocated and destroyed each time the method is called, their values are not retained between calls to the method.

When you declare the data type of counter within the For line, it exists only as long as the For loop executes. It is cleared from memory after the last iteration of the loop fin-ishes and REALbasic executes the next line of code within the method.

The part of the program in which a variable, method, or property is visible is called its scope. We have used two levels of scope so far: the scope of variables Dimmed inside a method is limited to that method (or the loop inside the method) and Global scope within modules. Global scope, which is available only in modules, makes items avail-able to the entire application. We will encounter other rules about scope as we learn more about REALbasic’s various features.

60 REALbasic Curriculum

Page 61: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Modules, Methods and Recursion

Note that you can modify the arguments to a method within that method, but you’re only modifying a copy of the value that was provided in the method call; when the method ends, the value passed in is unchanged. You can put the keyword ByRef in front of the parameter declaration (as in: ByRef x As String), in which case you’re working with the original value, and can change it. This is mainly useful for sending back multiple values from a method.

Recursion

We saw the For-Next loop in an earlier lesson. Now we’re going to look at a very differ-ent way of repeating an action, called recursion.

1 Open the Window Editor for Window1 and select the slider control. Change the Maximum for the Repetitions slider to 5. Also, make sure its LiveScroll checkbox is unchecked. These will both make tracing through the execution easier.

2 Create a new method in the StringLibrary module with the same arguments and return types as RepeatString. Call it RepeatString2.

3 Set RepeatString2’s code to this:

You may find this code disturbing because the method is calling itself in the second Return line).

A recursive method is similar to a mathematical proof by induction:

n It has a recursion condition, which is an if-then (or similar) statement, to determine which of the following two things it does;

n It has a base case, which causes it to stop calling itself, and do some final step; and

n It has a recursive case, which causes it to:n perform a not-last step;n change whatever the recursion condition is so it’s closer to whatever makes it exe-

cute the base case; and finallyn call itself.

In our example, the recursion condition is:

Function RepeatString2 (s As String, n As Integer) As StringIf n<=0 then

Return "" //no spaces between the ““Else

Return s+RepeatString2(s, n-1)+EndOfLineEnd if

n <= 0

61REALbasic Curriculum

Page 62: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Modules, Methods and Recursion

(note that <= means less than or equal to). The base case is:

The recursive case is:

The last step is to return an empty string; and the not-last case is to return a copy of the string, concatenated with a one-shorter duplication of the string.

Notice here that each time the recursive case calls back into the method, it reduces by 1 the value being passed into the next invocation of the method as its n.

Remember what we said about what happens when a method is called: it creates a brand new copy of all the variables it’s working with. The old copy is still there, wait-ing to finish running. And each time we call back into the same method, we get closer to the condition that will make it execute the base case and finish. Once it gets to the base condition, it all unwinds through each of the unfinished methods, finishing the evaluation of the expressions that called the method, adding one copy of the string and returning that into the evaluation of the earlier method at each stage.

When to use Recursion

Recursion is a little strange and probably counterintuitive to someone who hasn’t encountered it before.

You should consider using recursion any time you want to write code that carries out some process in which, after you have carried out one step of the process, whatever is left over has to be put through the same process. Some examples:

n Making n copies of a string involves putting together one copy with n-1 more copies;

n Eating a sandwich involves swallowing the whole sandwich if it’s only bite-sized; otherwise, you take a bite and then repeat the whole process; and

n To draw a tree, you draw a branch if that branch is really short; otherwise, you draw a branch and then draw a number of shorter branches attached to it.Once you get used to using recursive code, it’s often the easiest way to solve a problem.

By the way, notice that in our method, we could have had n =1 as our base case (and just returned the string), but then our code wouldn’t have been able to handle being asked for zero copies of the string. That might have been alright, but if you’re not sure, it’s best to write your code so it’s the most general possible.

Return ""

Return s+RepeatString2(s, n-1)+EndOfLine

62 REALbasic Curriculum

Page 63: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Modules, Methods and Recursion

Trace it

You should change the code in Update so it calls Repeat2 rather than Repeat, and trace through it enough times so you’re comfortable with what the recursive code is doing. Notice how n is reduced by one each time the method calls itself, and notice how the unfinished calls to the method build up in the Stack window as you go.

Experiment There are many things you could do from here, combining the things we’ve learned so far:

n Call Update from the TextChanged event in Editfield1, so everything gets updated when we change the text;

n Try changing the range of the slider to go up to several thousand. Notice that things start to slow down at this level. You should be able to see that RepeatString2 starts to slow down considerably earlier than RepeatString does. This is because creating and destroying all those variables makes your program do extra work to get to the same result.

n Try creating a different version of Update that only adds or removes enough copies of the string to make it match the slider, as a way of making it handle a larger number of repetitions more efficiently.

An example: if the result string is 2000 characters long, our source string is 2 charac-ters long, and the user moves the slider to 1001, rather than generating the entire 2002-character-long string, we could work out that we need to just add one more copy of the source string to the end. If the user instead moves the slider to 999, we can work out that we only need to delete the last 2 characters.

Hint: To shorten a string, use the Left function. You already know how to lengthen it. Also notice that if the user instead changes the source string, you can’t use this short-cut: you have to build the whole string again, so you’ll probably need two different update methods.

n Try adding a second slider (call it Repetitions2). Get the Results box to display Repetitions1.value copies of the string as a “paragraph”, followed by a couple of returns, then have Repetitions2 copies of the paragraph. You should only need to modify the single line in update to do this, and it will involve building an expression that calls RepeatString twice (so somewhere inside one of the arguments to RepeatString will be another call to RepeatString).

n If you think this is all too easy, try to write a RepeatString3 method that can take two strings (we’ll call them the string and the delimiter — delimiter is a computer term for ‘separator’), and two numbers. The method will return the first number of copies of the string, followed by the delimiter, and will repeat this the second number of times.

63REALbasic Curriculum

Page 64: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Modules, Methods and Recursion

64 REALbasic Curriculum

Page 65: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 6 Arrays and Strings

Aim

In this lesson, we will learn the basics of manipulating strings and how to use arrays. You will also see a simple example of an algorithm.

Say It Once

We are going to make a simple program in which the user types something and then it is displayed in a Message Box — but the program also tracks everything the user enters, and complains if they enter something twice.

1 Create a new project. Add a StaticText, an EditField, and a PushButton to Window1 so it looks like Figure 27 on page 66.

65REALbasic Curriculum

Page 66: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Arrays and Strings

Figure 27. How to set up the window.

2 Set the Title property of the Window to ‘Say Something’. Set the Name of the EditField to Entry, and set the Text property of the StaticText to “Say Something:”.

3 Click the Code Editor button (just below the Project tab) to switch to Window1’s Code Editor. Click the Add Property button in the Toolbar.REALbasic will display the Property declaration area in the code editing area:

Figure 28. The Property declaration area.

66 REALbasic Curriculum

Page 67: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Arrays and Strings

A property is a variable that belongs to an object. It is declared the same way a variable is declared in a Dim command. It automatically exists as long as the object exists. You can also set a default value for the property to have when the object first comes into existence (after the =). By clicking on the three buttons at the right side of the prop-erty declaration, you can set the scope of the property.

From left to right, these are Public (can be accessed from anywhere in the program), Protected (can only be accessed from code in the window you are looking at and any subclasses of this window — we will discuss subclasses in a later lesson) and Private (can only be accessed by code in this window). We will discuss why you might wish to limit the scope of the variable in this way in a later lesson. For now, leave the scope as Public.

4 Enter “Said()” as the name of the property and set its data type to “String”. Leave the last field empty. The property name and its data type are mandatory but the default value is optional.Note that there are no spaces between Said and the opening parenthesis.

About Arrays

What we have just done is to declare an array. An array is a numbered list of data. Each item in the list must be of the same type (in this case, string).

The first element in the array is always numbered zero and when you are declaring the array, you must say what the highest-numbered element will be. Your code can then ask for the nth element’s value, or it can set that value, as long as that number is within the bounds of the array.

You could declare the property as:

and then you’d have an array of 11 elements (starting at 0, and counting up to 10). If we put:

we’d have an array with 1 element. So the way we ask REALbasic for an empty array is by leaving the upper bound blank.

By the way, you’d better get used to counting from 0. It happens a lot in computer pro-gramming.

Add a Function to the Window1 Click the Add Method button in the toolbar. Set the name of the new

method to “AlreadySaid”, declare one parameter as “s as String”, and set the Return Type to “Boolean”.

Said(10) As String

Said(0) As String

67REALbasic Curriculum

Page 68: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Arrays and Strings

The IDE should now look like this.

Figure 29. The AlreadySaid declaration.

Don’t forget that AlreadySaid is one word.2 Enter the following code into the Code Editor.

The Code Editor should now look like this.

//Pre: None//Post: s is an element of Said, no other elements of Said are changed// and if said was already an element, return true, else return false Dim counter As Integer //return true if s is an element of SaidFor counter = 0 to UBound(Said)

If Said(counter) = s thenReturn true

end ifNext Said.append sReturn False

68 REALbasic Curriculum

Page 69: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Arrays and Strings

Figure 30. The AlreadySaid method.

Comments

It is helpful to put comments for people reading the code (including yourself ). You should try to put enough comments to make the purpose of the method fairly appar-ent to someone who is reading that method for the first time.

A comment is written by putting two slashes // in a line. You can put anything you like after the slashes, and REALbasic will just ignore it. You can put comments on their own lines or you can add them to the end of lines of executable code. If you do this, the code to the left of the slashes will execute and everything after the slashes will be treated as a comment.

You can also put as many comment lines in a row (each preceded by //) as you like. Although you can write very long REALbasic lines, you might like to follow the exam-ple above, and break a single sentence or paragraph of comments into multiple com-ment lines.

There are two other ways to write comments, but you should avoid both of them:

n You can type the word REM instead of two slashes; this is just a holdover from older BASICs, and doesn’t stand out from the code as well as the two slashes;

n You can use an apostrophe ' instead of two slashes, but you should avoid this, because it is used in debugging (we will learn more about apostrophe comments in a later lesson).

69REALbasic Curriculum

Page 70: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Arrays and Strings

Pre- and Post-Conditions

If you’re tackling a complex design, you should write Pre- and Post-conditions for your methods, if those conditions are not very obvious.

A pre-condition is something that must be true in order for the code in the method to work correctly. Often, you will design methods to be called at a particular point in the execution of the program, and you should describe what the state of the program should be like in a precondition comment.

A post-condition is something that’s guaranteed to be true after the method has fin-ished running.

In principle, you should be able to prove that all the preconditions of every method in your program will be met, immediately before each method is called. And the post-conditions will help you to do that.

This may seem picky, but you will quickly find that writing large, complex programs without bugs in them is quite difficult1. If you think about proving to yourself that every method’s pre- and post-conditions are being met, at every step along the way, you will be helping to make your programs correct. You can also check the conditions yourself as you are debugging the program2.

In the example above, we have no pre-condition, so it should be legal to run the code at any time. The post-condition tells someone looking at the code precisely what it does.

Return Statements Act as Exit Points

Notice that we are able to Return a value in the middle of running a For loop. This immediately terminates the loop, and the entire method. This means that if we get to the end of the For loop, we know we haven’t found what we were looking for, so then we Return false.

Accessing the Array

Notice how we access a particular element of the array: we put a numeric expression in parentheses after the name of the array: Said(counter). That forms a larger expression whose value is, essentially, now a string variable. It’s a string variable, not just a string , because you can assign a value to it as well as find out its value, just as you can with any other variable.

1. A small computer program might have a few thousand lines of code. One person might write a program with a hundred thousand lines over time, and a major program can be many millions of lines of code. Millions of parts, all different, and virtually every one has to be cor-rect.2. Or add explicit tests for them.

70 REALbasic Curriculum

Page 71: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Arrays and Strings

We don’t directly assign to an array element in the code above, but we can say things like:

if we want to.

There are a number of ways to add elements to, or to remove elements from an array. In this case, we use the Append method of the array to add an element to the end of the array. Look in the on-line help to find other ways of adding and removing elements from an array.

Finally, you can find out the upper bound of an array with the Ubound function, as we do in our For loop. It returns the highest value of index you can legally access. This means that:

would be perfectly valid (assuming there is at least one element in the array), but:

will always cause an error.

Note that since the first element of an array has an index of 0, the number of elements in an array is its UBound + 1.

Finish the program

n Add the following code to the Action event handler for the PushButton in the window:

Run the Program

Now run the program, and observe what it does when you type in something twice. Try using the debugger to observe how the program works (don’t forget to step into the line that calls AlreadySaid). Also, once you’ve run AlreadySaid a couple of times,

Said(Counter) = ""

MsgBox Said(Ubound(Said))

MsgBox Said(Ubound(Said) + 1)

//Pre: None//Post: alert the user if the entry has been entered before, store the entry so we can tell that.

if AlreadySaid (Entry.text) thenMsgBox "You already said that."

end if

//Clear the entry after it's accepted.Entry.text = ""

71REALbasic Curriculum

Page 72: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Arrays and Strings

look at the Variables pane in the debugger, clicking on Self (to view the things in the window rather than the method you’re currently running), then click on the under-lined link next to the variable Said so you can see the array’s contents.

You have to go through this because the debugger shows you where variables and prop-erties live. This means you have to get at the properties of the window from the win-dow’s variables pane. But the variables pane you first see when the debugger activates is the variables for the current method.

This business of Self vs. Me and how you access properties and variables in the debug-ger is a little complex. You might wish to read the REALbasic documentation if you would like more clarification on how it all works.

More on Arrays

In this program, we are treating an array like a mathematical set: it’s a box of things, and we just want to know if a particular thing is in it or not, and to be able to add things to it. The index (the number we provide to indicate which element of the array we want) is just a way of looking through those elements in order.

Try to think of how an array can be used in other ways. For example, an array can be used just like a function from a small range of integers to some value. This would exe-cute very quickly. Many programs will pre-compute the value of some complicated function and store the values in an array, to avoid repeating a lengthy computation.

Experiment

There are many things you could do from here:

n Modify the program to only remember the last, say, 5 things entered;

n Have the program report how many entries ago a repeat was entered;

n Have the program store and check only the first word entered.

n Write a program using an array to accept a series of numbers, then report their sum and mean (average). If your math is up to it, also do the same thing without the array, calculating the sum and mean as you go.

72 REALbasic Curriculum

Page 73: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 7 Algorithms

Aim

In this lesson, we will begin developing and writing algorithms.

What is an algorithm?

The algorithm is one of the most important inventions in computer science. Here is a formal definition of an algorithm:

This definition is adapted from Donald Knuth’s The Art of Computer Programming1. This means an algorithm must be:

n Finite: An algorithm must always terminate after a finite number of steps (although this number can be arbitrarily large, or even unknown);

n Definite: Each step of an algorithm must be unambiguous; and

n Effective: Each step of the algorithm must be possible within a finite period of time.

An algorithm is an unambiguous procedure for performing some task in a finite number of steps.

1. Knuth, Donald E, The Art of Computer Programming, Vol 1: Fundamental Algorithms, 3rd Ed., Addison Wesley Longman, 1997, Reading Mass. ISBN: 0-201-89683-4

73REALbasic Curriculum

Page 74: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Algorithms

Algorithms and Computer Science

Computers were originally developed to perform calculations to produce such things as navigation tables. Later, they were employed to store and produce calculations from business data. In both cases, developing and coding algorithms was really all that com-puter programming was about.

This is no longer the case. Many of the tasks given to computers these days are about decision-making, controlling some continuous process, or running a simulation, rather than completing a finite calculation. There are probably quite a few computers in your car, for example; and think of the number of computers being used to play games. While developing and employing good algorithms is important in developing such programs, there is now quite a bit more to computer programming than just developing algorithms.

Nevertheless, it is traditional in computer science to study algorithms early and in some detail, and we will do the same. The finite nature of algorithms (either they work, or they don’t; you run them and they finish in a certain amount of time) means that they make good, self-contained programming exercises. Their finite nature also makes them very good for examining issues of efficiency (which we will look at in more detail in later lessons).

Also, it works pretty well much of the time to think of control or simulation programs as being repeated application of one or more algorithms.

An example of an algorithm: Counting words1 Start a new, empty project, open Window1, and lay it out like this:

74 REALbasic Curriculum

Page 75: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Algorithms

Figure 31. The Word Counter Window.

From top to bottom, the objects are titled Source, CountButton and WordList. If you like to pretty things up and make the window resizable, a good size setting for the win-dow is 260 x 300. The bottom object is a ListBox. You should read about how to use a ListBox in the REALbasic documentation, although we will discuss the particular fea-tures we use in this program as we go.

Set the Title property of Window1 to “Word Counter”.

Suitable settings for the ListBox are:

The InitialValue property has a tab, not a space, in between the column titles. The best way to enter the column titles is to open the Edit Value dialog by clicking on the but-ton with the ellipsis (three dots) in the value area.

Property Setting

Name WordList

ColumnCount 2

HasHeading True

InitialValue Count Word

75REALbasic Curriculum

Page 76: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Algorithms

Figure 32. The Edit Value dialog box.

Leave all the other values for the ListBox unchanged.

Here is what our program will do: the user types or pastes text into the top box, clicks Count, and the bottom list displays the words in the text, along with the number of times each word occurs.

Now we need to develop an algorithm to do the word counting. We have already learned about all the programming techniques we will need in order to implement this algorithm; what we need to do now is to consider how to put them together.

Starting with a Flow Chart

Drawing a flow chart can be an effective way to begin developing an algorithm. A flow chart is a pictorial representation of the steps involved in carrying out some process. The parts you use to draw a flowchart are shown in Figure 33 on page 77:

76 REALbasic Curriculum

Page 77: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Algorithms

Figure 33. The Elements of a Flowchart.

A flowchart is made by joining the boxes together with arrows. It should have a single starting Terminal, and one or more ending Terminals. You write concise English text in the boxes to describe what to do at each stage, as shown in Figure 34 on page 77:

Figure 34. Troubleshooting flowchart.

Elements of a FlowchartTerminal: Beginning or end of algorithm

Flow line: sequence of steps

Data: input or output

Process: a step to be carried out

Decision: the algorithm continues alongone of two or more paths

No

Troubleshooting flowchart

Yes

Problem

Does it work?

Yes

Don’t mess with it

No problem

No Did you mess with it?

No

Will you pay for it?

Yes

Does anyone know?

Yes

Blame someone else

No

Trash it

77REALbasic Curriculum

Page 78: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Algorithms

The flowchart describes a set of decision-making and computational steps, starting at the beginning Terminal, and following the arrows and boxes, performing the actions and making the decisions in the boxes until an ending Terminal is reached.

Pseudocode

While REALbasic’s programming language is very high-level and efficient for writing code, all computer languages are still fussier about every little detail than we need to be when we’re thinking about an algorithm. What is important when you start develop-ing an algorithm is to get the important decisions in place. You can fill in the specifics, like variable declarations and particular commands later.

It is usually effective to describe an algorithm in a kind of fairly formal, structured English. This should be detailed enough for a person to understand the details of how the algorithm works, and to feel sure that they could code the algorithm in an actual programming language, but no more detailed than that. There are no fixed rules about how to do this, but here is a simple example of pseudo-code:

Figure 35. Troubleshooting Pseudo-code.

You read this by starting at the top and doing the next step each time, unless directed to go somewhere else.

Troubleshooting Pseudo-code1. Does it work?2. If yes, go to 16.3. Did you mess with it?4. If yes, go to 85. Will you pay for it?6. If yes, go to 127. Go to 178. Does anyone know?9. If yes, go to 1210. Blame someone else.11. Go to 17.12. Trash it.13. Go to 17.14. Blame someone else.15. Go to 17.16. Don’t mess with it.17. No problem.

78 REALbasic Curriculum

Page 79: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Algorithms

A Word-Counting AlgorithmNow let’s look at what we need to do to count the number of instances of each word in a string:

n We need to find each word in the string. This requires us to decide what defines a word (is punctuation part of a word, for example?);

n We need to store each word we find in a data structure, along with a count of the number of times we have encountered that word; and

n Each time we encounter a word, we need to see if it is already in the data structure. If it is already in the data structure, we need to increment (add one to) its count; if it isn’t already in the data structure, we need to add it to the data structure with a count of 1.

In developing an algorithm to implement this, we will have four major parts:

n IsWordCharacter: A function that says whether a particular character is a word character or not (if it’s not, we’ll consider it a separator character, and skip over it);

n WordPosition: A function that tells us whether a word has already been stored in our word list and if so, where in the list it is stored;

n AddWord: A method to add a word to the list if it isn’t there, and to increment it if it is; and

n CountWords: A method to search through the string, handing each separate word to the word storage method, and determining where a word begins and ends in part by calling the function that defines what a word character is.

This isn’t the only way to break this problem down; it would be quite possible to write the whole thing as a single method, for example. But this is a fairly natural separation of the parts of this task.

We will keep track of the count in a pair of matching arrays: the word at a particular index in the first array will have the count stored at the same index in the second array. Managing this data structure is an extension of the kind of code we’ve written in previ-ous lessons.

The algorithm to separate the words from the string is more interesting. If you try to write a method to do this, you may find it a little more challenging than you expect.

You will have to write a loop that looks at the letters one at a time, but in doing this, it must decide correctly where a word starts and ends, and it must pass only the charac-ters that are part of the word to the method that stores it.

The strategy we will use is to start the loop each time through in one of two states: InWord or not. (So InWord will be a Boolean variable). Each time through the loop, we look to see whether the next character is a boundary character for the current state (so if we are InWord, look for a non-word character, and if we are not InWord, look for a word character).

79REALbasic Curriculum

Page 80: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Algorithms

When we flip from the not InWord state to an InWord state, we have found the begin-ning of a word, and the opposite means we have found the end of a word. The change of state also marks the end of a word if we are initially InWord. We begin the whole process by looking at the first character to decide which state we start in.

How to Write an Algorithm

You should always think about the following things when writing an algorithm:

n The preconditions for the algorithm, meaning what has to be set up before the algorithm can run. In our case, we need a string, and we need methods that can store the words as we find them.

n The postconditions for the algorithm, meaning what changes to the state of the program outside of the method itself have occurred after the algorithm has finished. You should always be able to specify this very clearly. In this case, the only change made after the program runs is that the words have been passed to the storage method. But the method might have made other changes to the overall state of the program, so we need to note such changes if there are any.Note that the algorithm changes the value of the Counter variable, but since this is a local variable, it disappears after the method ends, so we don’t need to worry about it.

n The conditions we have to keep making true as the algorithm executes; there may be several stages where you repeatedly carry out different actions. In this case, we are incrementing counter, and passing a word to AddWord every time the counter points to the end of a word.

Algorithms can also use sub-algorithms, which solve a smaller part of the overall pro-gram. We have a sub-algorithm in our case, contained in the For loop in CountWords. It, too, can be considered in the terms described above:

Preconditions for the loop:

n The string must not be empty;

n Counter = 1;

n InWord is True if the first character is a word character, False otherwise.

Postconditions for the loop:

n Counter is 1 greater than the length of the string;

n We have not emitted the last word of the string, if the string ends with a word character.The loop invariant, which is the thing we keep making true at the end of the loop, is similar to the one for the entire algorithm, except that it doesn’t send the last word to the AddWord method if the string ends at a non-word character.

80 REALbasic Curriculum

Page 81: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Algorithms

Our algorithm as a flowchart

Figure 36. Our algorithm as a flowchart.

Exercise: Translate the flowchart into pseudo-code

Try to translate Figure 36 into pseudocode, to see if you’ve followed what we’ve dis-cussed so far.

Begin

Counter = 1

Length of String > 0?

Done

No

Yes

InWord = IsWordChar (CurrentCharacter )

InWord? WordStart = 1Yes

Counter > Length of String? InWord?Yes

InWord?

No

IsWordChar (CurrentCharacter )?Yes

IsWordChar (CurrentCharacter )?

No

Store the Word

No

Yes

Counter = Counter + 1

No

No

Store the Word

Done

Yes

No

No

81REALbasic Curriculum

Page 82: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Algorithms

The actual code

Here is the actual CountWords method, which you should add to your window:

//Pre: None//Post: Word array contains all of the words in Source;//Count array contains corresponding count of those words in Source

Dim InWord As BooleanDim counter, WordStart As Integer

if Len(Source.text)>0 then //If source is not emptyInWord = IsWordCharacter (1)//Inword invariant (below)If InWord then//Wordstart invariant (below)

WordStart = 1end if

for counter = 1 to Len (Source.text)//Invariants:// Inword: InWord is true if the counter character of Source.text was

IsWordCharacter//WordStart: WordStart is the last counter character such that the

character before it was not IsWordCharacter

if InWord thenif not IsWordCharacter (counter) then

AddWord (Mid (Source.text, WordStart, counter-WordStart))InWord = false //InWord invariant

end if//WordStart invariant: InWord implies we don't need to change

WordStart

else //not InWordIf IsWordCharacter (counter) then

InWord = true //InWord invariantWordStart = counter //Wordstart invariant

end ifend if

nextend if

//The loop doesn't detect the end of the string as a boundaryIf InWord Then

AddWord(Mid(Source.text, WordStart, counter-WordStart))End If

82 REALbasic Curriculum

Page 83: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Algorithms

This code is written with a very formal description of the preconditions, the postcon-ditions, and the loop invariants in the comments. We’ve actually named the loop invariants, and tried to prove where in the loop we made them true.

Doing this is overkill for this fairly simple exercise, but you should employ something like this (or at the very least, try to think like this) for any more complex algorithm you try to produce. The closer you can come to proving your code is correct before you run it, the fewer bugs you will produce in your code.

2 Add the following properties to the window: Count() As Integer and Word() As String.

3 Add the following function to the window:

The Code Editor for the IsWordCharacter function should look like this:

Figure 37. The IsWordCharacter method.

Function IsWordCharacter (n As Integer) As Boolean//Pre: None//Post: If the character at location n in Source is a letter or number,

Return True//else return false

Dim c As String

c = Mid (Source.text, n, 1)Return (c>="0" and c<="9") or (c>="A" and c<="Z") or (c>="a" and c<="z")

83REALbasic Curriculum

Page 84: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Algorithms

Separating something like this into its own method is a good idea. We can easily change what defines a word by changing this single method (perhaps making it depend on some preference settings). It also makes the word counting method shorter and simpler, since it doesn’t need to include this code. In a more complex project, you also might be able to re-use this method in other string processing code.

4 Add the following function to the window:

Make sure you can follow what this method does.1

5 Add the following method to the window:

Function WordPosition (w As String) As IntegerDim counter As Integer//Pre: None//Post: Returns the array index within the Word array if it is there, or -1 if

it is not.

For counter = 0 to UBound(Word)If Word(counter) = w then

return counterEnd if

Next

Return –1

1. Note that REALbasic provides an IndexOf function that does the same thing as this func-tion, for any array. We will sometimes write our own version of a built-in function, for the purposes of learning.

Sub AddWord (w As String)//Pre: Count and Word arrays have same number of elements//Post: if w is in Word array, the value of Count at the same index is

incremented//otherwise, w is appended to Word array, and 1 is appended to Count

array//ie we are maintaining a count of the words submitted to this method,

in the two arrays

Dim position As Integer

position = WordPosition(w)If position = -1 then

Word.append wCount.append 1

ElseCount(position) = Count(position) + 1

End if

84 REALbasic Curriculum

Page 85: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Algorithms

You should note that breaking WordPosition out into a separate function allows the rest of the code to be independent of how the data is represented. It’s a very good idea to keep assumptions like ‘these characters are all of the word characters’ quite separate from the code that uses them.

6 Add the following to the Action event handler for CountButton:

As you will have read if you looked up the ListBox control in the built-in documenta-tion, the ListBox is for displaying information in a grid or list. Among its many fea-tures are the AddRow method, which adds a new row and sets the contents of the first column; and the Cell property, which lets you set the contents of individual cells in the grid. The two lines in the above For loop, then, add a new row to WordList.

Run It

We’re done. As usual, you should run the program and try it out. Also try inserting BreakPoints and stepping through the code to watch it in action.

Experiment

There are many ways of extending the project from here. A few, in rough order of diffi-culty, are:

n Change the code to ignore numbers (remember how we detected whether a string was a number in an earlier lesson?);

n The code provided is case-insensitive (that is, capital and lower case letters are considered the same when comparing strings), because that’s how the regular = operator works in REALbasic. You can do case-sensitive comparisons with the StrComp function. Try adding a checkbox to the window that lets the user choose whether to make the word count case-sensitive or not;

n Add a separate display of the most common word and its count. There are two obvious ways of doing this (after the array is constructed, and as the array is constructed); and

n You might try making the list sort properly when the column headers are clicked on. This is as actually fairly easy to do, but you’ll need to read the documentation on the ListBox to figure it out. Reading documentation is an important skill you should start learning now, anyway.

//Execute CountWords, then copy the results into WordListDim counter As integerCountWords

For counter = 0 to UBound(Word)WordList.AddRow Str(Count(counter))WordList.Cell(counter,1) = Word(counter)

Next

85REALbasic Curriculum

Page 86: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Algorithms

Conclusion

Developing algorithms is much of what computer science is about, and developing an algorithm is more art than science. Mostly, it just takes practice, and reading about algorithms, to learn to do it. In this lesson, we’ve tried to give you a few guidelines, and an example of how to think about developing an algorithm.

This is good, formal computer science, and there is a lot of discussion to be found online about these and other design virtues. A nice one to be found fairly quickly through a google search is:

http://cs.colgate.edu/faculty/nevison.pub/web102/web102S00/Notes8.htm.

86 REALbasic Curriculum

Page 87: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 8 Abstract Data Types

Aim

In this lesson, we will begin looking at object-oriented programming. We begin this by examining how and why we should create our own data types.

What is an Abstract Data Type?

Formally, an Abstract Data Type (ADT) consists of a set of operations, which are the only way for other code to access some particular data. The ADT defines a type, and the data is said to be of that type.

The benefit that this provides is that it separates implementation from interface. In tra-ditional object-oriented programming terms, this is called encapsulation. You may also hear that an ADT abstracts the details of data, and provides information hiding.

Encapsulation provides three benefits:

n We can develop and debug the Abstract Data Type separately from the rest of the program;

n We can change the implementation of the Abstract Data Type without having to change any code that calls it; and

n We can provide access to several similar types of data sources from one set of code, without addressing the details that distinguish the types of data.

87REALbasic Curriculum

Page 88: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Abstract Data Types

These benefits are a first glimpse at something we are going to be looking at repeatedly throughout this course: we want to be able to break a complex program down into well-separated parts that can be developed, debugged, improved, and changed sepa-rately.

The second benefit also allows us to approach development in an incremental fashion: we can implement an ADT in a quick-and-dirty fashion in order to get the program working, then go back later and make it faster, use less memory, or provide extra fea-tures.

Pre- and Post-Conditions

We saw preconditions and postconditions briefly in the last lesson. You should employ these concepts in defining an Abstract Data Type: you should state as simply and accu-rately as possible what each operation provided by an Abstract Data Type does, in terms of what should be true before you execute that operation, and what will be dif-ferent afterward.

‘Object-oriented’ means built-in support for ADTs

If you have used other programming languages before, you should know that you can employ the benefits of ADTs in virtually any programming language. However, object-oriented programming Languages such as REALbasic provide built-in features that explicitly support creating Abstract Data Types, as we will see.

Improving The Word Counter with ADTs1 Make a copy of the Word Counter project. Open it.

We are going to make a version of the Word Counter that counts the text on the Clip-board. We are going to make it get the text from an Abstract Data Type.

2 In the Project Editor, click on the Add Class button. You will then see a new icon in the Project Editor, and the Properties pane will be ready for you to set its properties:

Figure 38. The Properties for the CharacterSource class.

The only property you should change now is the Name, which you should set to Char-acterSource, as shown in Figure 38.

88 REALbasic Curriculum

Page 89: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Abstract Data Types

You have just declared a new type of data you can store in variables and properties in your program. The next step is to provide it with suitable methods and properties so we can use it as a source of data for our word counter.

3 Double-click on the icon for the CharacterSource class, to open its Code Editor.

4 Click on the Add Property button, and give the new property the name “ClipBoardSource” and data type of “ClipBoard”:

5 Click again on Add Property and give the new property the name “CurrentPosition” and data type of “Integer”.

Object References versus Scalars

This is the first time we’ve stored an object in a property or a variable. The ClipBoard type that we just declared for our ClipBoardSource property is an object, which is a dif-ferent kind of thing to the strings, numbers and Booleans we’ve kept in properties and variables until now.

Properties in REALbasic can store two quite different types of things: scalars and object references. Scalars just have a value. Once you’ve declared the variable, you can start working with its value.

An object reference is different: it tells REALbasic where in its memory to locate an object. When you declare the variable or property, you’ve just declared somewhere to keep an object’s location (and you’ve said what type of object will be there), but you haven’t actually created an object. A variable or property declared to be an object ini-tially has the special value Nil, meaning it points at nothing.

Before you can actually do something with an object, you have to get the variable or property to refer to it. In this case, we need to ask REALbasic to create an object, and provide a reference to it that we can store in our variable.

This is the only way to access objects in REALbasic. Although it may seem a little strange, this is actually a natural way to work with objects, and it will soon become sec-ond nature.

1 Click the Add Method button, and name your new method Begin and don’t give it any parameters or a return value. Set its code to:

This method must be called before our Abstract Data Type can be used (we’ll see a better way to initialize an object in a later lesson).

2 Add the following methods to the class:

//Must be called before the object can be usedCurrentPosition = 0ClipBoardSource = New Clipboard

89REALbasic Curriculum

Page 90: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Abstract Data Types

Function CurrentChar as String

Function Finished as Boolean

Function Length As Integer

Each of these functions takes no parameters but each has a return value.You’ll probably need to look up a few REALbasic features (such as Len and Mid, as well as the features of the ClipBoard object) to follow this code. Notice that we can just return the results of a Boolean expression (in the Finished function).Can you see how the methods we’ve implemented here provide everything we need to loop through the string on the clipboard? Notice also that any code calling these methods doesn't need to know anything about the source of the string.

3 Add a property to the Window and name it “ClipBoardSource” and give it the data type of “CharacterSource”.

4 Change the parameter passed to IsWordCharacter to “c as String” and change its code to:

//Pre: Begin has been called since the clipBoard changed;//This method is not called more often than the length of the clipBoard

text//Post: each time this method is called, the characters on the clipBoard

text are returned in order

CurrentPosition = CurrentPosition + 1Return Mid (ClipBoardSource.Text, CurrentPosition, 1)

//Pre: Begin has been called//Post: return true if the last call to CurrentChar returned the last

character of the clipBoard text, else return false

Return (CurrentPosition > Length+1)

//Pre: Begin has been called//Post: the length of the text on the ClipBoard is returned

Return Len (ClipBoardSource.text)

//Pre: None//Post: If c is a letter or number, return true, else return false Return (c>="0" and c<="9") or (c>="A" and c<="Z") or (c>="a" and c<="z")

90 REALbasic Curriculum

Page 91: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Abstract Data Types

Modify your CountWords method to read:

You can see here that we can call methods and functions from classes we create, exactly the same as we do with the built-in classes.

//Pre: None//Post: Word array contains all of the words in ClibBoardSource;// Count array contains corresponding count of those words in ClipBoardSourceDim InWord As BooleanDim c, StringBuffer As String// Initialize ClipBoardSourceClipBoardSource = new CharacterSourceClipBoardSource.Begin // c Invariant, starting *before* first characterInWord = false //Inword InvariantStringBuffer = "" //StringBuffer Invariantwhile not ClipBoardSource.Finished

//Invariants:// c: c is the next unprocessed character in ClipboardSource// StringBuffer: StringBuffer holds the string of characters that will be the next word

to be added to our list; after it is added, or between words, this string is empty// Inword: InWord is true if the counter character of Source.text was

IsWordCharacter//Note: Other than StringBuffer, we only need to act on word boundariesc = ClipBoardSource.CurrentChar //c invariant

if InWord thenif not IsWordCharacter (c) or ClipboardSource.Finished then //Word

End; emit wordAddWord StringBuffer //StringBuffer InvariantStringBuffer = "" //StringBuffer InvariantInWord = false //InWord invariant

elseStringBuffer = StringBuffer + c

end if

else //not InWordIf IsWordCharacter (c) then //WordBegin; start buffering

InWord = true //InWord invariantStringBuffer = StringBuffer + cif ClipBoardSource.Finished then

AddWord StringBufferend if

end ifend if

Wend

91REALbasic Curriculum

Page 92: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Abstract Data Types

It is important to recognize the difference here between the type or class (Character-Source) and an instance of that type (ClipBoardSource). There is an analogy in real life: Tom Cruise is an instance of the actor class; or New York is an instance of the city type. Computer programmers might also use a kind of shorthand and say that ‘New York is an instance of city’.

The While Loop

We’ve introduced a new type of loop above: a While loop. It has a similar form to a For loop, but it starts with a While statement — consisting of the word While followed by a Boolean condition — and ends with the word Wend. It tests the condition, executes the code inside the loop, and repeats these two steps over and over until the condition is false.

How is the ADT Code an Improvement?

We’ve changed the source of the text for our word counter, but that’s not an improve-ment: it’s a feature change. How is this method of writing the word counter an improvement?

When we write computer code, we generally want to do these things:

n Correctly implement the desired behavior;

n Implement the desired behavior, fully debugged, as quickly as possible; and

n Make the code as easy to modify as possible.

We will sometimes1 also want to:

n Make the code run using a minimal amount of some resource (time, memory, bandwidth and so on).

The code in this project is an improvement over the code in the last project because it better satisfies the easy to modify requirement. This benefit isn’t immediately apparent, but we will see in coming lessons how easy it is now to make our word counter work with different data sources.

This is a very good general design principle: any data structure you build should come with a layer of interface code. This code should provide the features the rest of the pro-gram needs in order to use that data, but should hide all details of how the data is actu-ally stored.

1. It is a very common mistake among programmers to obsess about “efficiency” in a lot of situations where it just doesn’t matter.

92 REALbasic Curriculum

Page 93: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Abstract Data Types

The ADT Advantage

It’s important to see at this point what we’ve done by using an ADT for this project: CountWords needs to know nothing about the source of the words it is counting. Instead, we’ve pared down the features it needs to do its job to the absolute minimum. Now, we can count the words in any source of text by implementing a very simple interface to that text. We need not modify CountWords at all. We can, in a sense, ‘plug in’ a source of text to CountWords. In this case, it is the text on the Clipboard.

We will see in coming lessons how cleanly object-oriented programming supports this ability to ‘plug things together’.

An Exercise

There is another data structure in our program: the pair of arrays that keeps the words and their counts. Try to implement this as an ADT.

93REALbasic Curriculum

Page 94: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Abstract Data Types

94 REALbasic Curriculum

Page 95: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 9 Polymorphism

Aim

In this lesson, we start learning to use polymorphism, which lets us take advantage of similarities between objects to simplify code.

How To Use This Lesson

You my find that you need to go back over this lesson a few times. Some of this may seem strange or even counterintuitive the first time through.

What is Polymorphism?

Polymorphism, broadly speaking, is the ability to treat similar things in similar ways. Here’s how it works in REALbasic (minus one or two details we will learn about in later lessons):

n As we saw in the last lesson, all objects must have a class;

n Classes are placed in a tree-shaped class hierarchy (each class having one superclass and as many subclasses as you wish);

n Classes inherit all the methods and properties of their superclass;

n Each class is its own type, but classes are also of the type of their superclass, the superclass of their superclass, the superclass of that, and all other superclasses reaching to the root class of the whole class hierarchy, the object class.

95REALbasic Curriculum

Page 96: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Polymorphism

n You can treat an object as an instance of any of its types. This means, for example, that you can treat all the controls in a window as RectControl objects, because all controls are subclasses of the RectControl object. You could move all of them around, for example, without needing to write different code to handle each different type.It is this last capability that is polymorphism: we can put shared behavior into a shared superclass, and write code that deals only with shared features of objects, ignoring their differences.

Properly used, polymorphism will let us reduce the amount of code we must write and debug, and to reduce the amount of work required to maintain and extend a program. However, polymorphism is a subtle feature, and learning to use it well requires both understanding and experience. Much of what we will be doing in this course is to get you on the road to using object-oriented programming effectively, and much of that comes down to using polymorphism effectively.

It will take us several lessons to cover all of REALbasic’s object-oriented programming (OOP) features. In this lesson, we will learn about class hierarchies, and about using events to extend a superclass. We will also be modifying the word counter from previ-ous lessons so it can work with different sources of text without further modification.

An Example of a Class Hierarchy

Here is a diagram of part of the built-in REALbasic class hierarchy:

Figure 39. A part of the built-in class hierarchy.

A couple of examples from this diagram: Object is a superclass for all the other classes; Control is a subclass of Object, and a superclass for Line, RectControl, PushButton and EditField.

Sometimes, it might be necessary to distinguish the immediate superclass of a class: RectControl is the immediate superclass of PushButton, for example. On other occa-sions, the immediate superclass of a class will just be called its superclass. Exactly which meaning of superclass is intended should be obvious from context.

Our Class Hierarchy

As another example, here is the class hierarchy we’re going to create in this lesson:

Object

Control FolderItemDialog

ContextualMenu SaveAsDialog OpenDialog

PushButton EditField

RectControl

96 REALbasic Curriculum

Page 97: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Polymorphism

Figure 40. The class hierarchy for this project.

The Polymorphic Word Counter

Let’s get to a working example:1 Open the project from the last lesson.

Remember how we wrote the word counting code to get its data from an Abstract Data Type? We’re going to modify our project now so that data source is an object of a particular class. We will then make the one word counter method able to get its data from any subclass of that class.

2 Open the CharacterSource class. We’re going to change it so it doesn’t do anything. Seriously.

Inheritance, Polymorphism, and Abstract Classes

We’re going to turn CharacterSource into an Abstract base class. Its role will be to define an interface for an Abstract Data Type. We will rely on subclasses to provide the actual behavior wanted. You won’t ever create a CharacterSource object as such (because it wouldn’t do anything). You’ll create an object of one of CharacterSource’s subclasses, but our CountWords method will treat that object as a CharacterSource and not need to know what the object actually is.

1 Add four Event Definitions to the class. Do this by clicking the Add Event Definition button once for each event definition. This opens an declaration area with the same options as you have for creating a new method. Name the following four Event Definitions as follows:

Events

Event Definitions provide a means for code defined in the superclass to call code defined in the subclass, without having to know anything about the subclass.

Object

CharacterSource

ClipboardSource FileSource

Event NameReturn Type

BeginEvent (none)

CurrentCharEvent String

FinishedEvent Boolean

LengthEvent Integer

97REALbasic Curriculum

Page 98: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Polymorphism

What we are going to do now is to modify the methods in this class to do nothing but call the events we just defined; we are then going to create two subclasses, one to return text from the Clipboard, and another to return text from a file.

2 Delete the ClipBoardSource property from CharacterSource.You can select each property in the Code Editor browser area and then right+click (Command-click on Macintosh) and select Delete from the contextual menu.

3 Modify the methods in CharacterSource to read:

4 Switch to the Project Editor and click on the Add Class button. Name the new class ClipboardSource and enter CharacterSource as its Super.

5 Double-click on the class to open its Code Editor. Expand the Event Handlers in the pane on the left.We see the four events we just defined here automatically because this class is a subclass of CharacterSource.

6 Add the property we just removed from CharacterSource:

7 Enter the following code into the four Event handlers

BeginEvent:

Function CurrentChar() As StringReturn CurrentCharEvent()

Function Finished() As BooleanReturn FinishedEvent()

Function Length() As IntegerReturn LengthEvent()

ClipBoardSource As Clipboard

//Pre: None//Post: CurrentPosition == 0

CurrentPosition = 0ClipBoardSource = New Clipboard

98 REALbasic Curriculum

Page 99: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Polymorphism

CurrentCharEvent

FinishedEvent

LengthEvent

8 Modify Window1 to look like this:

//Pre: Begin has been called since the clipBoard changed;// This method is not called more often than the length of the clipBoard

text//Post: each time this method is called, the characters on the clipBoard

text are returned in order

CurrentPosition = CurrentPosition + 1Return Mid (ClipBoardSource.Text, CurrentPosition, 1)

//Pre: Begin has been called//Post: return true if the last call to CurrentChar returned the last

character of the clipBoard text, else return false

Return (CurrentPosition > Length)

//Pre: Begin has been called//Post: the length of the text on the clipBoard is returned

Return Len (ClipBoardSource.text)

99REALbasic Curriculum

Page 100: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Polymorphism

Figure 41. The Word Counter window.

9 Change the name of the top PushButton to “CountClipButton” and Caption to “Count Clipboard”.

100 REALbasic Curriculum

Page 101: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Polymorphism

Now, we need to modify CountWords to work with a CharacterSource given to it as an argument. Change its declaration so that it is passed one parameter, “Source as Char-acterSource”.:

//Pre: None//Post: Word array contains all of the words in Source;// Count array contains corresponding count of those words in Source

Dim InWord As BooleanDim c, StringBuffer As String

Source.Begin // c Invariant, starting *before* first characterInWord = False //Inword InvariantStringBuffer = "" //StringBuffer InvariantWhile Not Source.Finished

//Invariants:// c: c is the next unprocessed character in Source// StringBuffer: StringBuffer holds the string of characters that will be

the next word to be added to our list; after it is added, or between words, this string is empty

// Inword: InWord is true if the counter character of Source.text was IsWordCharacter

//Note: Other than StringBuffer, we only need to act on word boundaries

c = Source.CurrentChar //c invariant

if InWord thenif not IsWordCharacter (c) or Source.Finished then //Word End; emit

wordAddWord StringBuffer //StringBuffer InvariantStringBuffer = "" //StringBuffer InvariantInWord = false //InWord invariant

elseStringBuffer = StringBuffer + c

end if

else //not InWordIf IsWordCharacter (c) then //WordBegin; start buffering

InWord = true //InWord invariantStringBuffer = StringBuffer + cif Source.Finished then

AddWord StringBufferend if

end ifend if

Wend

101REALbasic Curriculum

Page 102: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Polymorphism

10 Set the Action event handler of the Count Clipboard button to:

11 Put a breakpoint at the top of the Action event handler we just created, put something short (a few characters will do) on the Clipboard, run the program, and step through the process of executing the code in the CharacterSource and the ClipboardSource classes.You’ll see that the methods that CountWords calls from its Source argument go first to the methods in CharacterSource, then ‘down’ to the event handlers in the Clipboard-Source subclass. Functions return their results in the opposite order: back to the Char-acterSource function that called the event handler, then out to CountWords where the original method was called.

Classes vs. Objects

It is important to be clear on terminology here: the class is the definition of what an object does; the object is the actual usable thing we create when our program runs. The object contains data and does the things the class defines. We say the object is an instance of the class.

An object is always an instance of more than one class: in this case, Source is an instance of both ClipboardSource and CharacterSource. Within the button’s Action event handler, we treat it as a ClipboardSource, because we need to create a fully func-tional, non-abstract class that actually does things. However, CountWords has a Char-acterSource variable as its argument. When we call CountWords, its Source argument ends up pointing at the same object we just created (remember our discussion about how object variables don’t contain an object, but only refer to them?).

Polymorphism in Action

This is polymorphism in action: we could pass CountWords any class that has Char-acterSource as its superclass, without further modifying the CountWords method. Any details required to make it work with a particular source of data will be provided in the event handlers of the particular CharacterSource subclass in question.

//Execute CountWords on the clipboard, then copy the results into WordList

Dim counter As integerDim Source As ClipBoardSourceSource = New ClipboardSource

CountWords(Source)

For counter = 0 to UBound(Word)WordList.AddRow str(Count(counter))WordList.cell(counter,1) = Word(counter)

Next

102 REALbasic Curriculum

Page 103: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Polymorphism

This means we can debug CountWords in isolation, and also reduce the amount of code we need to write to count words coming from a new source of data. We will see that right now in the code to implement the Count File… button’s behavior.

More on Events

Events are the most important extension mechanism in REALbasic. The events you define and intercept in classes are the same mechanism as the event handlers we’ve been writing for controls. You could create your own, specialized button class, for example, by creating a new class, setting its Super to PushButton, and then providing code in its Action or other event handlers. You can also define new events in your new class that will be available to any further subclasses, and to any instance of that button that you drag from your project window into a Window you create.

Events as an extension mechanism are unique to REALbasic. Other object-oriented programming languages use a very different extension mechanism called method over-riding. Method overriding is also available in REALbasic, and we will learn about it in later lessons. Don’t look for much advice on how to use events, or when to use events instead of method overriding. Apart from what we will develop in this course, and what you may find on the internet by other REALbasic programmers or in the few books on REALbasic, there isn’t any.

The File Counter

Now, we’re going to create the code to make the Count File… button work. As usual, if you need to, look up the information on how to handle files in REALbasic, in the built-in reference.

1 In the Project Editor, create a new class. Name it FileSource, and set its Super to CharacterSource.

2 Open the class’s Code Editor and add the following properties:

3 Add the following code to the Event Handlers:

BeginEvent

CurrentCharEvent

Name Data Type

CurrentPosition Integer

TheStream BinaryStream

CurrentPosition = 0TheStream.position = 0

CurrentPosition = CurrentPosition + 1Return Chr(TheStream.ReadByte)

103REALbasic Curriculum

Page 104: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Polymorphism

FinishedEvent

LengthEvent

A Minor Issue

We wrote our own means of detecting the end of file in the code above (keeping a Cur-rentPosition count, and comparing it to the file length). The BinaryStream provides both a Position property and an EOF property, but the way they are implemented doesn’t suit our purpose. EOF is True before we’ve read the last character, and Position will be equal to the length of the file both before and after reading the last character. So we can’t write a proper While loop based on either of these properties. For example, if we wrote:

we wouldn’t return the last character in the file. If we wrote:

we would have the same problem. Other ways of using these built-in mechanisms can be devised to read the last character, but without making them fairly complicated, they will fail if we try to use a zero-length CharacterSource (try it!).

This isn’t a huge issue, though; we just wrote our own mechanism.1 Add the following method to the FileSource class:

Return CurrentPosition > Length

Return TheStream.Length

Function FinishedEvent() As BooleanReturn TheStream.EOF

Function FinishedEvent() As BooleanReturn TheStream.Position = TheStream.length

Sub SetFile(f As BinaryStream)TheStream = f

104 REALbasic Curriculum

Page 105: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Polymorphism

2 Add the following code to the Action event handler for the Count File… button:

Notice how we added an extra method to our class. Objects of type CharacterSource are guaranteed to support four methods (Begin, CurrentChar, Finished and Length), but objects of type FileSource support an extra method (SetFile). Notice how the but-ton knows that it is working with a FileSource, so it can set the file, but CountWords doesn’t know about this extra method, and doesn’t need to.

File Types

We need to tell REALbasic what types of files it should be trying to open. You should read Chapter 8 of the User’s Guide for more information about File Types.

1 Choose Project . Add . File Type Set. You will see a new FileTypes icon in your Project tab. Double-click on it to see the File Type Sets Editor:

//Ask user for a file, then execute CountWords on that file, //and copy the results into WordListDim Counter As IntegerDim Source As FileSourceDim f As FolderItemDim s As BinaryStream

Source = new FileSource

//Request filef=GetOpenFolderItem("application/text")

If f<>Nil thens = f.OpenAsBinaryFile(False)

Source.SetFile s

CountWords(Source)

For Counter = 0 to UBound(Word)WordList.AddRow str(Count(counter))WordList.cell(counter,1) = Word(counter)

NextEnd if

105REALbasic Curriculum

Page 106: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Polymorphism

Figure 42. The File Types Set editor.

2 Click on the Add File Type button to add a new row to the list. Enter the following information:

Try It

That’s it. You might like to trace through reading a (very short) file.

Review

We’ve seen the basics of implementing a class hierarchy, and of employing polymor-phism. You should go back and re-read the introductory material discussing the fea-tures we used in this program. Focus on how the class hierarchy and the events mechanism enable us to treat two different classes the same. Notice how this is an extension of the idea of the Abstract Data Type.

Object-Oriented Design

A major theme of this course is how to design applications as cleanly separated parts that let us develop and debug parts of complex programs quite separately. We saw how methods and particularly Abstract Data Types help us to do this. Inheritance and

Field Value

Display Name application/text

Object Name applicationText

MacType TEXT

MacCreator ????

Extension .1st;.nfo;.readme;readme;.txt

106 REALbasic Curriculum

Page 107: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Polymorphism

Polymorphism take this idea further: you can not only implement different ADTs sep-arately, but you can develop and debug behavior shared between objects that imple-ment the same ADT once. Good object-oriented design will often have a lot of its code placed toward the top of class hierarchies, which means that a lot of the code in the program is generalized and shared.

Achieving this sort of efficiency of design is as much art as science. It takes years of programming experience, and a lot of looking at well-written object-oriented code to develop good object-oriented design skills.

Explanations/References

Events are discussed in Chapter 5 and in the Adding Event Definitions section of Chapter 9 of the REALbasic User’s Guide.

Unfortunately, the REALbasic User’s Guide only discusses polymorphism using the other mechanism (‘virtual methods’, which we’ll cover later). But note that if you read the Adding New Events section of Chapter 9, what it is describing is polymorphism.

We’re deliberately taking this slowly, so a really good understanding of these issues will have to wait until we’ve done some more lessons.

One of the important design principles we want to adhere to is that superclasses should need to know nothing about their subclasses; by defining an event and calling it, a superclass is defining a way to communicate with its subclass, whatever it may be, while being suitably ignorant about the details of that class.

If you read Chapter 9, it may help to understand that the Virtual Methods mechanism described there is another way to have communication occur between subclass and superclass (but in that case, you put the subclass in control). We’ve started with events, because you need those to subclass controls, and we’ll just stick with events for a while, since we want to keep things simple.

Further Exercise

Try adding a TextBoxSource that counts the contents of an EditField. Note that since EditField is already a class, and because you can only define one superclass for a class, you can't make a subclass of Editfield that is also a CharacterSource. Instead, you will have to write a kind of adapter class that includes a SetTextBox method, similar to File-Source’s SetFile.

107REALbasic Curriculum

Page 108: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Polymorphism

108 REALbasic Curriculum

Page 109: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 10 Eliza

Aim

In this lesson, we will put together a program to exercise our new programming mus-cles. We’re going to stick mostly to things we’ve been using for a while, not venturing into the new ADT and polymorphism material. We’re just trying to see what a slightly more complex program looks like.

What is Eliza?

Eliza is a classic computer program. The program pretends to chat with its user, acting as a psychiatrist or counselor. The user types plain English, and the program seems to respond intelligently in English.

The program does this by looking for particular words or phrases in the text entered by the user. If it finds a match, the program responds with a matching question or statement. If the program doesn’t find a match, it responds with a request for more information or with some other generic phrase.

Planning the Program

We have to implement several different things to make this program work. We need to provide:

n A way to get the phrases searched for and the responses to them into the program;

109REALbasic Curriculum

Page 110: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Eliza

n Storage and retrieval of the search phrases and responses; and

n The user interface and the logic that implements the actual questions and responses.Try to decide how you would do these things before you go on.

Loading the Phrases from a File

We will load the phrases from a text file on the disk. We’ve seen how to read a file before, but this time, we have to store some structured information in the file.

The file will be able to contain multiple responses. Each response will consist of one or more words or phrases to search for, and one or more suitable responses.

This means we need to separate:

n Each response from the next;

n Within a given response, the phrases to search for from the responses; and

n Within the phrases and responses, the individual search terms or responses from each other.

We will do this by having each response on a separate line in the file. We will then sep-arate the search phrases from the responses with a tab. Finally, we will separate the individual search phrases from each other, and the individual responses from each other, with a slash (/). So a single line from the file might look like this (the big space in the line is where the tab is):

We will indicate the random responses, to be given when there is no match, by a line that is empty before the tab.

ASCII Characters and Unicode

Computers represent letters as numbers. There are two ways of doing this in REALba-sic:

n Using the ASCII (American Standard Code for Information Interchange) character set, a set of 127 characters, including upper and lower-case Roman letters, numbers, punctuation and a few others, including some non-printing “control” characters (like tab); and

n Using the Unicode character set, a much larger character set, intended to encompass every symbol needed to represent every language on Earth, as well as a great many other symbols.

mum/mom/mother Tell me more about your mother./What does this tell us about your mother?

110 REALbasic Curriculum

Page 111: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Eliza

ASCII is an old standard. It is important for two reasons: 1) compatibility with other systems; and (2) because ASCII characters fit into a single byte1.

Unicode is a new standard for text on major computer systems. It is important because most people in the world need more than just the Roman character set to communi-cate. The only significant disadvantage to Unicode is that it requires two bytes to rep-resent each character, so it takes twice as much space to store text in Unicode, and it is a little slower to process as well.

Unicode has been designed so that the first 127 characters are the same as the ASCII character set.

REALbasic stores strings internally in ASCII if the operating system it is running on uses Roman characters, and in Unicode on other systems. Its regular string operations operate on ASCII or Unicode characters accordingly. There are also ‘B’ versions of all the operations (AscB and so on), which work on bytes only. Consult the built-in refer-ence for more information.

For our purposes, we just need to be able to identify two non-printing characters, which we will do with the Chr function (which you should look up).

StringResponder

Let’s begin. Since this is a fairly simple program, we will put most of the features in a single class.

1 Create a new project. Add a new class, with no Super and with its name set to “StringResponder”. Open its Code Editor.

2 Add the following properties:

3 Create a new method and name it “LoadFromFile”, with parameters “f As FolderItem, ElDelimiter As String, RespDelimiter as String”). It has no return type.

4 Enter the following code for LoadFromFile.

1. For the uninitiated, a byte is the standard unit of computer storage space; it consists of eight binary digits (bits, each of which is a 1 or a 0), and is capable of representing any of 256 different values (say, numbers in the range 0 to 255). Various schemes are used to get (often, many) bytes to represent larger numbers, fractions and text.

Name Data Type

RandomResponse() String

RespondWith() String

SearchFor() String

111REALbasic Curriculum

Page 112: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Eliza

You should look up the string functions we haven’t seen before, such as NthField and Trim.

This method looks longish, but REALbasic’s string commands actually make it pretty straightforward: we separate the two major parts of the line, then just loop over the parts of each. We separate the storage of the information into methods such as Add-Response.

5 Add the following methods:

//Pre: f is a valid text folderitem, delimited as described below.//Post: Records, delimited by Chr(13), are loaded into the responses,//with response delimited from the string searched for//being delimited by RespDelimiter, and multiple resonses or search //fors being delimited by ElDelimiter//Note that Random Responses are indicated by empty search fors

Dim InputFrom As TextInputStreamDim InputLine, searchForIn, RespondWithIn As StringDim Counter1, Counter2 As IntegerInputFrom = f.OpenAsTextFile

//Split searchForIn from RespondWithInWhile not InputFrom.EOF

InputLine = InputFrom.ReadLinesearchForIn = Trim(NthField(InputLine, RespDelimiter, 1))RespondWithIn = Trim(NthField(InputLine, RespDelimiter, 2))

If searchForIn <> "" then//Separate multiple searchForIns, RespondWithIns and pair them upfor Counter1 = 1 to CountFields(searchForIn, ElDelimiter)

for Counter2 = 1 to CountFields(RespondWithIn, ElDelimiter)AddResponse NthField(searchForIn, ElDelimiter, Counter1),_

NthField(RespondWithIn, ElDelimiter, Counter2)next //Counter2

next //Counter1

else //Empty searchForIn, so do randoms//Append all RespondWithIns to RandomResponsefor Counter2 = 1 to CountFields(RespondWithIn, ElDelimiter)

AddRandom NthField(RespondWithIn, ElDelimiter, Counter2)next //Counter2

end if //searchForInWendInputFrom.Close

112 REALbasic Curriculum

Page 113: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Eliza

AddResponse (S as String, R as String)

AddRandom(R as String)

6 The last thing we need in our class is the method that fetches the response:

FindMatch(S as String) as String

This method searches the list of search words, and if one is found, its index is added to the Matches array. At the end of this process, we choose one of the indexes in the array at random, and return the matching response. If the matches array comes up empty, we return one of the RandomResponse strings.

Now we just need to wire in the rest. First, we need to fill in the Function RandomInteger(Top As Integer) As Integer used by FindMatch. We’ll add it to a module (remember modules?).

SearchFor.Append SRespondWith.Append R

RandomResponse.Append R

//Pre: There is at least one element in RandomResponse//Post: Find all elements of SearchFor that are in S, and return a random

matching RespondWith String// If no matches are found, return a random RandomResponse stringDim Matches() As IntegerDim Counter As Integer

//Build list of matchesFor Counter = 0 to UBound(SearchFor)

if Instr(S, SearchFor(Counter)) <> 0 thenMatches.Append Counter

end ifNext

//Return a random match, or a random responseIf UBound(Matches) <> -1 then //Random Match

Return RespondWith(Matches(RandomInteger(UBound(Matches))))Else //Random Response

Return RandomResponse(RandomInteger(UBound(RandomResponse)))End if

113REALbasic Curriculum

Page 114: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Eliza

7 Create a new module. Name it “Random” and add the function “RandomInteger” with parameter “Top as Integer” with a return type of Integer. Enter this code

We needed a function that gave us a random number between 0 and a given number. The REALbasic function Rnd returns a fraction between 0 and 1. You can use the rnd number as “from none to all” of some quantity, so by multiplying it by top, and round-ing it to the nearest whole number, we get the value we want.

8 Now we need to build our user interface. Open Window1 and set up a user interface like this:

Figure 43. The Eliza window.

The larger EditField is named Discussion; the smaller is called Entry. Turn off the Enabled property for Discussion in the Properties pane.

9 Open the window’s code editor. Add a property: Eliza As StringResponder.

10 Add the following methods:

HandleEntry

//Return a random integer in the range 0..Top

Return round(rnd*Top)

//The user just entered something. Handle it.Discussion.Text = Eliza.FindMatch(Entry.Text)Entry.Text = ""

114 REALbasic Curriculum

Page 115: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Eliza

SetResponder(R as StringResponder)

The reason we put these into methods rather than just into event handlers is because we will let the user enter what they typed several ways.

11 Enter the following as the KeyDown event handler for Entry:

This lets the user enter what they’ve typed by pressing Enter or Return.12 Add the method call “HandleEntry” to the button’s Action event handler.

Now we have just one thing to do: we have to create a StringResponder and load its contents when the application starts.

13 In the Project Editor, double-click the App class and add the following code to its Open event handler:

You should read up on anything new here, particularly the child property of Folder-Items.

A new FolderItem starts out pointing at the folder the application is in (or when you’re running in the IDE, the folder you saved the project in), so this code will try to load a file called Responses.txt from that same folder.

Eliza = R

Dim K As IntegerK = Asc(Key)If Key = Chr(13) or Key = Chr(3) then

HandleEntryReturn True

ElseReturn False

End if

//Initialize Eliza from fileDim f As FolderItem

Eliza = New StringResponderf = new FolderItem

f = f.Child("Responses.txt")If f<>Nil then

Eliza.LoadFromFile f, "/", chr(9)Else

MsgBox "Error: Responses.txt not found."Quit

End if

Window1.SetResponder Eliza

115REALbasic Curriculum

Page 116: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Eliza

14 Add the following property to the App class:

Scope of Identifiers

You may have noticed that we have defined two properties with identical type and name (Eliza As StringResponder in both the App class and in Window1). It is impor-tant to understand that these are separate properties, which can potentially refer to different objects (although in this case they end up referring to the same object).

This works because all the identifiers (the computer programming term for names in a computer program) in a program have a scope (meaning the part of the program where the identifier is valid). When you refer to a name in your code, the meaning of the name is looked for in the following order:

n Local variables, defined and valid only with the same method, declared via a Dim command;

n Properties, methods or new events visible in the same code editor (meaning in the same class or window);

n Properties or methods in a superclass (if they are not set to Private); and

n Global or Public Properties or methods in a module or Public properties or methods in other windows and classes.This means that an identifier defined further up in this list will prevent code from using an identifier that would otherwise be visible further down in the list.

Also, remember that unless a property or method is declared as Protected or Private when the method is defined, you can always refer to it from anywhere in the program using the MyObject.SomeProperty or MyWindow.SomeMethod (and so on) dot nota-tion.

Test It

A suitable simple Responses.txt file should have been available in the place from which you got this lesson. If you want to write your own file, use a text editor like NotePad or BBEdit; make sure you save the new file as a Text file.

That’s it. As usual, you should test the program out, and trace through any parts you are interested in.

Eliza As StringResponder

116 REALbasic Curriculum

Page 117: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Eliza

Further Exercises

This project can obviously be improved in all sorts of ways. Here are some ideas:

n The project should keep track of its responses better. At the moment, if you enter the same thing twice, the computer will sometimes give back the same response twice. How could this be fixed? (One suggestion: the responses should not be random from among the possible matches, but in order. Then rearrange the responses so the last one given goes to the bottom of the list. You could shuffle the list before you start to make it random between runs. There are other solutions, though, such as tagging the responses in some way). To shuffle a list, go through the list, and swap each element with another element selected at random;

n The project could start out by asking the user’s name, and then incorporate the name into some of the responses (say, by replacing a special character such as * with the name).

n If you feel more ambitious, allow for responses that display a dialog box and store the answer, then allow that answer to be used in other responses. The program will have to let the Responses.txt file name these answers, and it can’t know ahead of time what these names will be, so it will need another list, for storing named answers, and some way of indicating that a named answer should be inserted into a response. You’ve now got two pairs of arrays with the same role (letting you look up a value in the second array according to the value in the first array; the technical name for such a data structure is a symbol table); you might like to implement a SymbolTable class (remembering the benefits of ADTs) to take care of both tasks.

117REALbasic Curriculum

Page 118: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Eliza

118 REALbasic Curriculum

Page 119: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 11 Events and Controls

Aim

In this lesson, we will continue our exploration of REALbasic’s Object Oriented Pro-gramming (OOP) features.

Events and Controls

In Lesson 9, we saw how events let us link the code defined in a superclass with code in its subclass.

This is the same mechanism REALbasic’s built-in classes use to provide us with event handlers that we can add code to in a window’s Code Editor.

In this lesson, we will use the EditField’s events to make a new version of the EditField that will only accept numbers.

1 Open a new project.

2 Create a new class called NumEdit, with EditField as its superclass.

119REALbasic Curriculum

Page 120: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Events and Controls

3 Open NumEdit’s Code Editor and add the following code to the class’s KeyDown event handler:

The Key argument to the event handler represents the key that was just pressed. And the Boolean (True or False) return value from the event handler tells REALbasic’s built-in class what to do with they key that was just pressed: if the function returns True, the key is ignored; otherwise, the keystroke is processed normally.

In fact, functions in REALbasic always return something. If you don’t explicitly return a value, the function will return a suitable ‘zero’ value (0, an empty string, False, Nil and so on, depending on the return type of the function). Notice that when you don’t provide an event handler in a subclass, when the superclass calls this function, REAL-basic automatically returns the default False from the call. So, as you would expect, if you don’t provide an EditField subclass with a KeyDown event handler, it just processes every keystroke normally.

4 Switch to Window1’s Window Editor and use the pop-up menu above the Controls list to switch the list from Built-in Controls to Project Controls. NumEdit is listed here.

5 Drag the NumEdit class from the Project Controls list into the window, and run the program.Notice that it does almost what we want, but it doesn’t support the arrow or delete keys. We should really fix that.To do that, we need to know the ASCII codes for the keys we want to permit. We could go fishing around to find it in the documentation or online somewhere, but it is easier to just work it out for ourselves. Switch back to the Built-in Controls list and drag a regular EditField into the window, and add the following code to its KeyDown event handler:

As usual, look up Str and Asc in the built-in reference if you need to.6. Now run the program, click on our new EditField, and notice the numbers

displayed when you press the Arrow keys and the Delete key.

If (Key > "0") and (Key < "9") thenReturn FalseElseReturn True

End if

MsgBox Str(Asc(key))

120 REALbasic Curriculum

Page 121: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Events and Controls

7 Modify the code in NumEdit’s Keydown event handler to read:

8 Run the program, and notice that our new EditField now lets us use the Arrow keys and Delete key.We can improve this class even more if we allow the user to enter a period for decimal values and a minus sign for negative numbers. In doing this though, we should make it work properly and let the user enter a period or minus sign once and then only in an appropriate place.Think about what might be involved in doing all this. Read about the EditField’s Sel-Start and SelLength properties.

9 Modify the code to read:

So we stop the user from entering a period or a minus sign more than once, and we only let them type a minus sign at the beginning. The EditField now works correctly, allowing the user to enter a valid number but nothing else.

A Further Subclass

Our next aim is to create a subclass of NumEdit that won’t let the user enter a number higher than a set maximum value.

1 Create a subclass of NumEdit called LimitNumEdit.

If (Key >= "0") and (Key <= "9") thenReturn False

elseif Key >= Chr(28) and Key <= Chr(31) then//arrow keyReturn False

Elseif Key = Chr(8) then //delete keyReturn False

ElseReturn True

End if

If (Key >= "0") and (Key <= "9") thenReturn False

Elseif Key = "." and InStr (Text, ".") = 0 thenReturn False

Elseif Key = "-" and SelStart = 0 and Instr (Text, "-") = 0 thenReturn False

Elseif Key >= Chr(28) and Key <= Chr(31) then //arrow keyReturn False

Elseif Key = Chr(8) then //delete keyReturn False

ElseReturn True

End if

121REALbasic Curriculum

Page 122: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Events and Controls

You can do this by right+clicking (Control-clicking on Macintosh) on NumEdit in the Project Editor and choosing New Subclass from the contextual menu. REALbasic will create a new subclass of NumEdit and name it CustomNumEdit. Use the Proper-ties pane to change its name to LimitNumEdit.

2 Open LimitNumEdit’s Code Editor, and note that the KeyDown event handler is missing.

More on Events

A Event Definition is a method call that gets connected to an actual method some-where else. Entering code into an event handler provides the actual method for the event to call. But it can only be hooked up to one event handler. In a chain of sub-classes, the ‘highest’ one to provide an event handler ‘swallows’ the event, and doesn’t let any further subclasses see it.

This isn’t a problem, though, because there is nothing to stop the subclass that handles the event from defining a further new event, with exactly the same name and argu-ments as the one it is handling, and to call that at an appropriate time. Let’s see how to do that.

1 Open NumEdit, and add a new KeyDown event definition, just like the original (same argument and return type).

2 Modify the KeyDown event handler to read:

So wherever we were permitting a key before, we instead ask our subclass to decide what should be done with it. If there is no handler, the default False value is returned, so the behavior is just as it was before if there is no subclass, or if that subclass provides no handler for this event. But if it does, it can further restrict the acceptance of keys.

But note that the way we’ve set up our events and the way we call them doesn’t give a subclass a way to accept more keys. If the superclass rejects a key, the subclass doesn’t even see it.

If (Key >= "0") and (Key <= "9") thenReturn KeyDown(Key)

Elseif Key = "." and InStr (Text, ".") = 0 thenReturn KeyDown(Key)

Elseif Key = "-" and SelStart = 0 and Instr (Text, "-") = 0 thenReturn KeyDown(Key)

Elseif Key >= Chr(28) and Key <= Chr(31) then//arrow keyReturn KeyDown(Key)

Elseif Key = Chr(8) thenReturn KeyDown(Key)

ElseReturn True

End if

122 REALbasic Curriculum

Page 123: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Events and Controls

3 Test that NumEdit still works.

4 Change the EditField in the window to a LimitNumEdit control (by clicking on the EditField in the window and changing its Super in the Properties pane), and test that it still works. Since we added no code to it, it does exactly what its superclass does.Consider now what might be involved in implementing a LimitNumEdit as we want. Now let’s do it.

5 Add a Maximum property to the LimitNumEdit class, and a SetMaximum method:

We shouldn’t usually set the value of a property directly, so we created this setter method.

6 Add the following code to the KeyDown event handler:

As usual, look up any of these text-handling functions you are unsure of.7 Add the following code to the Open event handler for the control in the

window:

8 Run the project, and test that it works as planned.

9 For testing purposes, add a new “Boo” Event Definition to the NumEdit class. Create a new class FurtherNum, with LimitNumEdit as its Super. Notice that FurtherNum has a “Boo” handler.This works because LimitNumEdit doesn’t define an event handler for Boo (to make our terminology here clear: ‘not defining an event handler’ means not having any code in the event handler).

10 Now remove the New Event Boo from NumEdit and remove its handler before you save the final version of this. You might also like to Export the NumEdit and LimitNumEdit classes out of the Project Window (select them and look for Export in the File menu or in their contex-

Sub SetMaximum(M As Integer)Maximum = M

Function KeyDown(Key As String) As BooleanDim ChangedString As StringChangedString = Left(Text, SelStart) + Key + Mid(Text, SelStart + SelLength + 1)If Val(ChangedString) <= Maximum then

Return FalseElse

Return TrueEnd if

Me.SetMaximum 500

123REALbasic Curriculum

Page 124: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Events and Controls

tual menu) to somewhere handy. These are our first actually useful classes, and you may well have need of them some day. You can just drag the files into the Project Edi-tor in another project, in order to use them again. Make sure you drag NumEdit in before LimitNumEdit, though. Otherwise, there will be nothing for LimitNumEdit to be a subclass of when it’s imported, and it will lose its superclass setting.

Further Exercises

Try some of the following exercises:

n Implement a PositiveNumEdit subclass;

n Use the LimitNumEdit class in a project with a window that performs an operation on two numbers entered, displaying the results in a third EditField;

n The same, except with a set of radio buttons to choose the operation;

n The same again, but it also updates the result as you are typing;

n Implement a RangeEdit subclass, which defines a new WithinRange event, which is called when a number within a certain range is entered. You will also need to define suitable properties and a method to set the range.

Explanations/References:

Events are explained in the REALbasic User’s Guide Chapter 5 (particularly in the sec-tion Adding New Events).

124 REALbasic Curriculum

Page 125: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 12 Class Interfaces

Aim

In this lesson, we will examine our last major OOP feature in REALbasic: the Class Interface.

The Essence of Type

The notion of type that we have been working with amounts to this: a type is a name and a set of operations (properties and methods).

Since we can always create getter and setter methods for any properties a type might require, the simplest possible notion we can arrive at for a type is a name and a set of method definitions. (Notice that by method definitions, we don’t mean the actual code of the methods, but just their names and arguments1).

This is precisely what an interface is: a name and a set of method definitions. We can create a new type by creating an interface and assigning it method definitions. We can make a class have that type by adding the name of the type to its Interfaces property, and by making sure it supports all of the methods defined by the interface.

Notice that this idea is quite separate from inheritance. Inheritance from a common superclass guarantees that two classes will have the same methods, and thus that they

1. Another name you will hear for this is a method signature or a method declaration.

125REALbasic Curriculum

Page 126: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Class Interfaces

can be treated as the same type. But inheritance goes beyond the minimum required, by providing implementations of methods, along with properties.

Another way of describing the difference between an interface and class inheritance is this: an interface defines a type, but inheritance also provides at least part of the imple-mentation.

The obvious question now is: Why would we not want a class to get at least part of the implementation when we assign it a type? (Why even have this ‘lite’ way of defining a type at all?) The answer is: It avoids many complications when we want our program-ming language to let our classes have more than one type.

Multiple Types

As you start developing more complex programs, it quickly becomes natural to want to give a single class more than one type.

The most obvious example is the built-in classes: we might want these to take on extra roles, and the natural way to do this is to provide them with extra polymorphic types. In the program we will construct in this lesson, we will extend the word counter project so it can display its result in either a ListBox or in an EditField.

The correct way to do this in an object-oriented programming language like REALba-sic is to give these two classes the same type, thereby assigning them suitable opera-tions for displaying the word count.

But REALbasic only allows us to assign one superclass to a class. The obvious question now is: why can’t a class have multiple superclasses?

Only One Superclass

There are good reasons for only allowing one superclass for a given class. Programming languages that allow you to have more than one superclass run into a variety of compli-cations. For instance, what if the two superclasses both have a method or a property with the same name? What about when the two superclasses themselves have a com-mon superclass?

126 REALbasic Curriculum

Page 127: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Class Interfaces

Figure 44. A hypothetical class hierarchy.

In a programming language that supports multiple inheritance like this, assume Class1 has a property Size. This means that both Class2 and Class3 have a Size property. Should Class4 have one Size property, or two (presumably, we’d have some way of renaming one of them)? The answer is that it depends: you might want just one prop-erty, but you might want two. There are other complications, such as what happens to a method from Class1 that is modified in Class2, but not in Class3.

Considerations like this mean that programming languages supporting multiple inheritance have convoluted and often difficult to maintain mechanisms for control-ling how the inheritance is to be carried out.

Interfaces, since they carry no implementation, avoid this problem.

An Even Better Word Counter1 Open the project from Lesson 9 (the word counter that can count both files

and the clipboard).

2 Add a TabPanel to Window1 (read about how to use TabPanels in the User’s Guide).

3 Give it two panes called ‘List’ and ‘Text’ and put the WordList ListBox on the first page of the TabPanel, so the window looks like this:

Class1

Class2 Class3

Class4

127REALbasic Curriculum

Page 128: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Class Interfaces

Figure 45. Window1, Showing the ListBox.

4 Add an EditField called WordLister to the second page of the TabPanel.

5 Turn on its MultiLine and ScrollBarVertical properties, so this is what you see when you switch to page 2 of the TabPanel:

128 REALbasic Curriculum

Page 129: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Class Interfaces

Figure 46. Window1, showing the EditField.

Examine the methods and properties defined in Window1 and consider why, in the light of what we’ve learned in recent lessons, these more appropriately belong in a sep-arate class;Think about what form that class might take (it will need all the methods and proper-ties defined in Window1, for a start…).

6 Create a WordCountList class, and move the methods and properties from Window1 to the new class.

7 Add a WordCounter As WordCountList property to Window1.

8 Add an Open event handler to the Window, with code to initialize WordCounter:

9 Open the code in either of the buttons, and think about how it needs to be modified to accommodate the new object. The top parts of the code will be easy to change, but an interesting issue will arise when you consider how to display the results. You might be tempted to add Get meth-ods to the WordCountList class, so you can loop over the list of words and display their contents, just as we have been doing.

WordCounter = New WordCountList

129REALbasic Curriculum

Page 130: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Class Interfaces

Doing that would be poor design.

Give Objects High-Level Behavior (or ‘Think Twice About Accessor Methods’)

This part is very important. It is an example of the kinds of things you need to learn to be a good object-oriented programmer.

You should think twice about any design involving Get and Set methods (also known as Accessor Methods). While they are often appropriate, you should see if there is a bet-ter design solution. Any such solution will usually involve giving higher-level methods to the object you were tempted to add accessor methods to. By ‘higher-level’, we mean something like ‘more sophisticated’ or ‘performing a larger task.’

The current design we are putting together is an excellent example of this: the job of displaying the word count should be managed between the WordCountList class that will have the list of words, and the class that will be displaying that list.

A slightly different version of this design heuristic (meaning ‘rule of thumb’) is to say that the code to carry out a task should be distributed between just the objects that must be involved. This heuristic tells us that the button in the window should not con-tain any of the logic involved in displaying the count. This rule keeps our code simpler, gives us less places to look for problems, and makes the objects more portable between projects (or between different parts of the same project).

1 Now that we have made our broad design decision, here is the code for the Clipboard button’s Action handler:

Another good design would be to have the Display method execute the clear method itself; however, by separating that call, we keep a little extra flexibility to, say, display the word count in several stages, or from several sources.

2 Choose Project . Add . Class Interface1. Name it WordCountDisplayer in the Properties pane.

//Execute CountWords on the clipboard, then copy the results into WordListDim Source As ClipBoardSourceSource = New ClipboardSource

WordCounter.CountWords(Source)

WordList.clearWordCounter.Display WordListWordLister.clearWordCounter.Display WordLister

1. You may wish to right (or control-) click on the toolbar in the Project tab at this point, choose Customize… and add Class Interface to the toolbar.

130 REALbasic Curriculum

Page 131: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Class Interfaces

3 Double-click the class interface in the Project Editor, and add two method definitions:

and

4 Create a method named “Display” in the WordCountList class:

5 Create a class WordCountListBox, with ListBox as its super.

6 Click on its Interfaces property and enter WordCountDisplayer. Implement suitable Add and Clear methods:

and

Sub Clear()

Sub Add(w As String, c As Integer)

Sub Display(w As WordCountDisplayer)Dim counter As Integer

w.Clear

For counter = 0 to UBound(Word)w.Add Word(counter), Count(counter)

Next

Sub Add(w As String, c As Integer)AddRow str(c)Cell(ListCount - 1, 1) = w

Sub Clear()DeleteAllRows

131REALbasic Curriculum

Page 132: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Class Interfaces

7 Change the code in the Action handler of the CountFileButton to:

8 Use the Properties pane to change the ListBox to a WordCountListBox.Before you proceed with following instructions, see if you can create the WordCountE-ditField yourself. You’ll have to decide how to display the results (perhaps one word to a line, and each line will look something like ‘apples: 3’).

If you need help, here is one way of doing the methods in the WordCountEditField:

Your code might look a little different to this, and it might display the results a little differently. That’s fine, as long as it works.

//Ask user for a file, then execute CountWords on thatfile, //and copy the results into WordList

Dim counter As integerDim Source As FileSourceDim f As FolderItemDim s As BinaryStream

Source = new FileSource

//Request filef=GetOpenFolderItem("application/text")

If f<>Nil thens = f.OpenAsBinaryFile(False)

Source.SetFile s

WordCounter.CountWords(Source)

WordList.clearWordCounter.Display WordList

End if

Sub Add (w As String, c As Integer)If Text = "" then

Text = Text + w + ": " + Str(c)Else

Text =Text + Chr(13) + w + ": " + Str(c)End if

Sub Clear()Text = ""

132 REALbasic Curriculum

Page 133: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Class Interfaces

Don’t forget to add WordCountDisplayer to this class’s Interfaces property, and to change the EditField on the second page of the TabPanel in Window1 to this new class.

9 Run the program, stepping through the important parts if it’s not clear how it works.

Questions and Conclusions

Class Interfaces are an important tool for producing the best REALbasic program designs. You now have all the tools you need to simplify and structure your code effec-tively using Polymorphism, wherever that is appropriate.

Further Exercises

Try some of the following exercises:

n Add a new WordCountDisplayerGroup class to the project. Its task is to store references to multiple WordCountDisplayers, and to ‘broadcast’ calls to each of the objects it refers to. So it is a WordCountDisplayer itself, but it also has an Add method, with a WordCountDisplayer argument. The buttons need only then ask the Word counter to display itself in the WordCountDisplayerGroup, and that object will in turn ask each of the displayers to display the contents.

n Add the ability to ‘display’ to a tab-delimited file. This would work nicely as a third ‘tab’ that lets you choose the target file. To write this, you will need to research how to write to a file.

A Final Comment

Note that User’s Guide implies that interfaces are only to be used with controls (see page 425 of the 2005 User’s Guide), but this is not so: they are suitable for many situa-tions with any type of object.

133REALbasic Curriculum

Page 134: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Class Interfaces

Take-home assignment: Writing to a File

Your task is to add a new WordCountDisplayer to the word counting project we’ve been working on. This new class will write the word count to a file.

At a minimum, you’ll need to read the section Getting a File at a Specific Location in the REALbasic User’s Guide on page 372. You should also read Understanding Folder-Items on page 371, and Working with Text Files on page 390.

The text file should be tab-delimited, meaning that each word and its count is written to the file as its word, followed by a tab, followed by the count (as a string), and then followed by a return character (ASCII 13).

You should first write a class that just sends the information to a file with a fixed name on the desktop. Look up the DesktopFolder function in the built-in reference for infor-mation and examples on using this function.

After you get that working, you should modify it so that it can be given a path or a folderitem (your choice) to save the information to. You should add panel to the Tab-panel with a button that lets the user create the file to contain the information. You should display the chosen path in an EditField on the tab control. You might like to add a checkbox to turn this export on or off, as well.

Look up GetSaveFolderItem to find out how to display a standard file save dialog. You should also look up the FolderItem class to find out how to get information such as the path out of the FolderItem after the user has created the file.

134 REALbasic Curriculum

Page 135: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 13 Bubble Sort

Aim

We take a break from object-oriented programming to return to algorithms. Over the next few lessons, we will examine a number of different ways of sorting a list into order.

In examining this range of code and techniques, you will achieve a few things:

n You will begin learning about the rich and complex notion of efficiency in computer programming;

n You will see an example of how many ways there usually are to solve a given problem (even an apparently simple one) with a computer, and

n You will look at more code. It is important to read a broad range of code.

135REALbasic Curriculum

Page 136: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Bubble Sort

About Efficiency

There are a few very specific notions of efficiency that computer science is usually con-cerned with, and we will look at these in a moment. But before we do, let’s consider efficiency more broadly.

Programmer’s Time vs. User’s Time

We will begin by observing that there are two different times1 being used by a com-puter program:

n The programmer’s time, in writing the program; and

n The user’s time, in waiting for the program to finish.

Programmer Time is Scarce

Next, we’ll consider that there are a number of tasks that can take up a programmer’s time:

n Making a program work correctly;

n Making a program work faster (or, say, in less memory);

n Making a program easy to change;

n Doing something else (writing a different program; taking the dog for a walk; learning Spanish…)(The first three aren’t clearly separated. For instance, making the program easier to change and making it correct may go hand-in-hand).

Our second observation, then, is that there are many demands on a programmer’s time.

We’ll also notice at this point that most programs will only be used for a certain period of time, after which a new version is used, or the program is not used at all.

User’s Time vs. Computer Time

Computer time is getting cheaper very quickly. Meanwhile, people work at the same speed they always have.

More and more often, then, when a user runs a program, almost the entire time involved is taken up by the user setting up the data, choosing which program to run, reading the results, and so on.

1. Actually, there are potentially many other types of time, and other scarce resources we might want to preserve: network transmission time, or time to display something, or time to display a first result in some long, complex task.

136 REALbasic Curriculum

Page 137: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Bubble Sort

Why you should probably write a lot of quick and dirty programs

All of this leads to the conclusion that a lot of programs should be written using the quickest, simplest code possible.

Your time is probably much scarcer than your user’s. Even if it isn’t (perhaps your pro-gram will be used by a million people), a ‘slow’ program that finishes in one second, compared to a ‘fast’ program that finishes in 1/100 of a second, is probably fine. There are a lot of simple tasks you can save people from doing, by writing simple programs. If you can do more of this, by writing quick and dirty programs, then this is the sensible thing to do.

When you should spend more time writing a program

You should spend more time on a program in the following cases:

n The program won’t run ‘in an instant’ if you don’t pay attention to the program’s speed, and will be used often, or by many people;

n The program must handle a very ‘large’ problem (say, spending an extra hour writing more efficient code means the program finishes in a few minutes rather than a week — as we will see, this kind of difference is surprisingly common);

n The program will be used for a very long time. It will probably be repeatedly modified, so you should at least spend time to make its design easy to change and well-documented;

n When the speed of the code manifests itself as another quality that people will notice, you may want to optimize the speed of your code. The commonest example of this is in games: the faster your code runs, the more images per second it can generate, meaning the animation is smoother.You can doubtless conceive of other conditions along these lines.

Don’t Waste Time on Wasteful ‘Efficiency’

We will spend quite a bit of time looking at the notion of efficiency in programming, as programmers usually define it. As we do this, you will see that very often, code that is easier to write will run more slowly (sometimes much more slowly).

Don’t make the mistake that surprisingly many programmers do, of thinking that the slower, simpler code is bad code. Very often, it is better code, because you can write it more quickly and it is easier to understand.

137REALbasic Curriculum

Page 138: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Bubble Sort

Different Parts of a Program Often Require Different Attention

One final observation: even in a program that you decide to spend a lot of time opti-mizing (meaning you are making it run faster or in less memory), there will be parts of the program where you shouldn’t bother. You should only optimize the parts of the program that the computer will spend a lot of time in.

Four Lessons on Sorting

Now on to the narrower notion of efficiency.

One of the most famous books on programming, The Art of Computer Programming1, describes 29 quite different ways to sort a list of things into order (along with many minor variations). And the list in that book is by no means exhaustive.

In this and the next three lessons, we will look at four of these ways of sorting. We will examine how they work; we will test how fast they are; we will briefly consider other issues, such as what will be their best- and worst-case performance; and we will con-sider minor variations on them that might improve their performance.

The Bubble Sort

We begin with the Bubble Sort, probably the simplest possible sorting algorithm, and an amazingly inefficient one.

1 Open the project BubbleSort, and examine the code of the SortEvent Event handler of the BubbleSortList class.

2 Put a breakpoint on the Do command.We haven’t seen the Do… Loop Until before. This is just like the While… Wend loop, except that it executes the body of the loop once before testing the condition, and it stops executing the loop when the condition evaluates to True, not False.

You should try to work out how the sorting is done by examining the code, before reading the explanation in the next paragraph.

How the Bubble Sort Works

The Bubble Sort works by looking through the list from one end to the other, examin-ing each pair of adjacent elements in the list, and exchanging them if they are out of order. This is repeated until you can look through the list from one end to the other, without having to exchange any of the elements.

It has probably never occurred to you to sort a list in this way, and it is obvious how inefficient it is. But the code to implement a Bubble Sort is very simple. Don’t be

1. Knuth, Donald E, The Art of Computer Programming 2nd Ed, Vol 2, ISBN 0-201-89658-0 in case you’re interested.

138 REALbasic Curriculum

Page 139: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Bubble Sort

afraid to implement a Bubble Sort if you need to sort a small amount of information in a quick and dirty program. On the other hand, in the next lesson, we will look at a much more efficient algorithm that is very nearly as easy to implement (the Insertion Sort).

1 Look at the code of the Go button’s Action event handler. Then run the program and click the Go button. Trace through the execution of the code, examining the contents of the array as you go.This program is deliberately kept very simple. You’re expected to run the program in the debugger to see what it does, and if you want it to sort a different number of ele-ments, you will have to change the code in the button. This is all in keeping with our notion of efficiency. It is important to test code for efficiency sometimes, and to be able to see how it runs, but if we’re not prettying it up to make a final program, or you’re intending to run a lot of tests, it isn’t worth spending a lot of time on making the test itself very fancy. We’ll see more of this in the next few lessons.

Make sure you look through the code and see how we’ve used polymorphism to sepa-rate the implementation of the sort from the code that’s requesting the sort. The code requesting the sort only needs to know that the thing to be sorted is a NumList. This will be important in later lessons, where we run multiple different sorting algorithms and compare them.

The Narrow Definition of Efficiency

All of our discussions of the importance of your time aside, it is very important in computer science to understand how we look at efficiency. There are many situations where it will be important to write efficient code.

There are many possible types of efficiency, but the most important two are: how much time does an algorithm take to finish? And how much memory does an algo-rithm need?

The Bubble Sort is very good in terms of its memory efficiency: other than the list of elements itself, we need a counter, a variable to use in the exchange, and a Boolean. Even the counter is not actually necessary (think about how to write the method with-out it).

But the code is very inefficient in terms of time. Try increasing the list to 1000 ele-ments, and see how long it takes to finish. When the time to complete an algorithm increases very rapidly with the size of the problem (in this case, the ‘size of the prob-lem’ would be the number of elements in the list), we say the algorithm is time ineffi-cient.

139REALbasic Curriculum

Page 140: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Bubble Sort

Best and Worst CasesThe best case for this algorithm is an already-sorted list. In this case, it will complete as quickly as a simple test that the list is already in order. And a list that is close to sorted will sort fairly quickly as well1.The worst case for the Bubble Sort is when the list is sorted in reverse order. In that case, each time through the list, one element will be sorted into place, and the rest of the list will be unchanged. For a list of n elements, a straight Bubble Sort in the worst case will have to make n2 comparisons (because it searches a list of n elements n times).

Further Exercises

As you watch the algorithm in action, and if you think about what it’s doing, you might have noticed that the first time around the Do loop, the largest element in the list winds up at the end; the next time through the list, the second-largest winds up at the second from the end, and so on.

n Consider how the algorithm might be improved as a result.The improved algorithm will require only n2-n comparisons, for a list of n elements.

A nice and reasonably simple improvement of the algorithm is to make alternate passes in opposite directions through the list: this slightly improves the average time, and massively improves the worst case. It is difficult to arrive at a simple mathematical expression for how many comparisons are required in the worst case, but it is consider-ably better than either of the above.

1. There may be times when you will write a program that deals with this very situation: you may need to sort a list that is very close to sorted. In that case, a bubble sort (or more proba-bly, an insertion sort) will be considerably faster than other, fancier sorts we look at later.

140 REALbasic Curriculum

Page 141: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 14 Insertion Sort

Aim

In this lesson, we will look at another sorting algorithm. We will also build a program that lets us easily compare different sorting algorithms.

The Insertion Sort

Begin by considering how you would sort a set of filing cards with names on them.

You would probably think of using an Insertion Sort: Essentially, start with the first card, and start building up a new stack of cards with each card sorted into its correct spot. As you pick up each unsorted card, you will find its place in the sorted pile and insert it. This is exactly what we want to do on the computer.

Consider how you would implement this on the computer. You will probably want to move the elements of one array into another array, mimicking what you would do with real cards.

Now ask yourself if it is possible to implement the same algorithm with a single array. Notice that the total number of elements involved in the unsorted and the sorted list together doesn’t change: as one list grows, the other shrinks by an equal amount. From this, we can see that you can sort the array within itself, by building the sorted array from one end of the unsorted array. This will save memory and time (we save time because the computer doesn’t need to allocate a new array), without making the algo-rithm significantly more complex.

141REALbasic Curriculum

Page 142: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Insertion Sort

You will see as we implement this that moving element n into its correct place will actually involve rotating the list of elements between its new place and old place down by one, with the element itself rotating to the top of the rotated section of the array.

So part of the algorithm will be a rotate sub-array operation.1 Open the InsertionSort project.

2 Take a quick tour through the larger project. It lets us run more than one sorting algorithm over the same data, and to compare the time those multiple algorithms take.

3 Open the InsertionSortList class. Examine the Rotate method. Pretty straightforward.

4 Now examine the SortEvent event handler.Make sure you also check out the general structure of the project, and look for how we use object-oriented programming features to simplify the design.

5 Run the project, and try an interesting range of values: 100 to 1000 in steps of 100 is probably good.

Examine the Results

This next step is optional, but if you are at all comfortable with a spreadsheet, it’s a nice way to compare the results.

After the program runs, it will show an EditField with the times from the two sort algorithms. Copy the values from the Editfield and paste it into a spreadsheet. Sort the entire spreadsheet by the first column, then cut the values from the right column in the second half of the rows up alongside the right column in the first half of the rows, like this (circles show where data is pasted from/to):

Bubble Sort Array 100 24 11

Bubble Sort Array 200 89 54

Bubble Sort Array 300 223 104

Bubble Sort Array 400 469 208

Bubble Sort Array 500 617 323

Bubble Sort Array 600 880 413

Bubble Sort Array 700 1060 641

Bubble Sort Array 800 1398 771

Bubble Sort Array 900 1766 981

Bubble Sort Array 1000 2732 1248

Insertion Sort Array 100 11

Insertion Sort Array 200 54

Insertion Sort Array 300 104

142 REALbasic Curriculum

Page 143: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Insertion Sort

Now you should be able to graph the right three columns in the top half of the rows, using the first column as labels, and see how the two algorithms compare. You should be able to produce a spreadsheet something like this:

Figure 47. A spreadsheet and graph of the results.

The new algorithm is clearly much faster. But note that the two curves are similarly-shaped (parabolic). This means that the new algorithm reaches similar times for a data set that is not very much bigger. Both algorithms will take a long time with very large data sets.

Ask yourself where the time is being spent in the insertion sort. Answer: rotating the elements in the list.

Further Exercises

It would be interesting at this point to ask yourself how this algorithm might be improved. There are quite a few possible answers to this question…

Here is just one to get you started, which you should try to implement: It is inefficient to search for the insertion point by just starting at the top of the list and looking one

Insertion Sort Array 400 208

Insertion Sort Array 500 323

Insertion Sort Array 600 413

Insertion Sort Array 700 641

Insertion Sort Array 800 771

Insertion Sort Array 900 981

Insertion Sort Array 1000 1248

Number of El Bubble Sort Insertion Sort100 24 11200 89 54300 223 104400 469 208500 617 323600 880 413700 1060 641800 1398 771900 1766 981

1000 2732 1248

Sort Times

0

500

1000

1500

2000

2500

3000

100

200

300

400

500

600

700

800

90010

00

Number of Element

Bubble Sort

Insertion Sor

143REALbasic Curriculum

Page 144: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Insertion Sort

by one through the list, because the list is already sorted. Instead, implement a binary search, in which you start in the middle of the already-sorted list, then jump to the middle of either the first or second half, then to the middle of the first or second half of that, and so on, until you have narrowed down the location you’re looking for to within maybe five elements, then you switch to the one-by-one linear search. This will improve your sorting time quite a bit.

144 REALbasic Curriculum

Page 145: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 15 Refining the Insertion Sort

Aim

In this lesson, we look at a variation on the insertion sort. We will build a framework that allows us to compare different sorting algorithms’ speed, and use it to see if the new variation is faster.

About Testing

It is often useful to conduct tests to compare the speed of algorithms. In many cases, it is not a straightforward matter to prove if or when one algorithm will be faster than another.

A high-level language such as REALbasic introduces another complication: REALbasic does many things for us ‘behind the scenes,’ and we don’t know exactly how it does these things, or when. For instance, as we create and dispose of variables, or resize arrays or strings, REALbasic is taking care of some fairly complex memory management for us (tracking which variable is kept where, how big each variable is, and managing the recla-mation of space occupied by variables that are disposed of or resized). Sometimes, some activity REALbasic is doing behind the scenes will introduce hiccups or unpredictability into the time an algorithm or some part of it will take to complete.

As you will see in this lesson, just because we feel certain something should be quicker doesn’t necessarily mean that it will be…

145REALbasic Curriculum

Page 146: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Refining the Insertion Sort

Many Ways of Improving the Insertion Sort

At the end of the last lesson, we asked you to come up with ways to improve the algo-rithm for the insertion sort. There are many possible answers to this. Here are a few:

n Assuming the values to be sorted are randomly distributed, start looking for an insertion point at a index value estimated from the value to be inserted (so if it’s a 100-element list, with values up to 100, start looking for where to insert the value 50 in the middle of the so-far sorted values, and start looking for where to insert 25 at a quarter of the way into the list);

n Perform a binary search for the insertion point (look at the middle value, then the middle of the list above or below that, then at the middle of the values left, and so on).

n Sort into N separate lists, each covering a particular range of values, then merge these lists at the end; and

n Rather than rotating the elements in the array to insert a value, maintain a list of next index values in a parallel array, and work out the correct order using that array. This makes insertion take a fixed number of operations, rather than taking longer as the list gets longer.Some of these ideas can be combined, of course. We will test the last idea. It seems as though it should be faster, since assigning to a couple of array elements should be con-siderably quicker than the large number of assignment operations involved in the rota-tion operation in a long list.

1 Open the project 15_InsertionSort2. Run it for the range 100 to 1000 in steps of 100. You may wish to copy the results out to a spreadsheet and graph them.You may find that this new algorithm isn’t faster (it was faster for about 900 elements or more on a Powerbook G3/333 under Mac OS 9, but slower for any number of ele-ments on the same computer under Mac OS X). It seems reasonable to expect that the new algorithm will be faster, so this result is interesting (and it shows why we should test our assumptions!).

After the sort operation, a particular element of the link array contains the index value of the element in the Numbers array which comes after the element of the values array at the same index. This is easier to see than to explain, so here is an example:

146 REALbasic Curriculum

Page 147: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Refining the Insertion Sort

The link array tells us which row is next in order. We keep separate track of the lowest element in the array to be sorted, so we know that row 3 is first (it contains the lowest value, 1). We look across at the Link Array in row 3, and this tells us that row 6 is next (because it has the next-lowest value, 2). It is followed by row 4 and so on. The last row, number 2, has a Link Array value of –1, to tell us that there is no next element.

To insert a row into the list, it is only a matter of updating the link values of the ele-ments preceding and following it in order. It seems reasonable to expect that for large arrays, it should be quicker to just update a link array element, rather than to rotate a large part of the list.

Even if this sort method is faster, just building the link array isn’t quite the same as sorting the original array. Searching through the array in sorted order will be slower if it is necessary to follow the link array to find the next element. And finding the nth element in sorted order will be very slow. This is a common situation: which algo-rithm is better will often depend on how you want to use the results.

2 Open the LinkInsertionSortList class, and examine the SortEvent event handler.As an example, we’re doing everything in one big method here because doing some-thing through a method call rather than in place is a little slower. This can matter when you multiply that little difference by a lot of times through the loop.Remember our discussions about efficiency. We would want to do this only if doing it makes the code noticeably faster; the delay is making someone wait; and we don’t have anything more important to spend our programming time on.

Commenting and Uncommenting Code

There are three ways to indicate that something typed into REALbasic is a comment. Two of them are to begin a line with // and to begin a line with '. You should always use // for actual comments, because there is a different use for the ' comment: REAL-basic provides a Comment/Uncomment button in the Code Editor toolbar. This will add or remove the ' comment mark from a block of lines. You can use this to tempo-rarily disable or enable a chunk of code, which can be very useful during debugging. If

Index Numbers Link Array

1 5 2

2 5 -1

3 1 6

4 3 5

5 4 7

6 2 4

7 4 1

147REALbasic Curriculum

Page 148: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Refining the Insertion Sort

you always use the double slashes for your comments, the built-in Comment/Uncom-ment commands won’t disturb your actual comments.

The LinkInsertionSortList Sort event handler has some code commented out like this at the end. It uses the link array to actually sort the array (so immediate access to a par-ticular element of the sorted array is not slowed down). If you got faster results for the new algorithm, try again with the commenting removed. The new algorithm should now be faster, but the threshold at which it becomes faster will be at a higher length of list.

Why is the New Algorithm Slower?

It’s difficult to be sure why the new algorithm may not be faster, but we can make some educated guesses.

First, the new algorithm has to do more to start. The new algorithm has to resize two arrays, rather than one.

Notice also that for each comparison of two elements of the array we’re sorting, the new algorithm has to execute two comparisons more than the first algorithm does. So finding the location in which to insert the new element is going to be slower than it is in the first algorithm. It also has to keep track of two extra variables as it searches the list.

Further Exercises

It would be interesting to implement some of the other ideas for how to speed up the insertion sort. Build each as a separate class, and wire them all into the test framework so you can work out which is quickest for large lists. It would be surprising if one of the other ideas for improvements wasn’t actually faster.

Any such experiments will only be an academic exercise (although a good one). In the next lesson, we’ll go to quite a different algorithm called a Quick Sort that is much faster for a random list…

148 REALbasic Curriculum

Page 149: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 16 Quicksort

Aim

In this lesson, we learn about the Quicksort, one of the fastest general-purpose sorting algorithms known. We will learn how it works, code it up in REALbasic, and then compare it to the other sorting algorithms we’ve developed.

How the Quicksort works

We begin by shuffling the first element of the list into its final place, in the same process making the elements on either side all lower (on the left) and higher (on the right).

We start by comparing the first element with the element next to it, and the element at the end of the list:

Figure 48. The starting situation.

76131049825

x y

149REALbasic Curriculum

Page 150: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Quicksort

We move x to the right and y to the left, until x points at an element greater than 5 and y points at an element less than 5. Then we swap the elements x and y are point-ing to:

Figure 49. The first exchange.

Repeat this process, moving x and y toward each other as we go:

Figure 50. A further exchange.

This process continues until x y. Then switch the first element (5) with the element in the position before x:

76131049825

x y

76831049125

x y

76831049125

x y

76891043125

x y

150 REALbasic Curriculum

Page 151: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Quicksort

Figure 51. Finishing the first pass.

What have we done?

5 is now in its final place, and the sub-lists on either side of 5 are all lower than 5 (to its left) or greater than 5 (to its right):

Figure 52. We’ve reduced the problem to two smaller problems.

You should be able to see now that we can just recursively employ the same process to sort the two smaller lists.

The Project

Open the project 16_QuickSort. Open SortWindow in its Window Editor, double-click on the Quicksort button, put a breakpoint at the end of the Action event handler, and trace through the algorithm for a bit.

1 Run the old sort button for an interesting range: perhaps 500 to 1000 in steps of 100. On the author’s computer, the Quicksort algorithm is about 40 times faster than the insertion sort…

7 689104312 5

xy

7 689105312 4

x y

3124 7 689105

Now sort these lists…

151REALbasic Curriculum

Page 152: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Quicksort

2 Now try it again for some much shorter numbers. Quicksort might even be noticeably slower for some shorter lists.

Further Exercises

The algorithm can be made faster. The Quicksort algorithm is quite inefficient for shorter lists. What would work better would be to switch to another algorithm such as insertion sort for shorter lists. Notice that a large list will eventually be reduced to many very short lists toward the end of the process, so sorting these short lists more quickly will produce a significant speed-up.

A great exercise would be to produce a program that can work out at what size of lists the algorithm should switch to a different sorting algorithm. This would be a program that timed sorting a big array repeatedly, increasing the size of list that is sorted by insertion, until the time stopped getting shorter.

152 REALbasic Curriculum

Page 153: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 17 Exceptions, Constructors, Overloading

Aim

We take a bit of a breather from complex algorithms. We’re going to look at one major subject (Exceptions), and along the way, we’ll pick up a couple of simple extras (Con-structors and Overloading).

Exceptions

Handling errors and unusual situations with the control mechanisms we have seen (loops, if-thens, and the like) can make otherwise simple code much more complex, because you have to litter your code with tests for every possible error or unusual con-dition. This can make such code much harder to develop and maintain.

Exceptions provide an elegant answer to this problem, by providing a controlled way of jumping out of the regular flow of control.

Here is an example. Assume this is the normal flow of control in some part of a pro-gram (Method A calls Method B calls… Method D returns to Method C…):

153REALbasic Curriculum

Page 154: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Exceptions, Constructors, Overloading

Figure 53. The normal flow of control.

Now, what do we do when…

Figure 54. A problem occurs…

This problem might be an error in your code, or it might be something out of your control (perhaps we were about to open a file, but it has been deleted since we checked that it existed). Let’s just concoct an example. Here, an error occurs when we try to access an element of an index that doesn’t exist. In REALbasic, this raises an exception:

• MethodA calls…• MethodB calls…• MethodC calls…• MethodD

• Method D returns to• Method C which

returns to• Method B which

returns to• Method A

• Method A calls…• Method B calls…• Method C calls…• Method D

a problem occurs here?

Dim A(4) As Integer

A(5) = 7

…and the code jumps fromwhere it is executing to thenearest handler.

154 REALbasic Curriculum

Page 155: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Exceptions, Constructors, Overloading

When an exception is raised, REALbasic follows a very different kind of flow of con-trol to its regular line-by-line execution. It looks for the nearest matching Exception Handler. This can be at the end of the current method…

…or in the first method containing such a handler, starting from the bottom of the current call chain, and looking up:

Exceptions are raised automatically when something goes wrong:

ReadElizaLine InputFrom, ElDelimiter , RespDelimiter wend InputFrom .Close Exception E As OutOfBoundsException MsgBox "That value is too large." Quit

• Method A calls…• Method B calls…• Method C calls…• Method D

Dim A As MyObjectA.MyMethod

Oops, A is still Nil here.

That’s a NilObjectException

155REALbasic Curriculum

Page 156: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Exceptions, Constructors, Overloading

…or you can raise an exception yourself:

You can even invent your own exceptions, which are just subclasses of the class Runt-imeException. You can add your own methods and properties to them, just as you can with any class, and then raise them when you want to deal with an unusual circum-stance:

(The argument to the New command here is part of a constructor, which we’ll learn about in a moment).

It’s important to realize that Exceptions are objects, having a class, with all that entails:

n They can be part of a class hierarchy

n Handlers can catch exception superclasses or subclasses;

n You can add methods and properties to them;

n They can carry error messages or other information; and

n They can carry out an action.

An exception handler can either catch all exceptions:

Or it can receive the exception object itself as an argument:

And it can also catch the exception only if it is of a particular type:

Raise New NilObjectException

Although you probablywouldn’t want to raise aNilObjectExceptiondeliberately.

Raise New MyException ("You goofed.")

Exception…

Exception E…

Exception E As NilObjectException…

156 REALbasic Curriculum

Page 157: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Exceptions, Constructors, Overloading

You can have multiple exception handlers at the end of a method. This example pro-vides specific handlers for two particular exceptions, then a general handler that will catch any other type of exception:

When there are multiple handlers like this, the handler matching the exception that is closest to the top of the code will be called.

The above exception handlers occur at the end of the methods in which they occur. You can also build a smaller exception handling block in just a part of a method, using the Try – Catch – Finally – End Try construct, which looks like this:

This is the equivalent of the first example above, because it catches all exceptions that occur between Try and Catch. You can also get the exception itself in a variable:

Exception E As NilObjectException…

Exception E As OutOfBoundsException…

Exception…

…Try

…Catch

…End Try…

…Try

…Catch E

…End Try…

157REALbasic Curriculum

Page 158: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Exceptions, Constructors, Overloading

And you can catch only exceptions of a particular type:

Another option you have with this kind of block is to provide code that must be exe-cuted after the Try block, whether or not an exception is raised. This uses a Finally sec-tion:

You should always think about whether there is anything that the Try-Catch block must make sure is true after it has finished (for example, it must close any files it opened), and put that into a Finally block.

Note that unlike with the Exception block, you can have nested Try-Catch blocks (meaning, having Try-Catch blocks inside Try-Catch blocks).

Default Exception Handling

If an exception is raised but no matching handler is encountered, REALbasic provides a default handling:

n In the IDE, REALbasic will highlight the line at which the exception was raised, and will display a message about the type of exception that was raised (you’ve doubtless seen this many times already):

…Try

…Catch E As NilObjectException

…End Try…

…Try

…Catch E As NilObjectException

…Finally

…End Try…

158 REALbasic Curriculum

Page 159: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Exceptions, Constructors, Overloading

Figure 55. Default Exception handling in the IDE.

n If you compile your program and run it separately from the development environment (which is usually your goal), when an exception is raised, REALbasic displays an error message and quits:

Figure 56. Default Exception handling in a compiled application.

You want to avoid having REALbasic display a message like this if you possibly can, so learning to handle Exceptions yourself is a very important.

REALbasic provides a special extra way to handle exceptions: an exception that is not handled anywhere else will trigger an UnhandledException event in App. You should always provide such a handler in an application you are providing to someone else, so that you can provide a more elegant way of dealing with unhandled exceptions than REALbasic’s rather scary automatic dialog.

That’s an overview of Exceptions; now we’ll examine them in action.

Exceptional Eliza1 Open the included project, Exceptional Eliza.

We’re going to make the Eliza file parsing1 routine handle various errors in the file. By using Exceptions, we will be able to leave the ‘regular’ parsing routines almost entirely intact, while adding some very different behavior in these ‘exceptional’ circumstances.

1. Parsing is pulling apart a string to get structured information out of it. Humans do it when we comprehend an English sentence, and computers do it with files.

159REALbasic Curriculum

Page 160: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Exceptions, Constructors, Overloading

2 Examine the File Parse Error class. Notice that it is intended to be an abstract superclass (it doesn’t do anything itself; when you call its Announce method, this just gets handed on to the subclass as an event).

3 Examine the NaughtyWordError class. Particularly make note of the NaughtyWordError method. This is a special method called a constructor.

Constructors and Destructors

A constructor is just a method named Constructor or, as in this case, it has the same name as the class. Any such method will run automatically when an object of that type is created.

Note that a constructor can have arguments, which you provide as arguments to the New command (as we did above).

You can also have a destructor, which runs when an object is no longer referenced by any variable (and that won’t continue to exist for any other reason — a Window is an example of something that will continue to exist even if nothing is referring to it). Such an object can never be used again (there is no way for your code to refer to it), so REALbasic reclaims the space it occupies. Before it does, it calls the object’s destructor if one exists, so you can use that to “clean up after” your object, if necessary.

A destructor is a method with no parameters and no return type, named Destructor.

Notice that technically speaking, constructors and destructors are not necessary. You can write any kind of program without writing them. But it is a good idea to use a con-structor in any class where it is appropriate, because it helps to avoid many errors.

n Examine the InvalidLineError class. Particularly make note of the two constructors. Having two or more methods or func-tions with the same name is called overloading the method.

Overloading

We can have more than one method or function with the same name, if at least one of their arguments is of a different type, or if they have a different number of arguments. Note that REALbasic will only be able to choose one version of the method for any particular call, since the arguments will only match one version.

Overloading is particularly common for constructors, but you should feel free to use overloading wherever that seems reasonable (we will see a number of examples of over-loading in this and coming lessons). Note that other than in the case of constructors, overloading is merely a convenience. It would make no huge difference to have meth-

160 REALbasic Curriculum

Page 161: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Exceptions, Constructors, Overloading

ods with different names. But you should use overloading whenever you have different ways of requesting what amounts to the same operation.

Limits on Overloading

The current REALbasic compiler has two limits on overloading you should be aware of:

n A class and its subclass are not considered different types when distinguishing between versions of an overloaded method. So if Thing is a superclass to SubThing, the following method definitions will not be distinguished:

n REALbasic searches for a match for a method call up through the class hierarchy; if a method is defined in a class, it will not see a different version of that method defined in a superclass. The solution is to override the superclass’s method in the subclass and to then direct a call back to the superclass’s method explicitly. We will cover how to call a method in a superclass in a coming lesson.

Take a quick look at StringList. This is all stuff we’ve seen before.

Examine the module BadThings. A feature of modules we’ve not seen before is that they can have constants, which are like variables whose values can’t change.

It is a good idea to use a named constant like this for any fixed value your program relies on, because it gives you a single place to change that value. In this case, it is stor-ing a list of naughty words you can’t have in the responses file.

Now examine the changes to the StringResponder class.

Note that the code to parse a line has been moved to a separate method, ReadEliza-Line. Double-click on the name of the method in the left pane of the code editor, and notice that the method is declared to be Protected.

Private Methods

Some methods will form part of the public interface of a class. These are the operations that define the Abstract Data Type that the class implements (remember: a type is defined by what it does), and are meant to be called from other classes.

Other methods in a class will be part of the class’s internal operations, and are not meant to be called from outside of the class. ReadElizaLine is a good example of such a method.

Sub MyMethod(t As Thing)…End Sub

Sub MyMethod(t As SubThing)…End Sub

161REALbasic Curriculum

Page 162: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Exceptions, Constructors, Overloading

Making the method Private indicates that a method is not part of the public interface for a class. When a method is Private, the compiler makes it impossible to call the method from outside the class. Also, subclasses of the class do not inherit the method.

Another alternative is the Protected method. Like Private methods, Protected meth-ods cannot be accessed from outside the class, but subclasses of the current class inherit Protected methods.

Back to Exceptions

Note how the Raise commands generate the object right in the command, and how the arguments are passed to the constructors for the class. Note that New is now obvi-ously behaving as a function (which it was all along…)

Observe the locations of the Raise commands and the method handlers (use the Search area in the main toolbar to find these calls). Note that we have a handler for both the base class FileParseError (in LoadFromFile) and the subclass Naughty-WordError in ReadElizaLine.

Open the Responses.txt file, and see if you can find the two places where the exceptions will be raised.

1 Run the project, put breakpoints everywhere an exception is raised, and step through what happens in each case.Notice that the exception for the NaughtyWordError handler (in the ReadElizaLine method) causes the project to skip the line, but to continue parsing the file. On the other hand, the breakpoint for the FileParseError (in LoadFromFile) aborts the pars-ing process. Try commenting out the Quit command in the FileParseError handler to make this clearer.

2 Comment out the NaughtyWordError handler, and observe the behavior when the project is run.

3 Leaving the NaughtyWordError handler commented out, move the FileParseError handler into the ReadElizaLine method, but remove its Quit command. Now see what happens when the errors occur.

Further Exercises

If you comment out the Quit commands from all of the exception handlers and run the program, it will display a couple of alerts and then run. But try entering a phrase that doesn’t merit one of the canned responses (so it should get a random response; a good example would be ‘Hello’). The program will quit with an OutOf BoundsExcep-tion. You can fix this by fixing the Responses.txt file, but you should also make the pro-gram handle this better. Add a suitable Outof BoundsException handler.

162 REALbasic Curriculum

Page 163: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Exceptions, Constructors, Overloading

Another interesting exercise would be to have the Exceptions record themselves (say in an ExceptionLog class), and then report themselves at the end of the parsing process, before the project can continue. In case it isn’t obvious, the best place to record the generation of an object will be in its constructor…

163REALbasic Curriculum

Page 164: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Exceptions, Constructors, Overloading

164 REALbasic Curriculum

Page 165: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 18 File Enumerator

Aim

We’re taking a breather from learning new programming concepts, and putting some of these concepts together in a useful project.

A Useful Class: A File Enumerator

We’ve absorbed a lot of concepts in the course so far. We’re going to switch over to using these features to design a very useful class. This will be a flexible file enumerator.

Enumerating is a fancy programmer’s term for going through a set of things one at a time (a similar term you might see is traversing). We will create a class you can point at a folder or a file, and our class will generate an event for each item in that folder.

Design Issues

There are a few major approaches we could take to this project:

n We could create a class that traverses part of the file tree, providing its subclass with an opportunity to process each file as it does so; or

n We could create a class that repeatedly calls a separate file receiver class as it traverses the file tree; or

n We could make the traversal class passive, driven by repeated calls from outside, asking for the next file.

165REALbasic Curriculum

Page 166: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

File Enumerator

The approach we will take is the first one; if we wish, we can extend it to create the sec-ond. The third approach will tend to be more cumbersome — the external caller will need to keep checking the state of the file traversal, checking whether the traversal has finished, for example.

Before we go on, you should read about the FolderItem class.

Depth First vs. Breadth First

Files are arranged in a tree structure of folders, sub-folders, sub-sub-folders, and so on. Classes are in a similar tree structure of classes, subclasses, sub-subclasses, and so on. Tree structures for information are very common in computer programming, and dealing with them will often involve enumerating their contents as we are doing in this project.

There are two main ways of traversing a tree structure:

n In a depth-first traversal, when we encounter a folder in the current folder, we immediately start enumerating its contents, and immediately into any subfolder of that folder we come to, and so on. We will eventually get back to the rest of the items in a folder after enumerating the contents of its sub-folder; or

n In a breadth-first traversal, we enumerate all the files in the current folder, then enumerate the contents of any folders in the current folder.We will see both of these techniques in action in this lesson’s project.

The Project1 Open the project 18_FileEnumerator. Open the FileEnumerator class.

Notice that the class has a constructor, one public method, several private methods and three new events.Two of these events allow a subclass to determine how the enumeration takes place (DepthFirst) and allows a subclass to interrupt the iteration (Stop). Both of these work just fine with the default return value. So a subclass really only needs to implement one event handler (EnumerateItem).

2 Open the FileCounter class, and see how straightforward it is to create a child class that counts the files in a location.

3 Go back to the FileEnumerator class and examine the recursive structure of the file enumeration process. Note how a depth-first enumeration is carried out by immediately recursively enumer-ating any folder we come to when we come to them, while a breadth-first enumeration is performed by enumerating all the items in a folder, and then recursively enumerating the contents of any sub-folders.

166 REALbasic Curriculum

Page 167: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

File Enumerator

4 Put a breakpoint in the Enumerate method of FileEnumerator. Run the program, and choose a folder with a small number of files and one or two subfolders. Trace through the execution. Then comment out the command:

from the DepthFirst event handler for the FileCounter class, run the program, and choose the same folder.

TrueItem

Note that when we pick out a particular item in a folder, we use the TrueItem function rather than the Item function of the FolderItem. The difference lies in the treatment of shortcuts (shortcuts are called aliases on Macintosh): Item directed at a shortcut will work with the file the shortcut points at, while TrueItem will work on the shortcut file itself.

This was important to do, because if we were following shortcuts to their source, it would be possible to get stuck in a looped directory structure, in which a shortcut pointed back at one of the folders it was contained in, causing the enumeration process to run forever.

It would clearly be better if we supported following shortcuts to their original file, and in a later project we will do that; in fact, we will notify the subclass through an event that we’ve encountered a shortcut, and let the subclass choose whether or not we fol-low it.

Even better, we will build a class that can’t get stuck in a loop, no matter what the sub-class does. However, doing this is a surprising amount of extra work, and we will wind up building quite a bit of infrastructure to make this work efficiently in the coming lessons.

Concepts We’ve Used In This Project

Notice that this project uses recursion. This is a natural way to approach this problem, because the data involved has a recursive structure (a folder is the same type of thing as the folder it is within).

Notice that we’ve built a class that must be subclassed in order to do anything useful. Notice also that we’ve built a flexible class that can be used in a variety of ways. Armed with this class, you can make a variety of small file utilities very quickly. Notice how lit-tle extra code is involved in using this class to create a program that can count files and folders, for example.

Return True

167REALbasic Curriculum

Page 168: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

File Enumerator

Further Exercises

There are any number of potential exercises one could undertake from these begin-nings. Try to develop a useful file utility for yourself. Perhaps something that lists all the files anywhere within a folder, for example.

One nice enhancement would be to give the subclass the ability to decide whether a shortcut or its target should be enumerated. Probably the best way to do that would be to use a special event for an alias: EnumerateAlias( f As FolderItem, g As FolderItem) As Boolean. The method would return True to indicate that the target should be enumer-ated if it is a folder, False if it should not. You should think about the looping directory structure problem. It isn’t too hard to construct a simple solution, but it is a fair bit more work to devise something that doesn’t slow down very badly as the directory structure you’re searching gets bigger.

168 REALbasic Curriculum

Page 169: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 19 Data Structures

Aim

We want to make a version of the File Enumerator that can handle folder shortcuts without getting trapped in loops that can be caused by them.

The only practical way to avoid this looping problem is to keep a list of all the folders enumerated so far. Before we enumerate a folder, we check whether it is already in the list.

Now, a modern computer can have thousands of folders, and building and searching that list every time we encounter a folder takes us well into the territory of wanting to be concerned with efficiency1.

If we just keep this list in the kinds of simple data structures we’ve been using so far (say, an array of strings), and search that list from one end to the other (called a linear search), this searching process will slow the whole enumeration process significantly as the list gets long.

1. Actually, this still depends on the economics of our situation. If we’re building a utility to do something once or very occasionally, or if processing each file is going to take a long time anyway, it won’t be worth spending time to optimize this stuff. However, we are building something general-purpose and reusable here, so we can optimize it once, and use it again and again, so it will be worthwhile spending time to make it fast.

169REALbasic Curriculum

Page 170: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Data Structures

With all of this in mind, this lesson will examine a number of different data structures for storing and searching a list of strings. Note that REALbasic has a built-in data structure that can do what we need, the Dictionary. But we will learn a lot by imple-menting our own solution.

The Project

Following the ideas we’ve been talking about, we’re going to develop a class we will call a String Accumulator, that keeps a list of strings. It has one main method, to which you hand a string. If the string is already in the list, it returns True; if not, the string is added to the list, and it returns False. Thus, we can feed the path of the folder we’re about to follow into this method, and it will tell us whether we’ve already searched it.

In this lesson, we will examine three different data structures for storing the list, and two different algorithms for searching each of these data structures. We will use a framework that allows us to test the speed of the data structures and algorithms.

Make sure you spend some time thinking about how you might implement the string accumulator, using what we’ve learned so far.

As we saw in a previous lesson, we don’t have a practical way to understand exactly what REALbasic is doing behind the scenes of our code. When it comes to efficiency questions, the only reliable way to determine what is the most efficient code for a given task is to set up a test.

1 Open the project 19_StringAccumulator.The project’s main window provides two buttons. The top one lets you run a timing test comparing different implementations of a string accumulator. The bottom button lets you run a simple test on a single accumulator. Neither of the buttons have any out-put deliberately: this project is just the kind of minimal but functional framework a developer would probably put together in practice to run some timing comparisons. You can just apply breakpoints at a suitable point in a method to determine how things are going. For instance, you would put a break point on the last blank line of the top button and then examine the contents of the array Timings if you want to run a timing test.

2 Begin by examining the very simple StringAccumulator class.

3 Now examine the ArrayStringAccumulator class. This might have been what you envisaged when you thought about how to create the StringAccumulator class.

Binary Search

One way to speed up a search through a sorted list is a binary search, in which you repeatedly cut the list in half. You start looking at the middle element in the list, and cut your search to the first or last half of the list, according to where the element you’re

170 REALbasic Curriculum

Page 171: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Data Structures

searching for is. You then look to the middle of that sub-list, and cut the list in half again. Lather, rinse, repeat.

1 Examine the code in the BinaryArrayStringAccumulator.

2 Examine the code for the RunButton in the window. Comment out the code to add all but the BinaryArrayStringAccumulator and the ArrayStringAccumulator.

3 Make sure you have a break point at the end of the method.

4 Run the project and click the button. Examine the values in the Timings array at the end. You might be surprised at how much faster the binary search is.

If your math is up to it, note that a linear search through N items will average about 1/2N comparisons, while a binary search will average about log2N comparisons.

Before we go on, you should review the PowerPoint presentation: About Memory Management.

Based on what you learned about memory management, we should consider using a Linked List built out of a series of separate objects. It would be impossible to do a binary search on such a list, but inserting an item into such a list can be done in a con-stant amount of time, no matter how big the list is. What is not clear is whether such a list would be faster than the other lists we’ve looked at.

5 Examine the ListStringAccumulator2 class’s code, and then comment it back in to the button’s code, and run the project.Ouch. The new class is still half the speed of the ArrayStringAccumulator, let alone the binary search array.

Next, we are going to examine some tree data structures. These are very common types of data structures, and we will look at one of the simplest, a Binary Tree.

About Binary Trees

The data in a binary tree is contained in Nodes, which are joined by Edges (these will be objects as the nodes, and references to the other objects as edges):

171REALbasic Curriculum

Page 172: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Data Structures

Figure 57. An example of a binary tree.

In Figure 57, the numbers are contained in the nodes, and the arrows represent the edges. Each node has a less than and a greater than edge (either or both might be Nil).

To find something in a binary tree, just follow the edges:

Figure 58. Locate a value by following the edges.

To insert something, find where it should be, and insert it there:

6

4

1 5

9

6

4

1 5

9

5

172 REALbasic Curriculum

Page 173: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Data Structures

Figure 59. Insert something where it belongs.

A potential problem: the ‘shape’ of the tree depends on the order in which nodes were added:

Figure 60. An unbalanced binary tree.

The tree in An unbalanced binary tree.4 is unbalanced, and will work as badly as or worse than a straight linked list would.

6 Examine the code driving the BinaryTreeAccumulator class. Run it from the TestOneButton, tracing through it as you go.

7 Examine the non-recursive BinaryTreeAccumulator2 class. If you are unclear how it works, trace through it from the TestOneButton.

8 Rearrange the RunButton method so we can compare the timings for the two BinaryTreeAccumulator classes and the BinaryArrayStringAccumulator. Comment out the StackOverflowException handler. Run the application.

Wow. BinaryArrayStringAccumulator is still many times faster than any other approach we’ve tried.

6

4

1 5 9

7

7

1

3

4

5

2

34

5

2This is probably even worse than a linked list…

173REALbasic Curriculum

Page 174: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Data Structures

Other Approaches

The BinaryArrayStringAccumulator is reasonably fast; certainly, many times faster than a linearly-searched list. It will suffice for our file enumerator project.

Nevertheless, it is interesting to consider how we might make our ArrayStringAccumu-lator faster. We could use a smarter type of tree that always stays balanced: a 2-3 Tree. There is also a source of inefficiency in all of our classes: REALbasic doesn’t know that we are never going to resize our strings, or that we are going to need to store a lot of strings. By taking control of our own memory management at a lower level (using the MemoryBlock class), we could make all of these classes faster. Using a scheme like this, we might well find that the BinaryArrayStringAccumulator version is no longer the fastest.

Any textbook on data structures should describe the 2-3 tree — it is one of the most basic data structures in computer science; for the same reason, it should not be hard to find a description of the 2-3 tree online. However, there is a reasonable amount of cod-ing involved in implementing a 2-3 tree, putting it a little out of the scope of this course. Also, REALbasic’s built-in data-storage features (particularly the Dictionary class) means that you are unlikely to need to implement a data structure like that to program in REALbasic.

Other Improvements

You should read the REALbasic documentation about the MemoryBlock. A Memory-Block is a very simple chunk of memory, basically just an array of bytes. Because it is so simple, it is also very fast. REALbasic doesn’t go to the extra trouble required to make strings so much more flexible. This means you can take advantage of your knowledge that the strings you are storing will not need to change size, to make them work faster. You could even keep an entire binary or 2-3 tree, or for that matter our simple list, in a large MemoryBlock, which would also be substantially faster.

There is one more reasonably simple and very flexible and efficient way of speeding up almost any data structure, called hashing. We will employ hashing in a lesson fairly soon, and we will see a substantial improvement over our binary searched list at that time. For the time being, though, we have a class that will provide reasonable perfor-mance for our file enumerator, so we will go back to the file enumerator in the next les-son.

Further Exercises

There are a great many potential exercises that can be pursued from here.

A nice one would be a fairly simple way of speeding up either of the array-based classes: resize them rarely and in large increments. This would involve keeping separate track of how much of the allocated size is actually used, allocating say 1000 or 10000

174 REALbasic Curriculum

Page 175: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Data Structures

elements in the constructor, and, say, doubling the size of the array when it runs out of space. Note that a construct like this (at the end of a SubRangeSearch method, in this example):

is both perfectly acceptable and certainly the easiest way to take care of the array resiz-ing.

Exception E As OutOfBoundsExceptionReDim TheStrings(2*Ubound(TheStrings))SubRangeSearch(S, x, y)

175REALbasic Curriculum

Page 176: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Data Structures

Appendix: About Memory Management

Your program’s memory is basically a single enormous array of bytes. A byte is a num-ber between 0 and 255.

REALbasic takes care of managing that memory for you. You can create, destroy and resize variables and objects without worrying about the details. Behind the scenes, RB is tracking:

n Where each object you create is stored;

n Whether an object is still being used;

n When an object is no longer being used and the space it occupied can be reclaimed;

n Where the free space and the occupied space is; and

n A bunch of other stuff…

So if you change the size of an array or string, REALbasic decides whether the space the variable is currently taking up is big enough. If that space is not big enough, the existing content of the variable is moved to the new space, and the old space is reclaimed.

After a lot of creating and destroying objects…

Figure 61. An illustration of fragmented memory.

…the memory fragments, or becomes a mix of empty and filled chunks. Then if you try to create a big object, or to make an existing object much bigger, the computer has to move a bunch of things around to make space.

So if you’re concerned about efficiency:

n Resize things infrequently, in large chunks, rather than one character or element at a time;

n Consider reusing objects rather than destroying an object and creating a new one of the same type;

n Consider taking over memory management for important objects using a MemoryBlock.

It is worth noting that the developers of REALbasic try to shield us from needing to do this, and they have succeeded on the whole at making these considerations only important in very performance-critical situations. As an example, if you ask REALba-sic to resize an array one element at a time, it doesn’t actually do that; it secretly resizes the array in somewhat larger chunks, keeping track of how much of the space it has allocated you are actually using.

176 REALbasic Curriculum

Page 177: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 20 File Enumerator 2

Aim

We pull the results of our last project into the file enumerator project from the previ-ous lesson, and refine the file enumerator a bit as well. Something a bit lighter after our last project.

Analyze the Problem

Start by thinking about our objective: We want the FileEnumerator class to handle shortcuts in an intelligent way. It should do as much work as is reasonable, while leav-ing all the major choices up to the subclass (we did that already, for example, with the choice of whether the enumeration should be depth-first or breadth-first). So stop and think for a bit about how we should deal with shortcuts.

The first thing to notice is that the subclass should decide whether a shortcut should be followed to its original or not. The solution is to provide a FollowAlias Event that lets the subclass decide.

But here’s another, subtler design issue: should the shortcut file be enumerated as a regular file? Since we will be passing the FolderItem for the alias to the FollowAlias event, we choose to not pass that same FolderItem through to the EnumerateItem event.

This is because, if the subclass wants to process the aliases along with the other files, it can do so in the FollowAlias event quite easily. However, if instead the subclass wants

177REALbasic Curriculum

Page 178: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

File Enumerator 2

to ignore the shortcuts, it doesn’t need to check each FolderItem it enumerates, to see if it is a shortcut. As for the files pointed at by the shortcuts, we enumerate them through the regular EnumerateItem event, if the FollowAlias event returns True. This design will be flexible, but simple to use, no matter what the behavior desired for aliases is.

The other issue we encounter is how to prevent shortcuts from getting us trapped in loops. This is easy to deal with now: before we enumerate a folder, we check whether its path1 is in a list of the paths of already-enumerated folders. If it is in this list, we skip it; if it isn’t, we add it to the list and enumerate it and its contents.

The Project1 Open the file enumerator project from Lesson 18, and examine where the

string accumulator could be used to avoid loops caused by shortcuts.

2 Now open the updated version, 20_FileEnumerator2.The project has been rebuilt to better accommodate the new goals. The simplest way to break out encountering a shortcut into a separate event is to use a subclass. How-ever, the code for that needs some changes in the FileEnumerator class to work prop-erly.

Accordingly, FileEnumerator has been modified so that rather than giving it the path to enumerate in a constructor, we pass it to the Enumerate call. This allows the sub-class to recursively re-initiate the enumeration process as it needs.

While we were making changes to this class, we also broke out encountering a folder to its own event, giving the subclass the opportunity to override enumeration of a folder. Note that the default behavior is not to enumerate the folder; the subclass must return True in the EnumerateFolder event if the folder’s contents are to be enumerated.

Why do it this way? Because there was no good name for an event with the opposite interpretation. There is some value in having a good self-documenting name…

3 Examine the class in which we add the alias-handling behavior.Notice how the events mechanism lets us ‘re-interpret’ an event: FileEnumerator enu-merates everything it encounters through the EnumerateFolder and EnumerateItem events, without regard to whether any of the items are aliases. FileAliasEnumerator intercepts that EnumerateItem event, and splits the alias enumeration off into a differ-ent event.

4 Run the code and try it out on some medium-sized folders. The speed is not bad, even in the debugger.

1. The path of a file is a string that specifies exactly where it is. All files and folders have a unique path.

178 REALbasic Curriculum

Page 179: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

File Enumerator 2

We probably did the speed issue to death for now, but if you have time, it might be interesting to swap in a much slower string accumulator class and see how that affects the speed.

5 Finally, try enumerating a really big folder (say, the root of the main drive). If you have a lot of really deeply nested folders, you might even see a stack overflow (though it’s unlikely).

We will consider how to resolve the stack overflow problem in a later lesson.

Further Exercises

Think about the types of utilities that could be developed based on the file enumera-tion capability we have here.

Before we do it in a later lesson, you might like to try to build a non-recursive version of this project.

It would be cleaner to have the FileAliasEnumerator capability folded back into the main class.

179REALbasic Curriculum

Page 180: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

File Enumerator 2

180 REALbasic Curriculum

Page 181: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 21 Hashing

Aim

We combine a simple data structure called a hash table with the simple linear list from an earlier lesson. The result is a data structure that is much faster than the binary-searched array.

About Hash Tables

Hashing is a very simple, very widely used technique to speed up virtually any data structure. It must be combined with another data structure, because what it does is to separate the items to be stored and searched into many smaller groups; but we still have to store and search those groups somehow.

The reason this is fast is because we can split one large data structure into many smaller data structures. The splitting is fast, and takes the same amount of time, no matter how many groups we have.

The groups are made by devising a way of consistently generating a hash key from every possible value to be stored. This hash number should have the following properties:

n It should be reasonably fast to generate;

n It should be in a reasonably small range (in the range of the number of groups you want);

181REALbasic Curriculum

Page 182: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Hashing

n It should minimize collisions (values that wind up in with the same key). This means that a very ‘random’ set of values should be evenly distributed, but also a set of, for example, very similar values should generate very different hash numbers.This second criterion is sufficiently open to interpretation to have produced a reason-able amount of debate in computer programming circles. You will find a large range of hashing functions in computer science textbooks and on the Internet. The algorithm we are using is a reasonably robust one found online. Unfortunately, while the hash function itself is reasonably simple, the math behind the choice of a hash function is actually reasonably complex. If you are interested in the issues involved in devising a hash function, consult a suitable computer science text. One of the best (for this and many other topics) is The Art of Computer Programming1.

One thing that helps with almost any hashing function is to have a prime modulus (the number of groups is called the modulus of the hash function).

Activities and Procedures1 Open the project 21_Hashing.

2 Examine the code in the Hash module, then the HashStringAccumulator and the ListHashStringAccumulator.Notice how simple this all really is. Also make sure you notice how HashStringAccu-mulator and ListHashStringAccumulator work together: rather than an explicit event passing from one to the other, the subclass only has to set up the hash table’s contents. HashStringAccumulator can employ any StringAccumulator in the hash table poly-morphically; so once the subclass has set up some kind of StringAccumulator in each of the elements of the hash table, its job is done. All of this means that all the subclass needs to supply is a constructor.

Also notice that both the HashStringAccumulator and the contents of its hash table are both StringAccumulators, because they both do the same thing2.

The value of the HashMod constant is a reasonable one for a relatively small amount of data such as we have in this project. To make following what is happening easier, change it to a small value (say, 5). Run the project, trying various values of HashMod.

1. In this case, you would consult Volume 3, but the whole series is an absolute work of art.KNUTH, D E, THE ART OF COMPUTER PROGRAMMING, 2ND ED, ADDISON WESLEY, READING MASS, 1997 ISBN 0-201-89685-0.

2. This is not an uncommon type of strategy. A similar thing you might do on occasion pro-vides a solution to a common problem: you have a class that calls a method on a single object of some type. You later decide that you now want it to call that method on each of a group of such objects. Rather than modify the class definition, you can write an intermediary class of the same type as the single class your class is calling now, and have your new ‘adapter’ class pass that call on to a whole group of objects.

182 REALbasic Curriculum

Page 183: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Hashing

You might also like to try creating other subclasses of HashStringAccumulator and tim-ing them.

Further Exercises

A good test of your understanding of hashing is to see if you can create a two-level hashing structure (hash tables containing hash tables, that then contain some other structure such as a list). Think for a while about how you might do this.

Bonus points if you stopped to think about that, and you realized that you need to use different HashMod values for the two different levels1.

1. In practice, it will almost certainly be better to have one big hash table than multiple levels of hash tables. One table is simpler, and you only have to run the hash number calculation once.

183REALbasic Curriculum

Page 184: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Hashing

184 REALbasic Curriculum

Page 185: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 22 Cyclic Redundancy Check

Aim

This lesson explores the strange world of binary arithmetic, through the implementa-tion of a very important algorithm, the Fast Cyclic Redundancy Check.

The theory involved is not actually very complicated, but it does involve learning a new kind of math. It’s considerably easier than, say, the basic arithmetic you learned in Primary School. But it is a little strange, so if you don’t feel it’s your cup of tea, that’s fine. Let’s call this lesson optional.

We’re doing this lesson because Cyclic Redundancy Checks (CRCs) are very impor-tant, but also because we it’s a good lesson involving binary arithmetic. There are many, many thousands of web sites and books available that can teach you basic binary arithmetic, so there seemed little point covering the same ground. Instead, we’re doing a lesson designed to get you to stretch your ideas about what all those 1s and 0s inside your computer are good for.

Also, a very broadly useful technique is used in the project to speed up the CRC calcu-lation.

185REALbasic Curriculum

Page 186: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Cyclic Redundancy Check

Learn Basic Binary Math

Binary math is math base 2. It works just like the base 10 math you do all the time, but it only uses 1 and 0, and rather than the digits in a number representing 1s, 10s, 100s and so on, they represent 1s, 2s, 4s, 8s and so on. If at any time in this lesson you feel you need more information about how to do binary math, try doing a google search for “binary math”. One page that looked useful was:

http://www.math.grin.edu/~rebelsky/Courses/152/97F/Readings/student-binary.html.

What is a Cyclic Redundancy Check?

It is common to want to compare two pieces of data that are separated in time or space, in a situation where you only have one or even neither of the two pieces available. You might have transmitted something over a network, or you’ve stored it for some period of time in some way, and you now want to determine if what you have is the same as the original.

A CRC is a way to do this: it is a short ‘signature’ generated from the data, in such a way that if the data has changed, the signature will almost certainly be different.

Since the CRC is generally much shorter than the data it is derived from, it is inevita-ble that many possible blocks of data will generate the same CRC. What we want, though, is to guarantee that the CRC will not be the same given expected patterns of errors (such as single bits being switched, bursts of sequential bits being switched, and so on).

The math is a bit beyond the scope of this lesson, but it is not too hard to prove that the CRC we’re going to use here meets these kinds of criteria. See, for example,

http://www.cs.williams.edu/~tom/courses/336/outlines/lect7_2.html

for a proof of this.

Math with Polynomials Modulo 2

In this lesson, we’re going to combine the computer’s native 1s and 0s into things that are almost numbers. Technically, they’re polynomials modulo 21. They’re almost num-bers because we can perform operations with them that are equivalent to the opera-tions you are used to performing with numbers.

1. See “Appendix 1: Polynomials Modulo 2” on page 193 if you’d like a little more explana-tion of what Polynomials Modulo 2 actually means. You don’t need to know this to complete the lesson, but we didn’t want to leave you dying to know why we use that term.

186 REALbasic Curriculum

Page 187: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Cyclic Redundancy Check

A polynomial modulo 2 is a string of 1s and 0s, just like a regular binary number. For simplicity, we’ll refer to them from here on as CRC numbers.

You can perform the usual addition, subtraction, multiplication, and division with CRC numbers, the same way you perform those operations with regular binary num-bers, with one exception: you ignore carries1.

The only operation we need for the CRC is division. In fact, calculating a CRC is just the remainder after dividing the data by a particular, fixed polynomial (usually referred to as ‘the poly’).

Now, division amounts to repeated subtraction:7192 ______72 )517843 504 ---- 138 72 ---- 664 648 ---- 163 144 -- 19

In this calculation, 72 is the divisor, 7192 is the result and 517843 is the dividend. There doesn’t seem to be a proper term for each of the numbers we subtract as we carry out the algorithm, so we’ll call these numbers (such as 504 from the first step here) the subtractor. And we’ll call the number we get after subtracting the subtractor and then bringing down the next digit the goal.

We will use the same algorithm for our modulo 2 division; we just need to know how to do modulo 2 subtraction, and also how to work out how many ‘times’ the divisor to subtract to get the subtractor at each step.

We’ll start by observing that we’re working in binary, so the second question amounts to whether to subtract 0 or 1 times the divisor — in other words, whether to subtract the divisor or not. And this just amounts to asking whether the dividend is less than the goal or not.

1. When you add 22 to 39 on a piece of paper, you add 2 to 9 and get 11. You write 1 under the 2 and the 9, then you write a little 1 somewhere above or below the 2 and the 3 in the next column. That little 1 is a carry, and in math with polynomials modulo 2, you just throw it away. This math thus becomes simpler and very fast.

187REALbasic Curriculum

Page 188: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Cyclic Redundancy Check

Subtraction of polynomials modulo 2 turns out to be the same as addition without carries, and is actually just the same as the exclusive or operation. We can see this by noting that since we are ignoring carries, each position in the addition or subtraction is entirely independent of the positions around it. So let’s look at adding or subtracting 1s and 0s when we ignore carries:

0 + 0 = 00 - 0 = 01 + 1 = 0 (because 1+1=10 in binary, but we drop the 1 carried over)1 - 1 = 0

0 - 1 = 1 (because 1+1=0)1 - 0 = 10 + 1 = 11 + 0 = 1

So whether we are adding or subtracting, two 1s or two 0s give us a 0, while a 1 and a 0 give us 1.

This turns out to be the same thing as the exclusive or operation (see Appendix 2: Boolean Operators, 194, for more about operations like exclusive or).

Back to determining when one number is less than or greater than another. Since addi-tion and subtraction are the same, all we can do for numbers of the same length is to compare their left most digits; if both have the same left most digit, you can regard either as the bigger one. Again, this makes the CRC calculation easy: if the first digit of both the goal and the dividend is the same, we subtract (exclusive or) the dividend; if they are different, we don’t. Actually, it’s even easier than this: the poly for a CRC always starts with a 1, so we just have to look at the next digit of the goal: if it’s 1, we exclusive or the poly; if it isn’t, we don’t.

An Example

To calculate a CRC, find the number of digits in the poly, and append one less zeroes to the data. So in the example we’re about to see, since our poly is 10011, which has five digits, we will append four 0s (0000). Now just calculate the remainder when you divide by the poly, ignoring carries:

188 REALbasic Curriculum

Page 189: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Cyclic Redundancy Check

1100001010 _______________10011 ) 11010110110000 10011,,.,,.... -----,,.,,.... 10011,.,,.... 10011,.,,.... -----,.,,.... 00001.,,.... 00000.,,.... -----.,,.... 00010,,.... 00000,,.... -----,,.... 00101,.... 00000,.... -----,.... 01011.... 00000.... -----.... 10110... 10011... -----... 01010.. 00000.. -----.. 10100. 10011. -----. 01110 00000 ----- 1110

Let’s look at the first few operations:

n Our first step is to divide 10011 into 11010 (notice that we only need to look at the same number of digits as our poly has at one time). Since 11010 starts with a 1, and our poly always starts with a 1, we can regard the Poly as smaller, so we subtract it. The result is 01001. We remove the 0 from the left end, and shuffle in the next digit of our data (this is just the regular long division algorithm), to get 10011, our next goal.

n Now we’re dividing the poly into 10011. Again, the left digit is a 1, so we subtract the poly again. This gives us 00000, so after we shuffle the next digit of the data in, we have 00001.

n Now, the left digit is a 0, so we don’t subtract the poly. We still have 00001, so now we shuffle the next digit of the data in, to get 00010.

189REALbasic Curriculum

Page 190: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Cyclic Redundancy Check

n Same thing again, so we get 00101.And so on. Since our poly always starts with a 1, the process winds up being very sim-ple: if the current left over starts with a 1, we exclusive or the poly, if not we don’t. Then we move the next digit of our data into the leftover from the right, wash, rinse and repeat.

Speeding it Up

Take a look at the first few lines of our worked example:

1100001010 _______________10011 ) 11010110110000 10011,,.,,.... -----,,.,,.... 10011,.,,.... 10011,.,,.... -----,.,,.... 00001.,,....

Note that XORing a series of numbers together can be done in any order1. To calculate a XOr b XOr c, we can calculate a XOr b and XOr the result with c, or we can calculate b XOr c, and then XOr the result with a. This is similar to addition and multiplication, which we can also perform in any order.

Now, consider what happens as we perform the XOrs for each pair of digits in the div-idend: for any possible pair of digits in the dividend, we will always be XOring with the same pair of values. So, if we look at the first two steps of the example, we will be XOr-ing with:

10011, 10011 -----110101

So we can perform the first two steps of the calculation above by XOring with 110101.

If we perform the equivalent computation for all four possible values that a pair of dig-its from the dividend can have, we can then step through the dividend two digits at a time, by XOring with a value looked up in the table. Here is what that table looks like:

1. The technical way of saying this is: ‘the XOR operation is commutative’.

190 REALbasic Curriculum

Page 191: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Cyclic Redundancy Check

The most common speedup is to extend this idea to construct a 256-element table, and to feed through the data one byte at a time.

One final comment: you need to use very particular polys to get good results. Calcu-lating what would be a good poly requires some slightly hairier math than we want to get into here. The Institute of Electrical and Electronic Engineers (IEEE, http://www.ieee.org) is a good source for such information. A search on google for “crc polynomials ieee” will quickly find you a list of good polys to use for different lengths of CRCs. The one used in the example project is a good poly for 32-bit CRCs, and 32 bits is a good length for most purposes.

The Project

The included project implements a table-driven CRC in REALbasic.

The code is fairly short and simple.1 Open the CRC project and look at the code in the CRC Class. Begin with the

BuildTable method.Building the table is straightforward: you just perform the calculations of the CRC for all the binary numbers from 0 to 255, one bit at a time.

2 Now look at the constructor. Notice that we build the table, and set the starting value of the CRC to all 1s.

3 Next, look at the Add method, to which you pass a string. It just loops over the bytes in the string, XORing the current value of the register with the corresponding table entry.

4 Finally, note that getting the result out is a separate operation from the calculation of the CRC (via the Value method).

Data XOr with

00 00000000000000000

01 00000010011010011

10 10011000000100110

11 10011010011110101

191REALbasic Curriculum

Page 192: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Cyclic Redundancy Check

By doing it this way, we can feed the data through in a series of stages. We can just keep calling Add with some chunk of our data, until we’ve read through all our data. This is particularly useful for, say, communication software, which might be receiving some data in chunks, rather than all at once.

Using CRCs

Remember what CRCs do: they give you a signature for some data. The uses for this capability are limited only by your imagination. A couple of examples:

n You might use a CRC on a file to ensure it wasn’t modified (perhaps your program’s preferences file);

n You could calculate a CRC for a document and then encrypt it. If you use a public key encryption method, someone would be able to verify that a document came from you (because they could decrypt the encrypted key and get a valid CRC for the document). If you don’t know what public key encryption is, read about it online. It’s an amazing and very useful form of encryption.

Further Exercises

There are a number of interesting exercises from this point:

n Extend the example to use a 65536-element table, so we can double the speed of the calculation.

n Modify the example so we only need to compute the table once — particularly useful for the 65536-element case. This will probably involve creating a separate table object or Module property, and passing it to the CRC calculator.

n Overload the Add operator to accept other data types: an array of strings; a number; an array of numbers.

192 REALbasic Curriculum

Page 193: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Cyclic Redundancy Check

Appendix 1: Polynomials Modulo 2

Why are these polynomials, and why are they modulo 2?

Math Modulo n

Performing math modulo something (where something here is a number) is like doing math on a clock face (actually, that would be math modulo 12). Adding and subtract-ing is then just moving clockwise or anti-clockwise around the clock face.

Another way of looking at this is that to do math modulo n, you just find the remain-der after you divide by n after any operation.

So in math modulo 12, if you add 8 to 9, you get 5 (try looking at a clock face, and move clockwise 8 steps from 9; or calculate 8 + 9 (17), and then find the remainder after you divide by 12 (5).

Polynomial Math

A polynomial is an expression like 3x5+8x3+x2+5x-1. You can’t simplify this expres-sion until you know what x is, but there is a whole branch of math concerned with math with polynomials just left in this form. You can add two polynomials together, by just adding the coefficients (the numbers in front of the xs) in each place, so

3x5+8x3+x2+5x-1 + 4x5+2x3-6x2+2x+4 = 7x5+10x3-5x2+7x+3.

Polynomials Modulo 2

When the coefficients are modulo 2, the math becomes very simple. The polynomial means the coefficients are added separately and as we saw, the modulo 2 means that the add and subtract operation amounts to exclusive or.

193REALbasic Curriculum

Page 194: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Cyclic Redundancy Check

Appendix 2: Boolean Operators

An operation on binary numbers is just like any other kind of operator: it represents a calculation that takes one or more values and generates a new value.

Operations on binary values are special because we can also consider them as Boolean operators, and in fact this is how they’re usually named. And just as we can use a multi-plication table to represent the results of a multiplication operation, we can use a truth table to represent the results of a Boolean operation. It is customary to consider 1 as True and 0 as False. Here is a truth table for the Or operator:

So:

n 0 OR 0 = 0

n 0 OR 1 = 1and so on.

We can see these as operations with truth values if we consider how we use or with real-world truths or falsehoods: Is it true that:

n This document is about REALbasic or the moon is blue (True or False = True, 1 Or 0 = 1)?

n The moon is blue or the world is flat (False or False = False, 0 Or 0 = 0)?

n This document is about REALbasic or the world is round (True or True = True, 1 Or 1 = 1)?

Here is the truth table for the And operator:

Bitwise Boolean Operators

REALbasic’s regular Boolean operators are used in almost every program. We’ll assume you’ve used these before now.

REALbasic also provides a set of Boolean operators that work on groups of binary val-ues at once. These groups of binary values you’re used to calling “integers”, but we can treat an integer as an ordered set of 32 Boolean values. REALbasic’s Bitwise operators then perform a Boolean operation using the corresponding bits of each of the values.

OR 0 1

0 0 1

1 1 1

AND 0 1

0 0 0

1 0 1

194 REALbasic Curriculum

Page 195: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Cyclic Redundancy Check

The bitwise equivalents of And and Or are BitwiseAnd and BitwiseOr. For instance, the following code:

displays “29”. We can see that by performing the calculation manually:10001 Or0110011101

The third Bitwise operator REALbasic provides is BitwiseXor. Xor is short for “exclu-sive or”, and it has the following truth table:

a Xor b is the same thing as a Or b And Not (a And b).

Note that there is no BitwiseNot operator, but you can achieve the same effect by XOr-ing with all 1s (the easiest way to write a number consisting of 32 1s is to use hexadeci-mal).

Hexadecimal, Octal, and Binary Constants

When you write programs that manipulate binary information directly, you will usu-ally need to include binary values in your code1.

You can type binary values directly by preceding them with &b, like this:

But typing 32-bit values this way gets tricky and long-winded. Alternatively, you can group 3 bits at a time together, and get a base-8 (octal) number. So rather than the col-umns in the number being 1s, 10s, 100s (10x10), 1000s (10x10x10) and so on, the col-umns are 1s, 8s, 64s (8x8), 512s (8x8x8) and so on. You do this by preceding the value with &o, like this:

In an octal number, 9s and 8s would be meaningless.

You can also use a base 16 number (hexadecimal), grouping 4 digits at once, and using the letters A through F as the extra values after 9. Hexadecimal is the most compact,

MsgBox Str(BitwiseOr(17, 12))

XOR 0 1

0 0 1

1 1 0

1. Remember: if complexity or maintainability is important in your program, you should use a named constant defined in a module rather than typing a number directly into your code.

&b11101

&o35

195REALbasic Curriculum

Page 196: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Cyclic Redundancy Check

and it’s also convenient that there are two hexadecimal digits in a byte, and four in an integer. You write a hexadecimal number by preceding it with &h:

So the quickest way to write 32 binary 1s is:

&h1D

&hFFFF

196 REALbasic Curriculum

Page 197: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 23 RPN Calculator Example

Aim

We’ve done all the hard material in this course now; next, we look at some examples. We’re going to build a simple Reverse Polish Notation (RPN) calculator. If you’ve ever used a Hewlett-Packard scientific calculator, you’ve used RPN.

As well as being good practice, this project will get you to think about implementing and using a stack data structure. We also introduce the Model-View-Controller soft-ware design paradigm.

Model-View-Controller

Much of this course has been designed to get you over the gap between knowing what the individual objects and language features in REALbasic do, and how to put these together into sophisticated programs.

In this project, we will move on from the closer level we’ve looked at so far, to looking at one larger way of structuring an entire program: the Model-View-Controller para-digm (MVC).

Before we look at MVC in more detail, we should consider another theme that has arisen throughout this course: efficiency. MVC will be overkill for many programs.

197REALbasic Curriculum

Page 198: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

RPN Calculator Example

Remember what we’ve said: in many situations, you should be writing quick, simple, “bad” programs that just solve a problem quickly.

But if you are designing a more significant program, MVC is likely to be a useful way to structure it. If you are designing a program that is somewhere in between, you can also employ a kind of part-way MVC structure.

On to the details. MVC is a very generalized concept, applicable to almost any kind of program. It says that your program should be divided up into objects assuming three quite separate roles:

n Objects in the Model constitute the data your program is designed to manipulate. In a word processing program, this would be the text and its style, along with other formatting information that specifies the content of the document. In a computer game, this might be the “game world” location (in that world) and current actions of every “actor” in the game, the player’s score, and so on;

n A View is a class or collection of classes that present the model to the user on the screen; and

n A Controller is a class or collection of classes that can manipulate the Model.By separating these three roles, we gain the ability to vary any of them with minimal changes to the others. For example, assume we built a word processing program using MVC. Now assume we want to make the program into a multi-user program that lets two or more users work on the same document via the Internet. Almost the only change needed should be to write a new set of controller classes. The model and the view will be almost entirely unchanged.

One very important point: a single class can take on roles in two or even all three of the parts of the MVC paradigm. As we will see, Interfaces let us separate the roles within the one object. This will make splitting these roles into distinct objects later on fairly easy, should it become necessary.

The Stack Data Structure

A stack is a data structure with, at minimum, the following operations:

n Push, which takes a single argument;

n Pop, a function which returns a single result of the same type as the argument to Push; and

n Empty, a function which returns a Boolean.These operations on a stack work in a fashion equivalent to a stack of plates in a cafete-ria. Things come off the stack in the opposite order you put them on. In situations where you can’t control the stack from a programming language, or sometimes even then, you might want to have more operations on the stack. Some of the other com-mon operations you might have are:

198 REALbasic Curriculum

Page 199: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

RPN Calculator Example

n Drop, which removes the top item from the stack;

n Duplicate, which adds an extra copy of whatever’s on top of the stack to the top of the stack;

n Over, which pushes a copy of the next-to-the-top item onto the top of the stack;

n Swap, which switches the top and second from the top items on the stack;

n Size, which returns the count of items on the stack; and

n Clear, which empties the stack.

Reverse Polish Notation

We’ve seen before that any mathematical expression can be represented as a syntax tree. And we’ve seen how a recursive process (which uses a stack) helps us to traverse such a tree.

Put these two observations together, and you get Reverse Polish Notation (RPN). In RPN, operations are written after their operands, rather than between them. An oper-and is like the argument to a function: it is the information you need to carry out an operation. In the expression

+ is the operation, and 2 and 3 are the operands.

To interpret an RPN expression, just read it from left to right; numbers are pushed onto a stack, while operations pull their arguments from the stack and then push their results back onto it. Notice how simple this evaluation rule is, compared to the rules for normal arithmetic expressions. There are no precedence rules requiring you to jump back and forth in the expression to evaluate it, and no need for parentheses.

One quick note: we talk about the stack like the plates in the cafeteria: the first things pushed are on the bottom, the last on the top, for example. But the convention in the computer industry is to illustrate a stack on paper as a list, starting with the bottom of the stack at the top of the page. This is just something you have to get used to.

Some examples of expressions in regular and RPN notation:

Remember, in the expression 2+3*4, because of the conventions of arithmetic, we carry out the multiplication first, so the result is 14. Notice that the RPN version of

2 + 3

Regular Notation RPN

2+3 2 3 +

(2+3)*4 2 3 + 4 *

2+3*4 2 3 4 * +

199REALbasic Curriculum

Page 200: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

RPN Calculator Example

this expression has the * before the +, reflecting the order in which we carry out the calculations.

Let’s look at how we evaluate the last two expressions. First, 2 3 + 4 *:

Now, 2 3 4 * +:

The Project

Open the included SimpleRPNCalculator project. Run it, and try making some calcu-lations with it.

The Classes and Interfaces

The items in the program have been grouped roughly according to their role in the MVC paradigm.

The StackDisplay Class and the Stack Interface

Notice first that we only have one View class: the StackDisplay class. But this class sup-ports an interface, Stack, which forms part of the Model.

The Stack interface defines the kind of stack operations we have discussed

The StackEntry Interface

The other Model interface we have defined is StackEntry. This interface was created so we can treat the enter box as part of the stack. If the user has typed in a number but not pressed Enter, we nevertheless want to treat what is entered as the top item on the

Expression Evaluation Sequence

Stack

2 3 23

+ 5

4 54

* 20

Expression Evaluation Sequence

Stack

2 3 4 234

* 212

+ 14

200 REALbasic Curriculum

Page 201: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

RPN Calculator Example

stack. The methods in this interface let the stack check whether there is something in the entry box, and to enter it if there is something there. The stack can thereby take care of treating this other object as part of itself, so the other parts of the application don’t need to be concerned with it.

We use an interface for this so that the stack object doesn’t need to be hard-wired into a particular entry object. The stack doesn’t need to know anything about what the entry object is; just that it supports the operations in the StackEntry interface.

The StackOp-erationBut-ton Class

The StackOperationButton class is an abstract class, just adding support for the StackO-peration interface to the standard BevelButton (which we’re using like a standard but-ton; it just looks more like a calculator button than a regular button does).

The StackOp-eration Inter-face

The StackOperation Interface just defines an object that knows how to manipulate the stack. And that just means it can store a reference to a Stack object when asked to.

The NumEdit Class

We stole the NumEdit class from an earlier project. Code reuse!

The StackEn-tryBox class

This adds the StackOperation and the StackEntry interfaces to the NumEdit class. Notice how to declare multiple interfaces for a single class.

The CalcWindow

Object Event Handlers in a Window

In this project, we’ve done something we’ve not done much before: we’ve put substan-tial amounts of code in the event handlers for the objects in the window.

You should only do this with code that is specific to the operation of the window, or which you are absolutely certain won’t be needed outside the window.

In this project, we needed a whole variety of individual buttons, each with different behavior. We’ve put as much of that behavior as is reasonable in a shared class defini-tion, and the rest in the code for the event handlers for each button in the window.

Notice that each time we add code to the event handler of an object in a window, we are effectively creating a new, unnamed subclass of the object’s class.

The Open Event Handler in the CalcWindow

The Open Event Handler in the CalcWindow does something we’ve not done before: it uses the IsA operator, to specifically test the type of each object in the window.

You should be wary of any occasion in which you are tempted to use the IsA operator. You should always ask yourself if polymorphism could be made to do the job instead.

201REALbasic Curriculum

Page 202: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

RPN Calculator Example

In this case, in fact, it could; every object in the window could support the StackOper-ation interface, and objects which aren’t StackOperation objects in the current design could just have empty methods for the StackOperations.

But this would mean adding an extra interface to the StackDisplay class that didn’t belong there, and that would confuse the self-documentation of the design. It would also add complexity with little gain. The initialization code in the window keeps this stuff in one place, and is really pretty simple to understand and maintain. We did think about this design before accepting it, though.

By the way, this situation, in which you have some kind of collection, and you need to do something to a certain type of object within it, is a classic ‘no right answer’ situa-tion in object-oriented programming. Using IsA to find the objects you want is often (thought not always!) a good solution in this situation.

Further Exercises

This is a great project for extension:

n Add more buttons, for more scientific or business functions.

n Add keyboard shortcuts. Rather than requiring them to be set up in a centralized place, the keys in the window should be able to register their own keyboard shortcuts. This allows us to retain an important feature of the program right now: a new key can be added, without adding code anywhere but in the key itself. AsyncKeyDown (look it up in the documentation) is one way to intercept keystrokes. An interesting design question is how much of this feature you can put in the class definition. Another interesting issue is how to handle two or more buttons requesting the same keyboard shortcuts — there is no single, obvious way to resolve this.

n Add keyboard modifiers. I should be able to get Sin-1 by holding down the Shift key and clicking the Sin button. Again, I should be able to write the code specific to each ‘shifted’ operation in the buttons themselves.

n A good test of your understanding of the MVC paradigm would be to separate the stack from the display. This is to say that the stack should be a separate property of the window, separate from its display. There are many ways to handle the user interface and its display in this situation: the stack could just issue a Changed call to the display, and the display could then ask the stack for its content; or the stack could notify the display of every event that happens to it. An interesting option is to have the buttons notify the display when they have finished an operation, and to have the stack notify the display at that point (this would be the most efficient, but would be the hardest to write; our discussions of broad efficiency issues should tell you that “efficient code” is not needed here — but this would be an interesting coding exercise).

202 REALbasic Curriculum

Page 203: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 24 Programmable RPN Calculator

Aim

We make the calculator from the last lesson programmable with RBScript. This is an interesting exercise, since RBScript’s ability to communicate with other parts of the same program was initially fairly limited1.

About RBScript

RBScript is a class that can run REALbasic programs. These programs are loaded into an RBScript object as text, and are then compiled and run. This means you can make your program modifiable by the end user.

Note that what is available to RBScript is actually a large subset of the full REALbasic language. See the built-in Language Reference for details.

1. This lesson was written when RBScript was in its very first incarnation. RBScript is now very flexible and powerful and much easier to use in your projects. This lesson has been left as it was because it is a good project to illustrate several programming techniques. Also, most of the techniques used here are still useful, with suitable variations, when you’re using the latest version of RBScript. A version of the project that uses one of the new RBScript features is included as RBScript Calculator (Context).

203REALbasic Curriculum

Page 204: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Programmable RPN Calculator

At this point, you should read through the built-in Language Reference’s information about RBScript.

The Challenge

The challenge in using RBScript is that it only offers a very simple way of communi-cating with the rest of the program. The code that is running in an RBScript program has access to almost the full REALbasic programming language, but none of the built-in REALbasic objects. There are just two commands that an RBScript program can use to communicate with the rest of the program:

n The Input function, which takes a single string argument and calls the RBScript object’s Input event handler, which receives the same string as an argument. The event handler can return a string, which becomes the result of the function in RBScript.

n The Print command, which takes a single string argument and calls the RBScript object’s Print event handler, which receives the string as an argument.RBScript has no ability to call any part of the program it is running in, or indeed any other way to communicate with that program, other than through these two com-mands.

The challenge is that we want to provide the ability to “add RBScript code to a but-ton”, and to extend RBScript’s abilities so that it supports some suitable extra com-mands for communicating with the calculator’s stack. We will implement two functions (Pop and Size) and size methods (Clear, Drop, Dup, Over, Swap and Push).

At this point, you should stop and think about how you can let the end user write a script like this:

when RBScript doesn’t provide these stack commands.

Hint: You will need to add extra code to the RBScript that the user provides, contain-ing implementations of all of the stack commands. These commands will need to com-municate with the stack through the Print and Input commands.

The Project

n Open the project RBScriptCalculator.

What we will do is define a Protocol for the RBScript code to communicate with the rest of the program. A protocol is a set of rules by which everybody agrees to behave. In this case, we will define a set of messages that can be sent through the Input and Event commands in RBScript, and their associated events in the RBScript object, which will implement the stack manipulation commands we need. Then, we will add extra code

DupPush Pop * Pop

204 REALbasic Curriculum

Page 205: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Programmable RPN Calculator

to the RBScript provided by the user, which implements methods to handle the proto-col for each action. To the end user, it will appear as though these methods are built-in to RBScript.

1 Open the code editor for the StackScript class.

2 Examine the Input and Print event handlers. The protocol is very straightforward. For example, if we receive the string “Pop” from the RBScript, we pop the top value from the stack and return it.

The most complex command is Push, which needs to support receiving an argument from the RBScript. What we do is separate the value from the command with a space.

3 Now examine the code called from the constructor in this class.To simplify adding the extra methods to the RBScript, we build up a string through some auxiliary methods. We begin by noticing that there are just three types of func-tions or methods we need to add to the string we are storing in TheScriptHeader, which will be added to the user’s RBScript code:

n Methods with no arguments;

n Methods with one argument; and

n Functions with no argumentsWe notice that all of these do the same thing: they pass their name out through either the Input or Print commands; if there is an argument, that is passed through the same command, separated from the name with a space.

So we create three auxiliary methods to generate method or function declarations, given that method or function’s name, and we just call the appropriate auxiliary method for each method or function we need to add to TheScriptHeader. Notice that we have an AddFunction1 that we never use; it’s just there for completeness, in case we want to extend this project at some point.

Other than all this stuff, there are getter and setter methods for the script itself, a Set-Stack method (so this class can be a StackOperation) and that’s about it.

4 Look through the RBScriptButton and ButtonEditWindow, to see how that all works.

5 Run the project, Alt+click (Option-click on Macintosh) on one of the blank buttons, and add a script to it. For example:

DupPush Pop * Pop

205REALbasic Curriculum

Page 206: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Programmable RPN Calculator

Further Exercises

This is a great project for extension:

n There is no error handling, which makes it very easy to cause the program to generate an unhandled exception. Add enough error handling so there is no way for the user to cause an unhandled exception. You should probably ignore some errors, and display the most useful command you can in the case of others. Note that the RBScript object has a property to tell you which line it is executing. It would be nice to tell the user which line in his RBScript caused an error.

n Add extra commands for the users to call. Commands to read and write data from files would be useful; and

n A more ambitious exercise would be to have the calculator save the scripts in its buttons when it quits, and reload them when it is launched. The PreferencesFolder function is very useful for this…

206 REALbasic Curriculum

Page 207: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 25 Graphics I

Aim

We are working up toward some fun stuff with sprites. Consistent with the develop-ment techniques we’ve discussed, we are going to start with one small part and test it. This part is a picture that can point in different directions.

This is also a great example of why you should have paid more attention during trigo-nometry classes in school…

We’re going to make a class hierarchy for generating and displaying a graphic that can point in different directions. Because of what we’re going to use it for later, we want to be able to pass it x- and y-coordinates, relative to the center of the object, and have it point toward those coordinates.

This will involve some trigonometry. But don’t be scared; we’ll explain the trigonome-try we use as we go.

Prereading

You should read about the Canvas and Graphics objects in the User’s Guide before you continue.

The Project1 Open the included project, DrawChevron, run it and see what it does.

207REALbasic Curriculum

Page 208: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Graphics I

2 Examine the code underlying the DirectedChevron class, starting from the top of the class hierarchy:

n DirectedPicture is an abstract class for reuse;

n BufferedPicture is a somewhat abstract class that provides a framework for a basic way of approaching this problem: rather than generating an image pointing precisely at the intended point, we have a number (often 8 or 16, identified by the property NumPics) of pre-generated images, and we display the one that points closest to the coordinates we’re interested in.

n DirectedChevron gives us some actual images for BufferedPicture to display.

Pixels

A picture on a computer screen must ultimately be reduced to a grid of colored squares. Each square is called a pixel (short for picture element).

Coordinates

Traditionally, a location in a 2-dimensional picture on a computer is measured from the top, left corner of the picture. A point is described with two numbers, representing the distance across and down of the point. These distances are usually referred to as the x and the y coordinates, respectively. As a shorthand, we will sometimes write the location of a point as (x, y). So the very top, left point would be (0, 0) and a point 100 units across and 50 units down would be written (100, 50)

The Trigonometry

Trigonometry means “the study of triangles.” Trigonometric functions relate the angles of a right-angled triangle to the lengths of the sides.

One thing you need to know about all of these functions in REALbasic: angles are measured in radians, for various mathematical reasons we need not worry about now. There are 2 * Pi radians in a complete circle. This just means that where you might be tempted to use “360” (because you are thinking in degrees), you write “2 * Pi”; and where you are tempted to use “180”, you write “Pi”. (You’ll also want to define a suit-able Pi constant, as we have in this project).

DirectedChevron.GenerateFrame

The role of DirectedChevron is to supply enough pictures to make up a quarter revolu-tion. The superclass will then flip these around to create enough pictures to make up a full revolution. We will place the points of the chevron around a circle that just fits inside ThePicture.

We begin by calculating the radius of this circle. This is half the width of ThePicture:

208 REALbasic Curriculum

Page 209: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Graphics I

Figure 62. The Chevron within ThePicture.

Next, we calculate how many radians around we are to rotate each image, compared to the last:

Figure 63. AngleInc radians further around for each image.

Next, we calculate where around the circle each point will lie. Each point will be repre-sented by its x (horizontal) and y (vertical) distance from the top, left corner of TheP-icture.

The front of the chevron is at AngleInc radians around from 12 O’Clock. We need a way to convert an angle into its x- and y-components.

AngleInc = 2*Pi*(n-1)/NumPics //How far around we are to rotate

AngleInc Radians around the circle

209REALbasic Curriculum

Page 210: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Graphics I

REAL, basic Trigonometry

Now we need to work out where the three tips of the chevron will be. For this, we need to be able to convert an angle and a distance into x and y coordinates.

Assume for the moment that the center of our chevron is at (0, 0). We want a point rotated p radians, and r pixels away from (0, 0). This lets us draw a triangle:

Figure 64. The task is to find a and b in this triangle.

Our starting point is the bottom point of the triangle, and the point we want to find is the right-hand point of the triangle. We can draw this point because going r pixels at an angle of p radians from the vertical is the same as going up b pixels, then right a pix-els. Notice that going straight up and then going straight to the right means those two moves are at right angles. Two trigonometry functions, Sin and Cos let us find a and b:

n The Sin of p tells us what a/r is. Since we know what r is, and we know what p is, it follows that a is r * Sin(p).

n Similarly, the Cos of p is b/r, so b is r * Cos(p).In general, these functions can be used in any triangle with a right angle in one corner. The side opposite the right angle is called the hypotenuse. The Sin of one of the angles that isn’t the right angle is the ratio of the side opposite that angle to the hypotenuse; the Cos of the angle is the ratio of the adjacent side to the hypotenuse. There is also a Tan function, which is the ratio of the opposite side to the adjacent side.

210 REALbasic Curriculum

Page 211: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Graphics I

You can remember this with the acronym SOHCAHTOA (Sin: Opposite/Hypote-nuse; Cos: Adjacent/Hypotenuse; Tan: Opposite/Adjacent).

Now, we want to center this not at (0, 0), but in the middle of the picture, at (r, r). So we add r to every x and y value. We also define a constant SideAngle, which is how far around from the top of the chevron to its opposite side that we place the rear points of the chevron. That gives us the following code to draw the chevron:

Sub GenerateFrame(n As Integer, g As Graphics)//Generates a chevron pointed at the nth point out of UBoundPics + 1 total

//Pre: Picture width and height are identical//0<=n<=UBoundPics//UBoundPics >= 6, UBoundPics is even//Post: p contains the chevron

Dim r As IntegerDim AngleInc As DoubleDim Points(8) As IntegerConst PI=3.14159265358979323846264338327950Const SideAngle = 0.8 //Proportion of half a revolution around for back of chevron

r = ThePicture.width/2AngleInc = 2*Pi*(n-1)/NumPics //How far around we are to rotate

//Point of chevronPoints(1) = r + r * sin(AngleInc)Points(2) = r + r * cos(AngleInc)

//Right sidePoints(3) = r + r * sin(Pi*SideAngle + AngleInc)Points(4) = r + r * cos(Pi*SideAngle + AngleInc)

//CenterPoints(5) = rPoints(6) = r

//Left sidePoints(7) = r + r * Sin(Pi*(-SideAngle) + AngleInc)Points(8) = r + r * Cos(Pi*(-SideAngle) + AngleInc)

//Draw itg.ForeColor = DarkBevelColorg.ClearRect 0, 0 ,g.Width,g.Widthg.FillPolygon(Points)

211REALbasic Curriculum

Page 212: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Graphics I

As usual, you should look up any of the REALbasic commands you are not familiar with. Briefly, though, FillPolygon takes an array of integers, treats each pair of numbers as a point, and draws a polygon (straight-sided figure) between those points, and filled with whatever the current ForeColor is.

Which Image Points Here?

The other method for which we need some trigonometry is the one that works out which image to draw to make the image point at a particular location.

What we need for this is the inverse of the Tan function mentioned earlier: this time, we have the location, and we want to work out the angle. The part of the location divided by the x part of the coordinate is just the Tan of the angle, as we mentioned above.

There is an Atan function that calculates the angle from the ratio, but in fact, REAL-basic has an easier function for us to use: Atan2 takes an x and a y value, and returns the angle from (0, 0) to that point. So we just need to subtract r from everything, to move it back to (0, 0), and ask for Atan2. Then we just round to the nearest angle our images point at (remember how we did AngleInc = 2*Pi*(n-1)/NumPics) in Gener-ateFrame? We just need to work out how many of those are in our angle). This gives us this method:

You should look through the project now, run and trace it, and tinker with it until you can see how it works.

Further Exercises

There are many possible ways to extend this project, and you should try to come up with your own ideas. Some specific ideas might be:

n Make the classic “pair of eyes watching the cursor” application, with circles for pupils. Bonus points for extending the application so it follows the pointer inside either of the eyes properly (meaning that if the pointer goes inside one of the eyes, the pupil will be centered under the pointer);

n Draw a more complex shape (say, a tank or robot), rather than the chevron; or

Sub FaceToward(X As Integer, Y As Integer)Dim NextPic As Integer

Const PI=3.14159265358979323846264338327950

NextPic = ((Round(atan2(X, Y)*NumPics/(2*Pi)+ NumPics) mod NumPics)) + 1If NextPic <> CurrentPic Then

CurrentPic = NextPicThePicture.DrawPicture ThePics(CurrentPic), 0, 0

End If

212 REALbasic Curriculum

Page 213: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Graphics I

n Create a class that can start from two bitmap images (one pointing straight up; one pointing at 45°), and will then generate the full 8 images by rotating each of the two original images through three right angles.

213REALbasic Curriculum

Page 214: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Graphics I

214 REALbasic Curriculum

Page 215: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 26 Communications

Aim

We develop a very simple yet useful application to demonstrate the use of TCP ports. The application sends a text message to another computer running the same applica-tion.

TCP/IP

Just as we have looked at protocols in other situations, there are different protocols for computers to talk to each other over a network. The protocol we will be using is TCP/IP.

This is the main protocol for the Internet. As with the calculator, the underlying implementation of the protocol hides complexities from the software that makes use of it.

To send information to a computer via the Internet1, you need to know two things:

n The IP Address of the computer on which the program is running; and

n The Port Number on which the program you are trying to communicate with is listening.

1. Using the most commonly-used protocol for internet communication, TCP (Transmis-sion Control Protocol).

215REALbasic Curriculum

Page 216: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Communications

You’ve seen IP Addresses before. They consist of four numbers between 0 and 255 with periods in between (like this: 210.18.155.12). It contains all the information needed to locate a computer on the Internet.

A port number is an integer between 0 and 655351. This is a bit like a box number at an address; it is because connections to a computer use different port numbers that you can have multiple programs running on the same computer communicating with various Internet servers, all at the same time. Every packet of information that is sent between two computers contains a specification for the port number on which it will be received.

How do the two programs that are communicating with each other know which ports to use in the first place? There are three ways:

n There are certain accepted standards that are usually used for certain services. Web servers, for example, usually use port 80. So when you type www.realbasic.com into your web browser, it translates www.realbasic.com into an IP address2, then sends a Hypertext Transport Protocol message to port 80 at that address.

n When a program receives a connection with another machine, it will often ask its operating system for a random unused port number, and ask the program at the other end to respond to that port number.

n Internet addresses (technically called Universal Resource Locators, or URLs) can specify the port number after the DNS name or IP address of the server (separated from that address with a colon). It would be possible for REAL Software to run a second web server program on the same computer used for the default server, and to link to it from the default port 80 server by using an address; something like this: http://www.realsoftware.com:8080.The information sent through the Internet is broken up into short packets and might arrive from the Internet out of order or needing retransmission due to an error, but this all happens at a lower layer than TCP provides3. The TCP service guarantees that the message will arrive intact and the parts of it will arrive in order. However, the

1. Or it might be 65537. After several hours of searching on the internet, the writer could not find out for sure.2. Using another standard service on a standard port number called the Domain Name Ser-vice. You may have had to enter DNS server address, which specifies which computer can provide this translation for you, into your computer when you were setting up your internet connection.3. An Internet communication service is built up in layers; the TCP layer which provides reliable delivery of packets in order does this using a lower layer called UDP (Universal Dat-agram Protocol) that provides neither of these guarantees. This is important because for some purposes, speed is more important than correctness (transmitting audio or video, or playing a real-time game, for example), so some programs will need to use UDP, which is much faster.

216 REALbasic Curriculum

Page 217: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Communications

information won’t necessarily all arrive at the same time. We need to keep this in mind whenever we write networked software.

With this in mind, let’s look at the project we are going to create: it sends a text mes-sage to the same program running on another computer. This is actually quite a useful program!

The Project1 Stop and think for a bit about what a suitable protocol1 for this task might

look like. The only real issue to cover is how the receiving program can know that the entire message has been received.

2 Examine the code in the included project, MessageSender.You should read the built-in language reference about the TCPSocket object. Note all we need to do: we create a receiving socket and tell it to Listen. And if we want to send a message, we ask the sending socket to send.

3 Examine a little the enclosed copy of RFC 821, describing one of the most important Internet protocols: SMTP. It’s called a Request for Comment because that’s how these standards start: someone puts out an idea and asks people to comment on it; it’s put out by the Internet Engi-neering Taskforce (IETF), who define most of the standards (mostly protocols) by which the Internet functions.It is very important that the protocols for sending and receiving email and web pages, and most of the types of information going over the Internet, are available for anyone to understand and implement. The IETF makes all of the RFCs defining how these standard services work available for free. If you want to write a web server, a web browser, an email server, or a program that works with any of the other Internet stan-dards, you are free to.

4 Examine the Port section of the built-in Language Reference.

5 Focus on the numerous possible errors that can occur when two separate computers are communicating via a network. We haven’t tried to handle errors such as these to keep the example simple.Most of the work in implementing programs that communicate via the Internet is often in handling all of these errors.

1. To make sure that all this talk of protocols is clear on one point: it is usual to build proto-cols on top of other protocols. A lower level in the internet communications protocols just gets packets where they need to go. Another protocol sits ‘on top’ of this to correct transmis-sion errors from the lower level, and to assemble larger messages out of the packets from the lower level, by putting them together in order (this gives us TCP). We will use that level to implement a higher-level protocol of our own invention to send messages.

217REALbasic Curriculum

Page 218: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Communications

Further Exercises

The project can be extended in a variety of ways:

n Handle sending styled text (set the EditField’s Styled property to True, and send both the text and the TextStyleData property);

n Allow for dragging and dropping things (files, clippings) onto the window and then off from the window in the other computer.Any such extensions of the project will, of course, require you to extend the protocol.

218 REALbasic Curriculum

Page 219: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

LESSON 27 Simulation and Animation

Aim

We’re now going to do a reasonably significant exercise in simulation and animation. We’ll produce a SpriteSurface with a collection of the chevrons from our earlier lesson, and we’ll have them chase the mouse pointer. Then we’ll see a little of the advantages of object orientation when we see how easy it is to animate the sprites.

Note that once again there is a little trigonometry involved in this project.

Prereading

You should read about the SpriteSurface and the Sprite classes before continuing.

A Physics Simulation

It is common in a game to design a physics simulation. These will usually be less than completely realistic, but will somewhat resemble how objects behave in the real world.

In this case, we are going to have a group of objects with the same behavior. In particu-lar, these objects will all have:

n Momentum, meaning they have a direction and speed with which they are moving, and it will require the application of a force to change that direction and speed; and

n Thrust, which is a force directed in the direction they are facing.

219REALbasic Curriculum

Page 220: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Simulation and Animation

The combination of these produces objects that behave like they are driven by rockets but are sliding about on ice. Another way to say this is that we are simulating a friction-free, zero-gravity situation.

We will have the objects always face toward, and thus thrust toward, the mouse pointer. And we will display a group of these objects, starting from somewhat random locations.

Can you imagine what this is going to look like?

The Math

We need to track the locations and the momentum of the objects, and to apply the thrust to them.

Most of the math involved in doing this makes use of vectors. A vector is, roughly speaking, an arrow: it is a direction and a distance1, or (equivalently) an x and y dis-tance.

We will implement this as an object with multiple get and set operations: you can get either the x and y distances, or the direction and magnitude. For this program, we will only provide set operations for x and y.

We also provide three other operations on vectors (we’ll see how these are useful as we explore the project):

MultiplyBy We provide an operation to multiply a vector by a Double. This multiplies the magni-tude by the Double. Note that since we happen to be storing the vector as an x and y quantity, we have to scale both of them, using trigonometry very similar to the calcula-tions we used in our Graphics I lesson.

Normalized This function returns a new vector with the same direction as the vector it is applied to, but with a Magnitude of 1.

Add and Operator_Add

To understand adding two vectors together, imagine them as arrows, and put the sec-ond arrow at the end of the first2:

1. It is customary to say “magnitude” rather than “distance” because a vector can represent not just direction and distance but other things that have direction and “amount” — say, direction and amount of thrust.2. The Operator_Add function lets us define our own + operator for this class. In other words, it lets us find out the sum of two vectors v1 and v2 by writing v1 + v2. Note that we don’t actually wind up using this in any of the projects.

220 REALbasic Curriculum

Page 221: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Simulation and Animation

Figure 65. c = a + b.

To compute the sum of two vectors, we can just add the horizontal components of the two vectors to get the horizontal component of the result, and the vertical compo-nents of the vectors to get the vertical component of the result:

Figure 66. To sum vectors, sum the horizontal and vertical components separately.

The First Project1 Open the first included project, SpriteFlock.

2 Examine the code in the Vector class; make sure you can see how it implements the operations described above.Notice that most of the operations change the content of the vector itself, but that Add is a function that returns a new vector.

3 Examine the code in the MomentumSprite class.This uses simple animation principles, moving the sprite according to its current speed between frames. We don’t try to fix the speed, so the speed of the sprites will vary depending on how fast the computer is that the program is running on.Notice that although MomentumSprite is a sprite, and therefore it has X and Y integer properties, we need to keep the coordinates of the sprite as Doubles, to avoid rounding errors (which would cause the sprite to “jump” at low speeds, for example). We per-form all our calculations about location using the doubles, then round that to the nearest integer for the actual X and Y properties for each frame.

221REALbasic Curriculum

Page 222: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Simulation and Animation

This also means that we create a MoveTo operation, so when we move the sprite some-where, we remember to set both the X and Y and the ExactX and ExactY to the new location. This is a great example of why directly setting properties is less flexible than using get and set methods.

Next, notice that the momentum of the sprite is kept as a vector, and that we have an Apply operation, to add acceleration to the current momentum. Each frame, we will work out the direction to the mouse pointer, and apply a vector in that direction to the vector representing the momentum.

The final method is Increment, which works out the new location of the sprite. Once again, we are effectively adding two vectors (the current location is just like a vector). We don’t use a vector for this because we need the separate X and Y components at this point.

So the location is a vector, the speed is a vector and the acceleration is a vector. We add the acceleration to the speed, and the speed to the location1.

4 Take a quick whip through the rest of the program.

More Comments

n We’ve separated the two important constants (the number of sprites, and the amount of their thrust) into constants so we can easily change their values or convert them to global variables. It is almost always sloppy coding to put a constant right in the code. This doesn’t mean it isn’t sometimes OK, but it means you should always think about it before putting a constant value (number or string) into your code. An example of a value that was OK to put in amongst the code was PI — it is very unlikely to change…;

n A quirk of the order of calling events on objects in the window meant we couldn’t just initialize everything in the window’s Open event: at this point, the window isn’t maximized, so we don’t know where to put the sprites. There are many ways to handle this — we’ve used a simple but practical method of kicking everything off one second after the application is started, from a timer. Hence InitSpriteSurface; and

n Note that we’ve somewhat separated out the display of the sprite from its simulation (we didn’t aggressively separate them as we’ve talked about before, because we wanted to keep the code simpler). This will be important in the next project, where we see how easy it is to animate the sprites as a result.

5 Run the project. Pretty!Stop and consider how this simulation could be easily adapted to do a whole range of interesting things: a solar system simulator, for example.

1. If you know some basic calculus, these are the position, the first derivative of the position (the speed), and the second derivative of the position (the acceleration).

222 REALbasic Curriculum

Page 223: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Simulation and Animation

Note how the sprites start out quite close together, but that over time, they get further and further apart.

AnimatedSpriteFlock1 Open the project AnimatedSpriteFlock. Run it.

Note the difference: the sprites are animated (they change color).We do this by creating a class that can replace the graphics source in the previous code. This new class (AnimatedPicture) contains one or more DirectedPicture objects. Based on the amount of time that has passed, it will pass requests for pictures in a cycle to each of its contained objects. Thus, this container class provides simple time-based cycling of pictures.

2 Examine the code that does this. Note how simple it is!Apart from some code to initialize this class, and an extra constructor and a method in the DirectedChevron class (so we could get the color from one instance to set the color of its opposite), the changes to add this new capability were very straightforward.Can you see why a good object-oriented design made this so? The answer involves polymorphism and a simplified model-view-controller paradigm. Can you see how this is a kind of simplified MVC design?

Fixing the Speed

Note that while the animation cycles based on time, the speed at which the simulation runs is dependent on the number of sprites and the speed of the computer (this deter-mines the framerate of the SpriteSurface).

There are a few ways to fix this: either explicitly set the framerate of the SpriteSurface; separate the model out entirely and update it based on a timer; or have the model keep track of the time between frames, and run the necessary number of simulation steps for the amount of time that has elapsed. Think about the advantages and disadvan-tages of each of these.

Further Exercises

This project can be extended in a great many ways. Some starting ideas:

n Bring in some more physics (you might do some searching on the Internet or in a high school physics text on the details). Reasonably easy is adding friction. Harder is having the sprites bounce off each other (easiest: assume each is actually a circle). This is a good point to think about realistic physics, versus having something that looks reasonable.

n Make a solar system simulator. Either one based on the real solar system, or have a central sun, to which all objects are attracted, and place a bunch of objects with

223REALbasic Curriculum

Page 224: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Simulation and Animation

random masses, positions and velocities, and see which ones fall into the sun, fly off into space, or enter a stable orbit. It’s fairly simple doing just the sun as a source of gravity; it’s interesting to do a project where each of the objects has gravity. Calculating that properly involves a number of operations proportional to N2 for N objects, so it won’t take many objects to start really slowing such a simulation down.

n Make a game or toy, such as an ice-skater simulation.You will have to research some of the other abilities of the SpriteSurface, such as colli-sion detection or keyboard scanning, but research is a good thing…

224 REALbasic Curriculum

Page 225: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

APPENDIX A REALbasic Coding Standard

Introduction

This document presents a coding standard for REALbasic.

The purpose of this coding standard is to assist REALbasic developers to:

n Write correct code;

n Write easily maintained code; and

n Understand REALbasic code.

General

Anything that is not obvious should be explained in a comment, at the point where it occurs.

Comment should be preceded by the double-slash // comment delimiter. The single quote character should not be used for general commenting; its use should be reserved only for commenting out code, because REALbasic provides a command to insert and remove the single quote before a block of commands, and doing this will leave // com-ments untouched.

225REALbasic Curriculum

Page 226: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

The purpose of a method should be explained at the top of the method, immediately below the pre- and post-conditions, if those do not provide sufficient documentation (see the example below).

Pre- and Post-conditions

Any method whose purpose and correctness is not very obvious should begin with comments explaining what the program assumes (the Preconditions) and what the method will change in the program’s state (the Postcondition). If possible, these condi-tions should be described in a way that could be checked by code.

In more detail:

Precondition The preconditions for a method are aspects of the program’s state that are assumed to be true before the method is run. Except for debugging purposes, the method does not check that the conditions are true, and the method will either fail or work incorrectly if these conditions are not true.

An example:

Postcondition The postconditions for a method are the aspects of the program state that are changed by the method. Examples are the value returned by a function and changes to data structures, user interface display, or communications (via a network, perhaps).

An example of a full pre- and post-condition (here, w is the argument to the method):

Loop invariants

Many program errors are due to mistakes in writing loops correctly.

It helps to avoid these errors if we think of a loop as a repeated change in state. Each time through the loop, something is true, it possibly becomes untrue within the loop, then it is made true again by the end of the loop. You should state the loop invariant above the loop, if appropriate, prove that it has been made true at that point, then prove through each possible execution path within the loop, that the invariant is kept true.

//Pre: Count and Word arrays have same number of elements

//Pre: Count and Word arrays have same number of elements //Post: if w is in Word array, the value of Count at the same index is //incremented// otherwise, w is appended to Word array, and 1 is appended//to Count array//ie we are maintaining a count of the words submitted to this method, //in the two arrays

226 REALbasic Curriculum

Page 227: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

There may be several loop invariants. If this is the case, you should label each loop invariant with a name, and refer to these names when you prove them correct.

An example:

Sub CountWords()//Pre: None//Post: Word array contains all of the words in Source;//Count array contains corresponding count of those words in Source

Dim InWord As BooleanDim counter, WordStart As Integer

if Len(Source.text)>0 then //If source is not emptyInWord = IsWordCharacter (1)//Inword invariant (below)If InWord then//Wordstart invariant (below)

WordStart = 1end if

for counter = 1 to Len (Source.text)//Invariants:// Inword: InWord is true if the counter character of Source.text was

IsWordCharacter//WordStart: WordStart is the last counter character such that the

character before it was not IsWordCharacter

if InWord thenif not IsWordCharacter (counter) then

AddWord (Mid (Source.text, WordStart, counter-WordStart))InWord = false //InWord invariant

end if//WordStart invariant: InWord implies we don't need to change

WordStart

else //not InWordIf IsWordCharacter (counter) then

InWord = true //InWord invariantWordStart = counter //Wordstart invariant

end ifend if

nextend if

227REALbasic Curriculum

Page 228: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

228 REALbasic Curriculum

Page 229: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

APPENDIX B Model-View-Controller Software Design

Introduction There is a well-established way to design a program called the Model-View-Controller Paradigm. You should use this paradigm in any complex program design involving a user interface.

Note that this paradigm is a very broad and high-level guideline. You will need to apply other design techniques to fully flesh-out your designs.

Programs have (up to) three parts

The Model-View-Controller Paradigm (which we will henceforth call MVC) considers programs to have up to 3 parts:

n The Model, which is the underlying data or system the program is designed to manipulate. In a word processing program, for example, the model provides a representation of the text and formatting of the document; in a strategy game, the model represents what all the units, terrain and other factors in the game are up to; in a RPN1 calculator, the model would be a stack of numbers.

n The View, which is the presentation of information to the user. In REALbasic programs, this will be a graphical user interface. Note that some programs may not

1. RPN stands for Reverse Polish Notation. It will be useful to look this up on Wikipedia or something similar, if you are not familiar with this way of representing calculations.

229REALbasic Curriculum

Page 230: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

have a view (a web or file server program might not have a direct user interface, for example).

n The Controller, which is the means by which the program is controlled. In REALbasic, this will mostly be graphical user interface controls. Potentially, though, the control for a program could come from a wide range of sources: files, other programs on the same computer or a network, for example.

The advantages of MVC

MVC is a tried and tested high-level structure for any application with a Graphical User Interface. It was originally developed in IBM’s Smalltalk, which was both one of the earliest and most influential object-oriented programming languages, and also one of the earliest examples of a graphical user interface. It has proven its value over more than 30 years since that time.

You can see MVC as a modern, GUI version of the older view that a program consists of input, processing and output. By cleanly separating these features within your pro-grams, you gain the same advantages we have seen elsewhere: you can develop and debug each in separation, and you can change any of the three with minimal or no changes to the others.

As an example, consider a complex video game. If you employ MVC in developing the application, you will be able to:

n Easily add new control schemes, such as game controllers;

n Add more complex enemy programming without worrying about whether it will display correctly; and

n Improve the graphics or sound for the game without concern for the mechanics of play.

Implementation by Class and Interface

In more practical terms, the classes and interfaces in your application should generally fit cleanly into one of the three parts of the application, and should have simple com-munication between them.

Note that a particular class will often fulfill roles in two or even three of the major parts of the application. This is fine, as long as the various roles are separated into dif-ferent interfaces or the class definition itself, and as long as the other classes that com-municate with the class in question do so via the relevant interface.

The point is not that the roles must be separated, but that they can easily be separated. If a single class, say a PlayerShip takes care of reading the keyboard, interacting with the model to determine what is going on in the game world, and displays itself on the screen, that is fine: if it has at least three different types that it works through to do

230 REALbasic Curriculum

Page 231: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

this. Its class might be a Sprite, so it can draw itself in the game, but as far as the game model goes, it is a PlayerControlledActor, and as far as the controls go, it is a Keyboard-ControlledObject. Then, if need be, we can separate those roles into separate classes at any point. Perhaps the single ship will later become a cluster of separate ships. We can define a new class to manage a group of sprites, but if the new class is still a PlayerCon-trolledActor and a KeyboardControlledObject, with a clearly defined, simple interface to each, then we should have little problem making this major change.

One somewhat bizarre possibility deserves mentioning: in a complex application, you might wish to go to the extent of having a single class with multiple roles treat itself as if it was three separate objects. The PlayerShip in the example above might have proper-ties for Controller and Actor, each of which refers to itself. This will add a small amount of overhead in developing the class (it might have to say If Controller.Fire, rather than calling its own Fire function directly), but it would let the class be later separated into multiple classes more easily.

Whether to go to that extent depends on the likelihood of wanting to separate the class’s roles into separate classes later. It is not recommended that you should always code in this way by any means.

A detailed example: A Reverse Polish Notation Calculator

The REALbasic Curriculum Project provides an excellent example of an MVC appli-cation in the Simple RPN Calculator project.

Notice that the various classes and interfaces in the project have been separated into folders to clearly illustrate the MVC separation within the application.

In particular, notice how the StackDisplay class IsA ListBox, but that its role as the stack that the buttons and the EditField manipulate is via its Stack interface.

Notice also that the EditField is also given a role in the model via the StackEntry inter-face. We don’t want to have to press Enter after typing in a number and before per-forming an operation, so this interface lets the stack object proper provide the StackEntry object with an opportunity to add its contents to the stack before a Pop operation.

Finally, notice that both the EditField and the buttons support the StackOperation interface, so that the stack on which they operate can be set in a single operation.

In summary, the various classes/interfaces, and their role in the MVC structure of the program are:

231REALbasic Curriculum

Page 232: s3.amazonaws.com · REALbasic Curriculum 1 REALbasic Curriculum Project Contents REALbasic Teaching Curriculum Overview 11 Lesson 1: Introducing REALbasic

Model Classes or Interfaces

n The Stack interface is simply an object with the simple stack operations such as Push and Pop; and

n The StackEntry interface isn’t an intrinsic feature of an EditField, but rather allows the stack to correctly calculate its size (since the entry is part of the stack as soon as it contains a number), so we separate it into an interface here.

View Classes or Interfaces

n The StackDisplay class IsA ListBox. Note that we don’t explicitly separate its operations from those of the stack, since the operations in this case are the same: all changes to the abstract stack are reflected directly by equivalent changes to the display. In a more complex application, this will usually not be the case.

Controller Classes or Interfaces

n The StackOperation interface lets us initialize all objects that will be working on the stack in the same operation;

n The StackOperationButton adds the StackOperation interface to the BevelButton;

n The NumEdit class is the standard numeric entry box we developed in an earlier project; and

n The StackEntryBox class adds the StackEntry and StackOperation interfaces to NumEdit.

Final Notes

It was not deemed necessary in such a simple application to fully separate the model from the view. From the outside, they are separated, but there is no explicit calling between the model and the view, since the operations on each are identical. You may find it useful to consider what would be involved in separating these roles. Perhaps make the stack a separate object from the ListBox that displays its content.

232 REALbasic Curriculum