Preface 1 COMP 14 Prasun Dewan1 Preface Why another Programming Book? Early Introduction to (Implementation of) Objects Instructors of introductory programming are faced today with two main choices: use an interpretive functional language such as Scheme or ML; or use a compiled object-based programming language such as C++ or Java. The second choice is the more popular one because it teaches the powerful concepts of object-based programming in the context of a practical language. On the other hand, though decreasing in popularity, the first choice continues to be a valid alternative because it allows students to write functions, and hence focus on programming logic, from day one. Once they have written a function, they can see what it does by simply calling it interactively – the interpreter performs the messy tasks of mapping user-input to function calls and displaying return values of these calls, freeing them from learning about I/O altogether. An analogous facility is not automatically provided for compiled object-based programming languages; thus students must be introduced to static main methods (or Applet init methods), input/output, and a host of other details before they can define and interact with objects. Worse, many of these details cannot be fully explained early in the course, and are often presented as parts of magic cookbook recipes, encouraging them to become hackers rather than computer scientists with a deep understanding of the programs they write. What is required to offer the best of both words is a tool that provides an intuitive, graphical user-interface for interactively instantiating classes and invoking methods. As part of work in user-interfaces, my research group developed such a tool, called ObjectEditor, for Java. The main contribution of this book is an early introduction to object-based programming based on ObjectEditor. ObjectEditor serves as training wheels that are later removed when students are taught to create their own user-interface classes that compose with computation classes they have written earlier. As a result, students learn to keep computation and user-interface code in different classes, thereby learning an important example of the principle of addressing independent concerns in separate classes. Some other textbooks also claim an early introduction to object-based programming; such an introduction essentially tells them how to invoke the println() method on the predefined object, System.out. How to implement an object is covered much later, typically around chapter nine. In this book, students start implementing their own objects from the chapter two, which is, in fact, the first chapter on programming, following the chapter that introduces them to the organization of a computer. Programming Fundamentals rather than Java Reference This book is different from current textbooks in several other ways. A major problem with them is that they are difficult to follow in a course, mainly because they tend to be references to Java rather than an introduction to concepts in object-based programming. Derived from the class notes I distribute to students, this book is essentially a transcript of what I actually say in class. Thus, the emphasis is not on providing a formal reference for the most useful features of the Java language and libraries. Instead, it is on selecting the most fundamental of these that can actually be taught in a single course, and presenting them informally in a conversational style with the transitions needed to smoothly move to 1 Copyright Prasun Dewan, 2000. Preface 2 between different topics. 2 To become a productive Java programmer, additional reference material on Java such as Java from the Source and Java in a Nutshell should be used – this book is not intended to compete with these excellent references. Real-World Analogies to Explain Concepts in-depth Object-based programming is complex. Thus, the idea that it can be really taught to beginning programmers seems fundamentally flawed – another argument used by those who prefer to instead teach functional programming. On the other hand, computer objects are modeled after familiar physical objects, and thus should not be difficult to understand. This book takes the analogy between the computer and physical world further than others have to explain many important subtleties of object-based programming. For example, assigning to a variable an instance of a subtype of its declared type is compared to getting a free upgrade at a car rental, thereby allowing students to fully understand the complex type checking rules of object-based programming languages. An analogy is also made between the theater and computer world, allowing students to intuitively understand the major software and hardware components that make a program work. These analogies allow object-oriented concepts to be covered in far more depth than other textbooks. Principles, Techniques and Small-but Complete Examples In addition to explaining how programming constructs work, the book also motivates them using realistic examples, identify principles regarding how the constructs should (and more important, should not) be used, and explain techniques for solving a general class of problems. Ideally, each example should be small enough to fit on one slide so that it can be easily understood in class. This poses a difficult problem for constructs of object-based programming, because their usefulness tends to be exhibited in complex programs. ObjectEditor, together with a careful use of inheritance, is used to address these conflicting goals. ObjectEditor is used to keep programs free of user-interface details, and inheritance to incrementally extend the examples. As a result, the examples are compact and yet exhibit the problems of real-life applications. The examples cover a wide range of applications, including calculators, spreadsheets, scanning, databases, and graphics/ animation. They are chosen to create a flow in which each new concept naturally follows the previous one. Often multiple ways of solving a problem are given, so that students can learn about and compare different techniques for solving the problem. For instance, students learn that creating instance variables for the dependent items of a spreadsheet make the program time efficient but space inefficient. When there is clearly a best way to solve a problem; it is presented as a principle. The principles identified cover a wide range from the usual syntactic ones such as how to name identifiers to semantic ones, which are typically not presented in other textbooks, such as the separation of concerns principle mentioned above. Interfaces, MVC, and Beans The book discusses in-depth three important software-engineering concepts that are either not covered or receive lip service in other textbooks. It introduces interfaces in-depth, explains the Smalltalk Model View Controller design pattern, and requires, and in fact, enforces through ObjectEditor, students to create objects as beans. One can argue that these concepts are too advanced for an introductory programming course. The reason they have been included is that it is important and, in fact, possible to teach them in such a course, especially one based on a Java toolkit. That these concepts are important is easy to argue. Interfaces are an important tool to do top-down programming, and allow the substitution of one implementation for another. The model view controller pattern prevents the implementation of graphical user-interfaces as monolithic spaghetti code. Java beans have recently proven to be an effective mechanism for promoting reusability. Moreover, if Java toolkits belong in the course, as most textbooks believe, so do these three concepts. To cover AWT or Swing, we must tell students what an interface is so that event listeners can be attached to buttons and other input 2 The book probably errs in the direction of over explanation. The author would appreciate specific examples of places where the obvious was said or there was unnecessary repetition. Preface 3 objects. If we are going to teach interfaces and event listening, we might as well do so properly. It is then a small step to also teach them MVC and beans. Therefore, the textbook covers interfaces and event listening, early, as first-class concepts, important in their own right, rather than late as mechanisms necessary for using the Java toolkit. Moreover, it makes use of the overlap between Java toolkits and MVC and beans to allow the latter two to be also covered in a semester course. Organization Each chapter of the book contains an introduction motivating the concepts covered in it, the detailed coverage of the concepts, a summary of the constructs, principles, and techniques explained in the chapter, and a set of questions. The questions include the kind that can be asked in exams and recitation classes and those that form programming assignments. The book starts by explaining the world of computers – CPU, operating system, programmer, user and so on – in terms of the world of theater – performer, director, author, audience and so on. It is difficult to program without knowing about the context provided by the basic components of a computer system. The theater analogy gives the student an idea of the roles of these components. Chapter 2 introduces programming to them through the concept of objects and classes, which are presented as analogues of physical objects and the factories that manufacture them. The classes they see here are simply collections of pure (stateless) functions. They first implement functions of the kind they have seen in Mathematics – parameterized functions of integers and real numbers – and then they see parameter-less functions, and functions of strings. Chapter 3 explains instance variables, and getter functions and setter procedures that expose the values of these variables as bean properties. Using ObjectEditor, they visually see the difference between the pure, stateless methods they implemented earlier, and the impure state-based methods they see here. Their familiarity with spreadsheets is used to illustrate and explain the concept of state. Chapter 4 explains interfaces, motivating them by showing that it possible to create multiple implementations of the same spreadsheet interface. The broader theme of this chapter is the concept of programming style. Students learn that it is not enough to create a program works; they must also make use of interfaces, modularization, programming conventions, comments, named constants, and other styling mechanisms to ensure that the program is well written. The principle of least privilege and the tradeoff between space and time efficiency are also introduced here. Chapter 5 covers all of the primitives types provided by Java. Each of these types is presented, just as a class is, as a set of operations. Thus, students learn that there is no fundamental difference between primitive and object types. They are given in-depth practice with character and Boolean types, learning how characters are ordered and that it is possible to use Boolean expressions without conditional statements. Operator precedence, short-circuit evaluation, type coercion, and strong typing are also covered here. Chapter 6 addresses, in-depth, programmer-defined types. Four important aspects in the programming of such types, interface, representation, algorithm, and implementation are identified and illustrated. The distinction between topdown and bottom-up design of these aspects is made. Other related concepts covered here are null pointers, polymorphism, constructors, and the distinction between instance and class variables and structure and simple types. Chapter 7 takes away the training wheels of ObjectEditor, teaching students how to implement their own, consolebased, user-interface using a main class. The messy details of console I/O are used to illustrate the need for creating multi-level algorithms and developing library classes. Chapter 8 explains conditionals, comparing different ways of writing nested conditional statements. Chapter 9 addresses loops, making the classical distinction between counter-controlled and event-based loops. It introduces the break statement as a mechanism to eliminate code duplication in event-based loops. Chapter 10 presents recursion as an alternative to loops. It could easily be taught before chapter 9. The reason for the chosen order is that the programming assignment on loops builds on the one on conditionals. Preface 4 Chapter 11 uses a scanning problem to explain indexing and enumeration. Students learn to implement a programmerdefine enumeration interface that lists scanned tokens. Arrays are introduced in the next chapter as programmer-defined collections. Standard array algorithms such as adding, deleting and searching for an array element are presented as operations on programmer-defined objects such as histories, databases, and sets. The fact that these objects share operations is used to introduce inheritance. Chapter 13 puts the training wheels on again for introducing graphics. Rather than simply illustrating output of graphical objects; it uses ObjectEditor to create examples that allow graphical objects to be edited. It provides further practice in both counter-controlled and event-based loops, showing how they can be used to animate graphical objects. It also explains how animation can be implemented using ObjectEditor. Chapter 14 and 15 take the training wheels away, showing how Java AWT can be used directly to create graphical interfaces with animation. Instead of presenting spaghetti user-interface code, they motivate and explain the use of model view controller design pattern; first for creating familiar console interfaces and then for the graphical interfaces. Chapter 16 explains files, explaining serialization and de-serialization of objects, and how to use both binary and text files. Finally, Chapter 13 discusses some of the fine differences between primitive and object types that are important to program correctly in Java. In particular, it explains the notion of a pointer, which leads to garbage collection. It does not explain advanced usage of pointers such as trees - enough about pointers is explained so that studentds do not get in trouble with assignment of objects.