SOFTWARE TOOLS FOR THE

FS 0.1• • ,..­

:OMPARING )0 LANGUAGES

3.95 ($4.95 CANADA) 1 0

6562 8 ' SOFTWARE r 0 STOOLS FOR THE DJL, D b PROFES90NAL J 0 U R ~ A L PROGRAIMfER ( 0 N

FEATURES GUESSING GAMES 16 by PI Plauger Speculating on the eventual success or failure of a programming language is a popular, if not demanding) pastime where everyone's best guess is as good as anyone else's, The +@ PROGRAMMING LANGUAGE 24 by jim Fleming C+@ (pronounced "cat"), an object-oriented language out of AT&T Bell L1bs, has the syntax of Cand the power of Smallralk. Unlike C++, however, C+@ includes a library of more than 350 classes, THE PARASOL PROGRAMMING LANGUAGE 34 by Robe1t jerois Parasol, short for "Parallel Systems Object Language," was influenced by Cand Smalltalk, although the design also reflects C++, CLU, AJgol , and Turbo Pascal. THE SATHER PROGRAMMING LANGUAGE 42 by Stephen M, Omohundro Sather, a language that's simple, interactive, and nonproprietary, has parameterized classes, object-oriented dispatch, statically-checked strong typing, multiple inheritance, garbage collection, and more, THE LIANA PROGRAMMING LANGUAGE so by Ray Valdes Liana is an object-oriented progranuning language specifically designed for creating Windows applications, Like C++, Liana uses classes and member functions to provide encapsulation, inheritance, and polymorphism, Unlike C++, Liana does not use pointers or support mUltiple inheritance, THE BETA PROGRAMMING LANGUAGE S6 by Steve lvlann Since Beta was designed by the same community that developed Simula, it's no surprise that this language resembles its object-oriented predecessor,

THE EIFFEL PROGRAMMING LANGUAGE 68 by Robert Howard Eillel is a class-based language that SUppOI1S multiple and repeated inheritance, selective exporting, strong type checking, parameterized classes, dynamic binding, garbage collection, and exception handling, DAVE'S RECYCLED 00 LANGUAGE 74 by David Betz David dusts off AdvSys, an object-oriented adventure-writing language, adding multiple inheritance to it. The result is "Dave's Recycled Object-Oriented Language" (or "Drool" for short) THE ART OF PRODUCT LAUNCHES 80 by Diane McGary To celebrate the 10th alUliversary of ,the Software Entrepreneurs' Fontm, Diane shares guerrilla marketing tips for successfully gelling your software into user's hands, C++ MANIPULATORS AND APPLICATORS 1SO by Reginald B. Charney C++ manipulators and applicators are most often used with the VO streams package, However, you can use them with any type of class which has overloaded operators,

2 Dr, Dobb'sjournal, October 1993 The Sather Programming Language " Efficient, interactive, and object oriented

Stephen M. Omohundro

ather is an object-oriented lan­ programs consist of collections of mod­ guage which aims to be simple, ules called "classes" which encapsulate efficient, interactive, safe, and well-defined abstractions. If the ab­ nonproprietary. One way of plac­ stractions are chosen carefully, they can ing it in the "space of languages" be used over and over in a variety of Sis to say that it aims to be as efficient different situations. as C, C++, or Fortran, as elegant and An obvious benefit of reuse is that safe as Eiffel or CLU; and to support in­ less new code needs to be written. As teractive programming and higher-or­ important is the fact that reusable code der functions as well as , is usually better written, more reliable Scheme, or Smalltalk. and easier to debug because program­ Sather has parameterized classes, ob­ mers are willing to put more care and ject-oriented dispatch, statically checked thought into writing and debugging strong typing, separate implementation code which will be used in many pro­ and type inheritance, multiple inheri­ jects. In a good object-oriented envi­ tance, garbage collection, iteration ab­ ronment, programming should feel like straction, higher-order routines and iters, plugging together prefabricated com­ exception handling, constructors for ar­ ponents. Most bugs occur in the 10 per­ bitrary data structures and asse11ions, cent or so of newly written code, not preconditions, postconditions, and class in the 90 percent of well-tested library invariants. This article describes a few classes. This usually leads to Simpler de­ of these features. The deve'lopment en­ license which allows its use in propri­ bugging and greater reliability. vironment integrates an interpreter, a etary projects but encourages contribu­ Why don't traditional subroutine li­ debugger, and a compiler. Sather pro­ tion to the public library. braries give the same benefits? Subrou­ grams can be compiled into portable C The original 0.2 version of the Sather tine libraries make it easy for newly writ­ code and can efficiently link with C ob­ compiler and tools was made available ten code to make calls on existing code ject files. Sather has a very unrestrictive in June 1991. This anicle describes Ver­ but don't make it easy for existing code sion 1.0. By the time you're reading to make calls on new code. Consider a Stephen does reseatch on teaming and this, the combined 1.0 compiler/ inter­ visualization package that displays data computer vision, as well as dewloping preter/debugger should be available on on a certain kind of display by calling Sather at the International Computer ftp.icsi.berkeley.edu and the newsgroup display-interface routines. Later, the de­ SCience Institute, 1947 Centet Street, comp.lang.sather should be activated cision is made that the package should Berkeley, CA 94704. He wmte the three­for discussion. work with a new kind of display. In tra­ dimensional graphics Jor Mathematica ditional languages, there's no simple and was a co-designer ojStat-Lisp Jor Code Reuse way to get the previously written visu­ the Connection Machine. He can be con­The primary benefit object-oriented lan­ alization routines to make calls on the tacted at [email protected]. guages promise is code reuse. Sather new display interface. This problem is

42 Dr. Dobb'sjoumal, October 1993 SATHER

(continued from page 42) ANGLE and SQUARE objects can be widely discussed is the problem of the especially severe if the choice of dis­ pushed onto stacks of this type. The call add_vertex routine for polygons. This play interface must be made at run time. s,pop might return either a triangle or a is a routine which makes sense for Sather provides [\vo primaly ways for square. The call s.pop.number_oJ-ver­ generic polygons but does not make existing code to call ne\vly written code. tices calls either the number_oJ-vertices sense for triangles, squares, and so on. "Parameterized classes" allow the bind­ routine defined by TRIAi\lGLE and re­ 111 languages which do not separate ab­ ing to be made at compile time and "olr turns 3, or the numbe,"-oJ-vertices rou­ stract types from particular implemen­ ject-oriented dispatch" allows the choice tine defined by SQUARE and returns 4. tations, you must either make all de­ to be made at run time. I'll demonstrate The choice is made according to the scenclants implement routines that don't these two mechanisms using simple run-time type of the popped object. The : make sense for them, or leave out func­ classes for stacks and polygons. names of abstract types begin with a $ tionality in parent classes. (dollar sign) to help distinguish them The Sather solution to this is based Parameterized Classes (calls on abstract types are slightly more on abstract types. The Sather libraries Listing One (page 112) shows a class expensive than non-dispatched calls). include the abstract class $POLYGON, which implements a stack abstraction. which defines the abstract interface that We want stacks of characters, strings, I Strong Typing all polygons must provide. It also in­ polygons, and so on, but we don't The Sather is a major fac­ cludes the descendant class POLYGON, want to write new versions for each tor in the computational efficiency, clar­ which implements generic polygons. type of element. STACK{TI is a "pa­ ity, and safety of Sather programs. It The add_uertex routine is defined in rameterized class" in which the pa­ also has a big effect on the "feel" of POLYGON but is not defined in $POLY­ rameter T specifies the stack element Sather programming. Many object­ GON. TRIANGLE and SQUARE, there­ type. When the class is used, the type oriented languages have either weak fore, do not need to define it. parameter is specified. typing or none at all. Sather, however, Run-time dispatching is only done for For example, the class FOO in Listing is "strongly typed," meaning that every calls on variables declared by abstract One defines a routine which uses both Sather object and variable has a speci­ types. The Sather compiler is, itself, a a stack of characters and a stack of strings. fied type and that there are precise mles large program written in Sather which The type specifier STACK{CHARI causes defining the types of object that each uses a lot of dispatching. The perfor­ the compiler to generate code with the variable can hold. Sather is able to stat­ mance consequences of abstract types type parameter T replaced by CHAR. The ically check programs for type correct­ were studied by comparing a version of specifier STACK{STRI similarly causes ness-if a piece of Sather code is ac­ the compiler, in which all calls were dis­ code to be generated based on S1R Since cepted by the interpreter or compiler, patched, to the standard version (Lim character objects are usually eight bits it's impossible for it to assign an object and Stokke, 1991). The use of explicit and strings are represented by pointers, of an incorrect type to a variable. typing causes one-tenth the number of the two kinds of stack will have differ­ Statically checked, strong typing helps dispatches and an 11.3 percent reduc­ ent layouts in memory. The same Sather the Sather compiler generate efficient tion in execution time. is reused to generate differ­ code because it has more information. ent object code for the two types. We Imy Sather avoids many of the mn-time tag­ Separate Implementation and Type defme a new type (such as tliple-length checking operations done by less strong­ Inheritance integers) and immediately use stacks ly typed languages. In most object-oriented languages, in­ of elements of that type without moclify­ Statically checked, strongly typed lan­ heritance defines the subtype relation ing the STACK class. Using parame­ guages help programmers to produce and causes the descendant to use an telizecl classes adds no extra mn time cost, programs that are more likely to be cor­ implementation provided by the ances­ but the choice of type parameter values rect. For example, a common mistake tor. These are quite different notions; must ,be made at compile time. in C is to confuse the C assignment op­ confusing them often causes semantic erator = with the C equality test ==. Be­ problems. For example, one reason why Object-oriented 'Dispakh cause the C conditional statementij( ..) Eiffel's type system is dimcult to check Listing Two (page 112) shows an ex­ doesn't distinguish between Boolean is that it mandates "covariant" confor­ ample of object-oriented dispatch. The and other types, a C compiler is just as mance for routine argument types (Mey­ class $POLYGON is an "abstract" class happy to accept ij(a=b) as ij(a==b). In er, 1992). This means a routine in a de­ which means it represents a set of pos­ Sather, the conditional statement will scendant must have argument types sible object types called its "descen­ only accept Boolean values, rendering which are subtypes of the correspond­ dants " (in this case TRIANGLE and impossible this kind of mistake. ing argument types in the ancestor. Be­ SQUARE). Abstract classes define ab­ Languages like Beta are also strongly cause of this chOice, the compiler can't stract interfaces which must be imple­ typed, but not statically checkable. Con­ ensure argument expressions conform mented by all their descendants. List­ sequently, some type checking must be to the argument type of the called rou­ ing Two only shows the single routine done at nm tin1e. While this is preferable tine at compile time. In Sather, inheri­ number_oLvertices.1NT which returns to no type checking at all, it reduces the tance from abstract classes defmes sub­ the number of vertices of a polygon. safety of programs. For instance, there typing while inheritance from other TRIANGLE's implementation returns the may be a typing problem in obscure classes is used solely for implementa­ value 3, and SQUARE's returns 4. code that isn't exercised by test routines. tion inheritance. This allows Sather to Routines in the interface of an abstract Errors not caught by the compiler can use the statically type-safe contravariant type may be called on valiables declared make it into final releases. rule for routine argument conformance. by that type. The actual code that'S Sather distinguishes "abstract types," called, however, is determined at run which represent more than one type of Multiple Inheritance time by the type of the object which is object, from other types, which do not. In Smalltalk and Objective-C, each class held by the variable. The class F002 This has consequences for both the con­ only inherits from a single class. In defines a routine with a local variable ceptual structure and the effiCiency of Sather, classes can inherit from an arbi­ of type STACK{SPOLYGON]. Both TRI­ programs. An example which has been trary number of classes, a property

44 Dr. Dobb'sjournal, October 1993 SATHER

(continuedfrom page 44) quire the internal implementation de­ chitectures. On a series of benchmark called "multiple inheritance," This is im­ tails of data structures like hash tables tests (towers of HanOi, 8 queens, and portant because it commonly occurs in to be exposed when iterating over their the like) Satller performed slightly bet­ modeling physical types. For example, elements. ter than C++ and several times better there might be types representing Sather allows you to cleanly encap­ than Eiffel. The new compiler performs "means of transportation" and "major sulate iteration using constructs called extensive automatic inlining and so pro­ expenditures." The type representing "iters" (Murer, Omohundro, and vides more opportunities for optimiza­ "automobiles" should be a descendant Szyperski, 1993) that are like routines, tion than typical handwritten C code. of both of these. In Smalltalk or Objec­ except their names end in an excla­ tive-C, which only support single in­ mation point (I) , their bodies may The Libraries heritance, you'd be forced to make all contain yield and quit statements, The Sather libraries currently contain "means of transportation" be "major ex­ and they may only be called with­ several hundred classes and new ones penditures" or vice versa. in loops. The Sather 'loop construct are continually being written. Eventu­ is simply: loop... end. When an iter ally, we hope to have effiCient, well­ Garbage Collection yields,.it returns control to the loop. written classes in every area of com­ Languages derived from C are usually When it is called in the next itera­ puter science. The libraries are covered not "garbage collected," making you re­ tion of the loop, execution begins by an unrestrictive license which en­ sponsible for expliCitly creating and de­ at the statement following the yield. courages the sharing of software and stroying objects. unfortunately, these When an iter quits, it terminates the I crediting authors, without prohibiting memory-management issues often cut loop in which it appears. All class­ use in proprietary and commercial pro­ across natural abstraction boundaries. es define the iters until/(BOOL), jects. Currently there are classes for ba­ The objects in a class usually don't know whilei(BOOL) , and breaki to im­ sic data structures, numerical algorithms, when they are no longer referenced and plement more traditional looping geometriC algorithms, graphics, gram­ the classes which use those objects constructs. The integer class defines mar manipulation, image processing, shouldn't have to deal with low-level a variety of useful iters including statistics, user interfaces, and connec­ memory-allocation issues. uptoi(INT):JNT, downtol(J/I.'7).1NT, and tionist simulations. Memory management done by the stepi(num,step.1NT).1NT. Listing Four programmer is the source of two com­ (page 112) shows how uptoi is used to pSather mon bugs. If an object is freed while output digits from 1 to 9. Sather is also being extended to sup­ still being referenced, a later access may Container classes, such as arrays or port parallel programming. An initial fmd the memory in an inconsistent state. hash tables, define an iter eltsi:Tto yield version of the language "pSather" (Mur­ These so-called "dangling pointers" are the contained elements and an iter er, Feldman, and Lim, 1993) runs on the difficult to track down because they of­ called seceltsi(7) to inselt new elements. Sequent Symmetry and the Thinking Ma­ ten cause code errors far removed from Listing Four shows how to set the ele­ chines CM-5. pSather adds constructs the offending statement. ments of an array to successive integers for programming on a distributed-mem­ "Memory leaks," caused when an ob­ and then how to double them. Notice ory, shared-address machine model. It ject is not freed even though there are that this loop doesn't have to explicitly includes sUppOIt for control parallelism no references to it, are also hard to find. test indices against the size of the array. (thread creation, synchronization), an Programs with this bug use more and The tree classes have iters to yield SPMD form of data parallelism, and more memory until they crash. Sather their elements according to the "pre," mechanisms to manipulate execution uses a "garbage collector" which tracks "post," and "in" orderings. The graph control and clata in a nonuniform ac­ down unused objects and reclaims the classes have iters to yield the vertices cess machine. The issues which make space automatically. To further enhance according to depth-first and breadth-first object-oriented programming impoltant performance, the Sather libraries gen­ search orderings. in a serial setting are even more im­ erate far less garbage than is typical in portant in parallel programming. Effi­ languages like Smalltalk or Lisp. The Implementation cient parallel algorithms are often quite The first version of the Sather compiler complex and should be encapsulated Interactive, Interpreted Programming was written in Sather by Chu-Cheow in well-written library classes. Different Sather combines the flexibility of an in­ Lim and has been operational for sev­ parallel architectures often require the teractive, interpreted envirorunent with eral years. It compiles into C code and use of different algorithms for optimal velY high-efficiency compiled code. Dur­ has been ported to a wide variety of effiCiency. The object-oriented approach ing development, the well-tested library machines. It is a fairly large program allows the optimal version of an algo­ classes are typically run compiled, while with about 30,000 lines of code in 183 rithm to be selected according to the the new experimental code is run in­ classes (this compiles into about 70,000 machine it is actually running on. It is terpreted. The interpreter also allows lines of C code). often the case that parallel code devel­ immediate access to all the built-in al­ Lim and StoIcke extensively studied opment is done on simulators running gorithms and data structures for exper­ the performance of the compiler on on serial machines. A powerful object' imentation. listing Three (page 112) is an both MIPS and Sparc architectures. Be­ oriented approach is to write both sim­ example of an interactive Sather session. cause the compiler uses C as an inter­ ulator and machine versions of the fun­ mediate language, the quality of the ex­ damental classes in such a way that a Iteration Abstraction ecutable code depends on the match of user's code remains unchanged when Most code is involved with some form the C code templates used by the Sather moving between them. of iteration. In loop constructs of tradi­ compiler to the optimizations employed tional languages, iteration variables must by the C compiler. Compiled Sather Conclusion be explicitly initialized, incremented, code runs within 10 percent of the per­ I've described some of the fundamen­ and tested. This code is notoriously formance of handwritten C code on the tal design issues underlying Sather 1.0. tricky and is subject to "fencepost er­ I MIPS machine and is essentially as fast The language is quite young, but we rors. " Traditional iteration constructs re­ as handwritten C code on the Sparc ar­ are excited by its prospects. The user

46 Dr. Dobb'sjournal, October 1993 SATHER

(continued from page 46) community is growing, and new class development has become an interna­ tional, cooperative effort. We invite you join in its development! Acknowledgments Sather has adopted ideas from a num­ ber of other languages. Its primary debt is to Eiffel, designed by Bertrand Mey­ er, but it has also been influenced by C, C++, CLOS, CLU, Conunon Lisp, Dy­ lan, ML, Modula-3, Oberon, Objective C, Pascal, SAIL, Self, and Smalltalk. Many people have contributed to the devel­ opment and design of Sather. The con­ tributions of Jeff Bilmes, Ari Hummen, Jerry Feldman, Chu-Cheow Lim, Stephan Murer, Heinz Schmidt, David Stoutamire, and Clemens Szyperski were particu­ larly relevant to the issues discussed in this article. References ICSI Technical reports are available via anonymous ftp from ftp.icsLberkeley.edu. Lim, Chu-Cheow and Andreas Stol­ eke. "Sather Language Design and Per­ formance Evaluation." Technical Report 1R-91-034. International Computer Sci­ ence Institute, Berkeley, CA, May 1991­ Meyer, Bertrand. Eiffe/- The Language. Prentice Hall, New York, NY, 1992. Murer, Stephan, Stephen Omohundro, and Clemens Szyperski. "Sather Iters: Object-oriented Iteration Abstraction." ACM Letters on Programming Languages and Systems (submitted), 1993. Murer, Stephan, Jerome Feldman, and Chu-Cheow Lim. "pSather: Layered Ex­ tensions to an Object-Oriented Language for Efficient Parallel Computation." Tech­ nical Report 1R-93-028. International Computer Science Institute, Berkeley, CA, June 1993. Omohundro, Stephen. "Sather Pro­ vides Non-proprietary Access to Object­ oriented Programming." Computers in Physics. 6(5):444-449, 1992. Omohundro, Stephen and Chu­ Cheow Lim. "The Sather Language and Libraries ." Technical Report 1R-92-017. International Computer Science Institute, Berkeley, CA, 1991­ Schmidt, Heinz and Stephen Omo­ • Objectworks c;:rn:rl.....I.. \;,U3WfJ1 Software DeYe~t hundro. "CIos, Eiffel, and Sather: A Com­ • VisualWorks Legacy Systems parison," in Object Oriented Program­ ming: The CLOS Perspective, edited by • Smalltalk for Cobol Programmers GUI's, Databa5es Andreas Paepcke. MIT Press, Boston, • Analysis & Design Client-Server MA,1993. • Project Management • In-House & Open Courses DDJ The Object People Inc. 509-885 Meadowtands Dr., Ottawa, Ontario, K2C 3N2 (Listings begin on page 112.) VOle for your faVOrite fearurei aI1icle. Telephone: (613) 225-8812 FAX: (613) 225-5943 Circle Reader Service No.4.

SmaRtalkN and PARTS He registered trademarks of Oigitalk, Inc. Objoctworks and ViwalWortc.! are trademarks of ,.",Place S)"tems Inc.

CIRCLE NO. 533 ON READER SERVICE CARD 48 Dr. Dobb's }ournal, October 1993 SATHER

Usting One (Text begins on page 42) inherit SPOLYGON; class STACK(T} is number_oL vertices:INT is res:=4 end: •• Stacks of elements of type T. end; attr s :ARR(T}: -­ An array containing the elements. attr size:INT: -­ The current insertion l ocation. class Foo2 is bac2 is is.empty:BOOL is s :STACK ( SPOLYGONJ : -- True if the suck is empty. res := (s=void or size""0) end; 0:=8. pop. numbec _oLvertices;

pop:T is end; -- Return the top element and remove it. Void if empty. end: if is.empty then res:=void else size:""size-l: res:", [size] : & [size} :=void end end: Usting Three push (T) is -- Push arg onto the stack. >5+7 if sl:void then s:=URR(T) (asize:=5) 12 elsif size~s .a8 ize then double.size end ; s [aize] ::r::arg: size:=size+l end: >40 . intinf . factor i al 8159152832 4789773434561 12 695961158942721100000000 private double.size is: -- Double the size of . s' . >;f OUT + "Hello woe ld! " ns::=tiARR{T){asize:=2*s.asize) ; ns.copy.fr om(s): s;=ns end: Hell o itr'orld!

clear is >v: :='VEC( 1.0.2.0.3.0): ,,:='VEC(1.0.2.0.3.0): -- Empty the stack. >v+"'" size:=0: B.clear end ~VEC(2 .0 . 4.0. 6.0) end: -- class STACK(T} >v.dot('.oI) 14.0 class FOO is bac is >#ARRAY(STR} ("grape". ne hecry". "apple" . "plum". "orange"). sort ll sl:STACK(GHARJ: ,l.push('.') : ~ ARRAY{STR) ("apple", "checcy". "grape". "orange". "plum ) s2:STACK(STR}; s2.push("'I'his is 8 string.") end: end: Listing Four

Listing Two >loop ~OUT+l.upto! (9) end 123456789 abstract class $POLYGON is >a: : ,..jZARRAY(INTJ (aaize: =10) numbeLoLvectices: INT: >loop a . seLel ts! (1. upto! (1 0» end end; >a .ARRAY(INT) (1. 2.3 .4. 5.6. 7.8.9 . 10) class TRIANGLE is inherit SPOLYGON: >loop a. s eLelts! (2 . a. e l ts !) end >. number_of_vertices: INT is res: =3 end: 'ARRAYONTJ (2.4.6.8.10,12.14.16.18.20) end; class SQUARE is End Listings

DJ: Dobb's jOllrlzal Special Issue Sourcebook ofWindows Programming

You demand expert, unique information on developing for Windows. T he Dr. Dobb's Sourcebook ofWindows Programming gives you that ~P[CIAl ISSUE Iliclulles Willdows NT singular perspective only Dr. Dobb sJournal provides. Find out how to: • D evelop multivendor W indows databases • Write cUStom control • C reate horizontally scrollable list boxes • Get inside the TrueType fo rmat • and much more! Pure, hard info rmation. Lots of code. Put this special issue to work for you!

AVAILABLE AT YOUR REGULAR NEWSSTANDS ON AUGUST 31 . Order Direct: Mail check to: Dr. Dobb's Joumai 800-433-0700 PO Box 105843 VISA/Mastercard Atlanta. GA 30348-5843

Only $4.95, plus $1.50 1 r class shipping. uppUes limited. Allow 4-6 weeks fur delivery.

112 Dr. Dobb's]ournai, October 1993