32
ISTrn511talk1 tiltors JohnPughandPaulWhite CodetonUrrivewffy&JJreObj~tPe@e ;IGS Publications Advisory Board TomAtwood, Object Design FranfoisBancilhon, 02Terhnokgia GradyBooth, Rrrtiona/ GeorgeBosworth, Oigita/k JesseMichael Chonoles,ACCofA4rzrtih Moriettrz StuartFmst,SflEf150ftworeTOOIJ AdeleGoldberg, Przrrf%reSytenr~ lLJordanKriendler, IBM(onsuftirrg Group Tomlove,Corrdtant BerhandMeyer,/5E MeitirPage-Jones, Woy/mmf$Wemr CliffReeve> IBM BjameStmustrup,,4T&Tkf/& rbs DaveThoma!, Object Technology hrterrmtional me Smalltalk Report tihorial Board JimAnderson, Digitalk AdeleGoldberg, PrrrcP/oceSystemr ReedPhillips MikeTaylor, Digito/k DaveThomas, Object lechrmlogylrrternotionol :olumnists JayAlmamde KentBeck, firrt(/m$SotWre JuanitaEwin$Digito/k GregHendley,Know/erfge fystem~COrp ilm Howard, FJfProtorol krc AlanKnight, JheObjwtkop/e WTltiamKohl, ibthWe//brtematform/ Marklorenz,Mtwos Soffwore, Inc. EricSmith, f(nowkvlge $memr @ Rebecsa WirJs-BmckDigita/k ;IGS Publications Group, Inc. RichardP.Friedman, Founder, P~iderrt,andCEO HalAvery,GmupPubfisher :ditor4al/Production KristinaJoukhadar, Editorial Ohector Eti5aVarian, Production Manager AndreaCammarata, ArtDirestor EliibethA.Up~AssosiateManagingEditor Margaretlmti,AdveriisirrgProduction Coordinator circulation Bmce$hriver,Jr.,Cirsulation Director JohnR.Wengler,~rculation Manager 4dvertlsing/Marketing Gary PortieAdvertising Manager,Ea$t Coast/Canada/Europe JeJfSmith, Advertising Manager, CentralU.S. Mishael W.Pedr,Advetiising Representative KristineViksnins, ExhibitSalesRepresentative 212.242.7447(v),212.242.7574(f) DianeFuller&Associates,5al~Rep~entative,WestCoast 408.255.2991(v),4D8.255.2992(f) SarahHamilton, DirertorofPmmotions andResearch WendyDhrbokowitz,Pmmotiorrs ManagerforMagazines CarenPolner,Senior Promotions GraphicDesigner \dministratlon MarghwkaR.Mondr,General Manager DavidChatterpaul,Senior Accounting Manager JamesAmerruvor, Business Manager MicheleWatkins, Assistant tothe president ~SIGS PUBLICATIONS .tiblishers of JOURNAL OF0Brr3cr-OmN’rEo PROGRAMMING, OBJECTMAGAZINE, C++ RIWOIrT, THE ShWLTALKREPORT, THEX JOURNAL, RIPORTON DBIECZANALYSIS&DESIGN, and Ommcr SPEKTMJM [GERMANY) July-August 1995 Vol 4 No 9 Features Remembrance of thingspast: Layeredarchitectures forSmalltalkapplications Kyle Brown Using a layered architecture and building from the”inside out” promotes good design, reduces application complexity, and encourages reuse. Segregatingapplicationanddomain Tim Howard The author introduces the domain adaptor architecture, a specialization of the application model architecture that is designed to work specifically with domain objects. 8 Columns Deep in the Heart of Smalltalk 13 ParameterizedCompile~ Making code reusable BoiI Hinlde and Ralph E. Johnson Motivated by a desire to implement a new breakpoint mechanism, the authors revise Smalltalk’s compiling subsystem to improve its flexibility. Smalltalk Idioms A modest meta proposal Kent Beck Introducing a MetaObject class lessens the risks of meta programming. Project Practicalities d Rules to live by Mark Lorenz How to resolve or, better yet, avoid some problems frequently encountered in O-O development. 19 22 Departments Editors’Comer Recruitment Managing Objects 26 Managing project documents Jan Steh’fman and Barbara Yates Techniques for managing base image changes when projects require changes to a vendor’s code. 2 28 The 5malltalh Report [lS5N# 1056-7976) is published 9 times a year,monthly except in Mar-Apr, July-Aug, and Nov-Dee, Pubfkhed by 51G5 Publications Inc.. 71 West 23rd St.. 3rd Floor. New York, NY 10010.0 Coovrioht 1995 bv 51G5 Publications All riahts resewed. Frepmduction of this material by electronic tramrnission, Xer.n or any other “rns%d will k- treated as a willful viola;on OFthe US Copyright law and isFlatly prohibirsd, Material maybe reproduced with express permission fmm the publisher. 5econd Classpostage Pending at NV,NY and additional Mailing ofices. Canada Post International Publications Mail Product SalesAgreement No. 2903B6. Individual subscription rates 1 year (9 issueshdomestic SE% Mexico and Canada $114, Foreign $129; Institutional/Library rates domestic $199, Canada & Mexico $224, Foreign $239, To submit articles, please send electronic files on disk to the EdiIors at E85 Meadowlands Drive #5o9, Ottawa, Ontsrio X2C 3N2, Canada, m via Internet to [email protected] formats for figures are Mac or DOS EP5,TfF, or GIF formats,Always send a paper copy of your manusaipt, including camem-ready copiesof your figures (laser output is fine). P05TMA5TEFt Send domestic address changes and subscription orders tmllw Smalltalk Report, P.O.Box 5050, Brentwoad,TN 37024 - 5050. For serviceon current domestic subscriptionscall 1.000.361.1279 or fax 615.370.4645. [email protected] foreign subscription orcers and inquiries phone +44[0)1 E5E.435302. PRINTED IN THE UNITED STATES. July-August1995 1

Smalltalk Volume 4 Issue 9 - ESUG

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Smalltalk Volume 4 Issue 9 - ESUG

ISTrn511talk1tiltors

JohnPughandPaulWhiteCodetonUrrivewffy&JJreObj~tPe@e

;IGS Publications Advisory BoardTomAtwood,ObjectDesignFranfoisBancilhon,02TerhnokgiaGradyBooth,Rrrtiona/GeorgeBosworth,Oigita/kJesseMichaelChonoles,ACCofA4rzrtihMoriettrzStuartFmst,SflEf150ftworeTOOIJAdeleGoldberg,Przrrf%reSytenr~lLJordanKriendler,IBM(onsuftirrgGroupTomlove,CorrdtantBerhandMeyer,/5EMeitirPage-Jones,Woy/mmf$WemrCliffReeve>IBMBjameStmustrup,,4T&Tkf/&rbsDaveThoma!,ObjectTechnologyhrterrmtional

me Smalltalk Reporttihorial Board

JimAnderson,DigitalkAdeleGoldberg,PrrrcP/oceSystemrReedPhillipsMikeTaylor,Digito/kDaveThomas,Objectlechrmlogylrrternotionol

:olumnistsJayAlmamdeKentBeck,firrt(/m$SotWreJuanitaEwin$Digito/kGregHendley,Know/erfgefystem~COrpilm Howard,FJfProtorolkrcAlanKnight,JheObjwtkop/eWTltiamKohl,ibthWe//brtematform/Marklorenz,Mtwos Soffwore,Inc.EricSmith,f(nowkvlge$memr @RebecsaWirJs-BmckDigita/k

;IGS Publications Group, Inc.RichardP.Friedman,Founder,P~iderrt,andCEOHalAvery,GmupPubfisher

:ditor4al/ProductionKristinaJoukhadar,EditorialOhectorEti5aVarian,ProductionManagerAndreaCammarata,ArtDirestorEliibeth A.Up~AssosiateManagingEditorMargarettlmti,AdveriisirrgProductionCoordinator

circulationBmce$hriver,Jr.,CirsulationDirectorJohnR.Wengler,~rculationManager

4dvertlsing/MarketingGaryPortieAdvertisingManager,Ea$tCoast/Canada/EuropeJeJfSmith,AdvertisingManager,CentralU.S.MishaelW.Pedr,AdvetiisingRepresentativeKristineViksnins,ExhibitSalesRepresentative

212.242.7447(v),212.242.7574(f)DianeFuller&Associates,5al~Rep~entative,WestCoast

408.255.2991(v),4D8.255.2992(f)SarahHamilton,DirertorofPmmotionsandResearchWendyDhrbokowitz,PmmotiorrsManagerforMagazinesCarenPolner,SeniorPromotionsGraphicDesigner

\dministratlonMarghwkaR.Mondr,GeneralManagerDavidChatterpaul,SeniorAccountingManagerJamesAmerruvor,BusinessManagerMicheleWatkins,Assistanttothe president

~SIGSPUBLICATIONS

.tiblishers of JOURNALOF0Brr3cr-OmN’rEoPROGRAMMING,OBJECTMAGAZINE,C++ RIWOIrT,THEShWLTALKREPORT,THEX JOURNAL,RIPORTONDBIECZANALYSIS&DESIGN,and Ommcr SPEKTMJM[GERMANY)

July-August 1995 Vol 4 No 9

Features

Remembranceof thingspast:LayeredarchitecturesforSmalltalkapplicationsKyle BrownUsing a layered architecture and building from the”inside out” promotes good design,reduces application complexity, and encourages reuse.

SegregatingapplicationanddomainTim HowardThe author introduces the domain adaptor architecture, a specialization of the applicationmodel architecture that is designed to work specifically with domain objects.

8

Columns

Deep in the Heart of Smalltalk 13ParameterizedCompile~ Making code reusableBoiI Hinlde and Ralph E. JohnsonMotivated by a desire to implement a new breakpointmechanism, the authors revise Smalltalk’s compiling

subsystem to improve its flexibility.

Smalltalk IdiomsA modest meta proposalKent BeckIntroducing a MetaObject class lessens the risks of meta programming.

Project Practicalities dRules to live byMark LorenzHow to resolve or, better yet, avoid some problems frequently encountered inO-O development.

19

22

DepartmentsEditors’ComerRecruitment

Managing Objects 26Managing project documentsJan Steh’fmanand Barbara YatesTechniques for managing base image changes when projectsrequire changes to a vendor’s code.

228

The 5malltalh Report [lS5N# 1056-7976) is published 9 times a year, monthly except in Mar-Apr, July-Aug, and Nov-Dee, Pubfkhed by51G5 Publications Inc.. 71 West 23rd St.. 3rd Floor. New York, NY 10010.0 Coovrioht 1995 bv 51G5 Publications All riahts resewed.Frepmduction of this material by electronic tramrnission, Xer.n or any other “rns%d will k- treated as a willful viola;on OFthe USCopyright law and isFlatly prohibirsd, Material maybe reproduced with express permission fmm the publisher. 5econd ClasspostagePending at NV,NY and additional Mailing ofices. Canada Post International Publications Mail Product SalesAgreement No. 2903B6.

Individual subscription rates 1 year (9 issueshdomestic SE% Mexico and Canada $114, Foreign $129; Institutional/Library ratesdomestic $199, Canada & Mexico $224, Foreign $239, To submit articles, please send electronic files on disk to the EdiIors at E85Meadowlands Drive #5o9, Ottawa, Ontsrio X2C 3N2, Canada, m via Internet to [email protected] formats for figuresare Mac or DOS EP5,TfF,or GIF formats,Always send a paper copy of your manusaipt, including camem-ready copiesof your figures (laseroutput is fine).

P05TMA5TEFt Send domestic address changes and subscription orders tmllw Smalltalk Report, P.O.Box 5050, Brentwoad,TN 37024 -5050. For service on current domestic subscriptions call 1.000.361.1279 or fax 615.370.4645. [email protected] foreignsubscription orcers and inquiries phone +44[0)1 E5E.435302. PRINTED IN THE UNITED STATES.

July-August1995 1

Page 2: Smalltalk Volume 4 Issue 9 - ESUG

John Pugh Paul White

2

BEFORE WE TM ABOUTTHETOPICon every Small-talker’s mind these days, the ParcPlace-Digitalkmerger, we would like to give a warm welcome to

Ralph Johnson and Bob Hirdde, our new columnists.Ralph and Bob will be taking us “Deep in the Heart ofSmalltalk,” a column for Smalltalk afficianados whowant to learn more of the inner workings of parts ofthe Smalltalk system where few people dare to tread.

As most of you are surely aware by now, Digitalkand ParcPlace have merged to form a new companythat, at least for now, will be

them? Wdl one beother a more desold as providingstresses cross-plathere will be onlying ones, or somthat leave their co

Beyond the laare other issues. Wing tool (which

known as ParcPlace-Digitalk Inc. Probably the mostThis obviously represents amajor shift of power in the commonly asked questionSmalltalk market. Although it has been “will therecertainly doesn’t match theworld significance of many of the continue to be twomajor takeovers and mergersthat have been occurring in the separate Smalltalks?”software industry such- as theIBM/Lotus buyout, it does leave those of us in thesoftware development trenches scratching our collec-tive heads.

Although it came as quite a surprise to many(including us), it would be hard to not admit that thewriting was on the wall. There were telltale signs suchas Digitalk not joining the new Smalltalk IndustryCouncil (STIC) and deciding not to have their devel-opers conference this year. And there certainly weremany rumours that Digitalk was a takeover target,although names such as Microsoft and HP were farmore commonly referenced as suitors than ParcPlace.

This merger leaves some obvious questions. Similarto the IBM/Lotus deal, Digitalk and ParcPlace appearto have quite different corporate cultures, with differ-ent philosophies with respect to engineering, cus-tomer support, product development, and marketing.Moreover, their two products represent quite differentimplementations of the Smalltalk language, Althoughtheir base class libraries are very similar, most of thefacilities that allow Smalltalk to communicate withthe outside world are implemented in quite differentways. The user interface architectures, for example,are quite different.

Probably the most commonly asked question hasbeen “will there continue to be two separate Smdl-talks?” But no matter what the answer is to this ques-tion, many other questions remain. If there are two sep-arate products, how will they differentiate between

what are the imsuch as WindowBetc? Both companuine desire to brproducts; where

Having listed sshould be quick tous positives to ththe bringing togetthe programmingSmalhalk world,panies has neverate synergy fromimmense. Eachparts of the cliepuzzle that theopportunity to buformidable comp

The new comvision for theDevelopers ConfeI’m sure it will proious corporate cltheir developmentmove opens upcommunity We cand wish good luorganizations.

Enjoy the issue

come the “low-end product and theluxe version? Or will one product betight host integration where the othertform portability? If they do decideone product, will it be one of the exist-ething brand new? And where doesllective installed base of customers?nguage and platform facilities there

ill Digitalk’s Team/V team programm-ironically was originally designed to

run in the ParcPlace environ-ment) become the standard forboth Smalltalks, or will ENVYremain the configuration man-

agement tool of choice forParcPlace and many Digitalkusers? This is a significant issuefor existing clients, becauseswitching from one facility to theother is ;O simple task. Similarly,

plications for third-party productsuilder, Repertoire, Object Explorer,

ies have separately expressed a gen-ing VARS on board to support theirdoes this merger leave them?o many questions to be answered, weo point out that there are some obvi-e merger. The most tangible benefit isher of some of the very best minds in

language business, let alone theThe engineering talents of both com-been in doubt, and if they can gener-

this merger, the opportunities arecompany has solutions for difficultnt/sewer application developmentother lacks. Together, they have theild a product line that is an even moreetitor in the client/server arena.pany has promised to present theirfuture at their upcoming (joint!)rence in San Jose at the end of July,ve to be a lively event, with many anx-ients wanting to know the future of

tool, Only time will tell whether thisnew opportunities for the Smalltalkertainly wish this new endeavour well,ck to our many friends at both these

!

The Smalltalk Report

Page 3: Smalltalk Volume 4 Issue 9 - ESUG

Introducing ArgosThe only end-to-end objectdevelopmentand deploymentsolution

An integratedobjeetmodelingtoolprovidesmodel-driven&wel@m71tforenwprise--ldapplications [

AUobjectTTU&lSare rmmagd in a sharedreposiu~,supportingteam dfwekspment and traceabdi~

I

‘--E4160 .“ +120 .7..iT..9—------00

w30” Q

~[.....IT

description:IBMnarnn alphat+mwnumh3r0fP.tm.s: 1.

~. . . . . . .r..—.,—..!._.....-... . ............

- Pcnue+ddragand drop “enzymes” make application&[email protected]

Compreksiw setofwk!gets,incl* huinessgraphs, mukimh, and othersmakeapphcatkm Adevhpment emyad powafd

VERSANT ArgosTh’ is the only application developmentenvironment (ADE) that makes it easy to build and deploypowerful, enterprise-wide object applications. Easy becauseArgos features an embedded modeling tool and Small talkcode generation that ensure synchronization between yourmodels and applications. Powet%d because Argos supportsfill traceability and workgroup development through ashared repository.

Argos automatically generates multi-user database applicationsthat run on the industry-leading VHLSXNT ODBMS. Argosdeals with critical issues such as locking and concurrency

VERSANTThe Database For Objects TM

I Pamda 1- 1% If I -.., - mll

control transparently. And only Argos is packaged as acompletely visual ADE built on ParcPlace VisualWorks=.

Leading organizations — in industries from telecommunicationsto finance — are using Argos to deliver business-criticalapplications. Find out how Argos can help you deliver yourcritical applications in weeks, instead of years.

1380 WNOWRoad ● Menlo Park, CA 94025 ● (415) 329-7500

01994 byVcmnt Obcu TLvhIInl.gy.VE1l.SAS’~,\W1.SiiNl’ ?.rgmandThe 11.dwc ForOhjccrsArcrrdcmark olVmvn ohjmr TcchnolqqC.rpmtion. .41 mhcrcumpmynmnmd Ih,gmarcrcgkrcrd trdemmh$ol’theindi!idudcmnpniw

Page 4: Smalltalk Volume 4 Issue 9 - ESUG

Remembrance of things past:Layered architectures for Smalltalkapplications

Kyle Brown

DIDN’T YOU AIWAYS HATE IT when your fatherstarted off a sentence with “in my day...?” I know

that it always irritated me, and as an adolescent Iswore that I would never succumb to the temptation tostart a sentence that way myself. Well, teenage oaths notwithstanding, I’m going to do it anyway.

When I first learned Smalltalk, a little over six yearsago, I was taught by my mentor SarnAdams that Smalltalkapplications are built in layers (see Fig. 1). Having comefrom an engineering background where I was stronglyinfluenced by the layered architecture of the 0S1 seven-layer communication model, this seemed only fitting andproper. Layered architectures promote good softwaredesign by separating concerns of one layer from another,reducing the complexity of the application of a whole,and encourage reuse both within the elements of a layer,and between layers (for a discussion of layered architec-tures in computer networks, see Tannenbauml).

SMALLTALK APPLICATION LAYERSThe four layers that I was taught comprise a goodSmalltalk application are:1, The GUI layer. This is the layer where the physicalwindow and widget objects live. Any new user interfacewidgets developed for this application (an activity thatseems to have been more common several years ago thantoday) would also be put in this layer. In almost all casestoday, this layer is completely generated by a window-builder tool.2. The Mediator layer. This layer is partially generated bythe window-builder and partially coded by the developer.The primary classes of this layer have been variouslycalled “ViewManagers” or “ApplicationCoordinators” inDigitalk’s Smalltalk products, and “ApplicationModels” inParcplace’s products. This layer mediates between thevarious user interface components on a GUI screen andtmnslates the messages that they understand into mes-sages understood by the objects in the domain model.3. The domain model layer, This is where the real “meat”of the application resides, An object-oriented analysisand design should result in a set of classes that primarilyreside in this layer. Examples of the type of objects in thislayer would include Orders,Employees, Sensors, or whatev-er is appropriate to your problem domain.

4

4. The infrastructure layer. This is where the objects thatrepresent connections to entities outside the object worldreside. Examples of objects from this layer includeSQLTables,3270Tenninals, SerialPorts, and the like.

Now that you’ve seen the description of these architec-tural layers, you might be saying to yourself, “Well, ofcourse; I always build my applications like that.” If so, therest of this article might seem familiar to you. On theother hand, if you’re scratching your head and going “Butwhy... ” or, even worse, smacking your forehead anddeclaring “Why didn’t I see that!” then please read on. Iassure you your projects will benefit.

Something that stood out to me during the recentSmalltalk Solutions conference is how rarely noviceSmalltalk programmers see their applications as dividedinto layers. I believe that this is a result of the wonderfulnew tools that the Smalltalk vendors have provided to usover the past few years.

Back in the old days, Smalltalk programmers would lov-ingly handcraft each of their classes one at a time. You don’treally gain an appreciation of how difficult it is to build anew graphics class or a database framework until you’vecoded one yourself. However, in the modern point-and-click world, building a complex order-entry screen seemsas simple as drawing the GUI using your window-builderof choice, telling it to generate the resulting Smdltalk class-es, then hooking those classes into the database by usingthe vendor-supplied database connectivity classes.

While the new tools have vastly increased our produc-tivity as programmers, it has become easy to lose sight ofthe bigger picture. While it is possible to completely codean application without ever creating a new class of yourown, it is not necessarily desirable. Part of the appeal ofobject-oriented programming is the ability to createreusable classes that represent your problem domain. Inthat way a month or a year from now when you (or some-one else in your organization) is getting ready to work onthe next application, you can pull those classes off the shelfand use them as is, or specialize them through subclassing.It is this reusability that gives O-O programmers the pro-ductivity advantage over their 3GL programmer peers.

Let’s say you’ve just coded an order-entry screen theway I described above (see Fig. 2). Six months later yourcustomer comes up to you and says “I’ve decided that I

The Smalltalk Reporl

Page 5: Smalltalk Volume 4 Issue 9 - ESUG

F@h

CodeQuality

Low

Maximize Reuse

Many things are needed to have reusable software.However, if developers cannot understandavailable software, it is not going to be reused.

Reusable Reusable software requires readily available, highComponent

QQ

quality documentation.

And the easiest way for Smalltalk developers to getNon-reusable quality documentation is with Synopsis. Install itComponents and see immediate results!

Features of Synopsis

. Documents Classes AutomaticallyLow

DocumentationKm

. Builds Class or Subsystem Encyclopedias

Quality . Moves Documentation to Word Processors

+ Packages Encyclopedias as Help Files

Products

mSynopsis for IBM Smalltalk $295 Team $395 -

8912 Oxbridge Court, Suite 300, Raleigh NC 27613 Synopsis for Smalltalk/V and Team/v $295Phone 919-647-2221 Fax 919-676-7501 Synopsis for ENVY/Developer for Smalltalk/V $395

don’t like this GUI you’ve built I want a drag-and-dropinterface, Oh, and by the way, we’re changing from arelational database to an ODBMS next week. Can I havethe changes by Friday?” At this point you might be tear-ing out your hair and considering looking into a promis-ing new career in food service. Or, if you had insteadcoded your application into layers, you could be takingit all in stride, saying “OK, first I’ll have to redraw theGUI; tiat’11 only take a little while; then I can start think-ing about the rest of the problem.”

RULES FOR PROPERLAYERINGSo, now that I’ve convinced you that layering your appli-

I Domain Model layer IInfrastructure layer

F. —– . -—––, ,. –,, ,.––.. – ,

rlgure I. 3mamalK appllcarlon layers.

July-Au#just1995

cation is a good idea, how do you actually go about it? AtKSC we believe that applications are like sandwiches, Wefollow the approach of building a Smalltalk applicationinside out we begin with the hamburger and work ourway out to the bun.

The primary focus of your effort in a non-trivialSmalltalk application should be in defining what domainobjects you have, then building and testing them. We havefound that if you begin with a statement of what yourproblem is, and then develop an O-O model using abehavioral OOA&D methodology you can usually get agood handle on the domain layer of your system. Forinstance, if you are building an order management and

-. +.... ,., ,rlgure 2. tvmssmg aomaln moael.

5

Page 6: Smalltalk Volume 4 Issue 9 - ESUG

I LAYEREDARCHITECTURES

inventory system, you might discover objects like Order,Warehouse, and Goodand investigate how they interact witheach other. You can then proceed from a design model tobuilding a prototype of these objects. The key here is todiscover how the objects interact, and how you can takeadvantage of the paradigm to make your objects moreunderstandable and reusable. The domain layer should bedeveloped, as much as possible, without undue consider-ation as to how the database will be implemented, or howthe GUIS w-illlook. While these considerations are impor-tant to the application as a whole, they should not beallowed to “pollute” the purity of your object model.

After you have built and tested your prototype objectmodel, you can then begin to work your way out to thelayers surrounding the domain model in Figure 1. Let’sbegin by looking at the development of theApplicationModellayer. As I stated earlier, this layer shouldbe primarily for mediating between the different ele-ments on your GUI, and translating messages from theGUI into messages understood

other. It should notties of either, but ma

In general, yourdumb, and small. Byan ApplicationModelfat), the methods thlate and mediate, raand that the Applicahave little state, or feRemember that theface to the world thyour application. Restate of the applicatio

A common examMediator layer and dovalidation of valuesdesigners will immedthe mediator layerquences that decision

by your domain model. It shouldJust remember to considerfollow the intents of the

Mediator pattern and the the implications of each designAdapter pattern from Gamma.2

In a nutshell, a Mediator is an decision to determineobject that “encapsulates how a

if it violates proper layering...set of objects interact.”2~ P-273An example of this kind of medi-ation is that an ApplicationModel may disable a set of but-tons or menu items based upon the state of other buttonsor menu items, The ApplicationModel keeps these widgetsfrom knowing about each other, and promotes good fac-toring of the design. It doesn’t make much sense toinvolve the domain layer in these, purely user-interfaceactions, so the Mediator also insulates the two from eachother.

An Adapter“converts the interface of a class into anoth-er interface clients expect.”2~ P-139 GUI Widgets have oneinterface that they respond to-they are concerned withthe state of their selection, what they are displaying, etc.On the other hand, the domain model is concerned witha different sort of interfac%it is concerned with the stateof Orders, or how Employees are related, etc. AnApplicationModel should adapt the one interface to the

Infrastructure layer

r .—‘Q~B~ke~s T–––––––lI I

Communications IBrokers

I SQL Classes 1 Communications IClasses

I I I——— ——— ——— ——— ——

Figure 3. Infrastructure microlayering.

other hand, the GUIthe validation this wincorrect value is enbeing accepted. Thewell-defined path ofthe responsibility all

Another examplebility between the Min the representationresults in a calculationdisplay the line itemcosts, should the caApplicationModelclassitems? While you cApplicationModel,it wOrderitself to do thiscost would be availsuch as a paper reporders, Following thedistribution of respreusable objects.*

Finally let’s takeend; between the doof your application.by now that it is an a

* Wirfs-Brock3 containsdistributed behavior.

6

attempt to take over the responsibili-ke their communication smooth.

ApplicationModels should be thin,these characterizations I mean that

should have few methods (thin vs.emselves should serve only to trans-ther than control (dumb vs. smart),tionModel objects themselves shouldw instance variables (small vs. large).task of a GUI should be to present aat reflects the state of the objects insist the temptation to represent then in the GUI itself.ple of cooperation between themain model objects would be in theentered into a GUI. Many novice

iately code all validation logic into, without considering the conse-

makes. If the information that youwant to validate is held in anobject in the domain model,does it really make sense for the

‘angechecksand‘tier ‘alida-tions to be made in differentobject in another layer? The prin-ciple of encapsulation indicatesthat the behavior should accom-pany the information. On the

must represent the visual aspects ofould include warning the user if antered or preventing the value fromtwo objects should cooperate along acommunication rather than stuffingin one objector the other,of improper distribution of responsi-ediator layer and the domain model is

of calculations, or intermediate. If your application calls for you to

s in an order, and the sum of theirlculation of that sum reside in the, or in the Orderthat contains the linean code the calculation into theould be more reasonable to allow thecalculation. In that way, the summedable to other presentation options;ort, or a summary report of manyse rules leads to objects with a betteronsibilities, which results in more

a look at the division on the othermain model and the infrastructureI think it’s become abundantly clearbsolute no-no for the Mediator layer

a good discussion of the benefits of well-

The Smalltalk Report

Page 7: Smalltalk Volume 4 Issue 9 - ESUG

Are you maximizingyour Smalltalkclass reuse? Now you can with...

Mlm from ARS

‘ adds multipleinheritanceto VisualWorksTMSmalitalk , ,,,~&@w ~~

● providesseamless integrationthat requiresno new syntax

● installsintoexistingimages with a simplefile-in● is writtencompletely in Smalltalk

“Y ‘+

Leading methodologies (OMT CRC, Booth, OOSE)advocate multiple inheritance to facilitate reuse. Smalltak’s/ack of multiple inheritance suppofi impedes the directapplication of these methodologies and limits class reuse. ‘T?Ml is a valuable tool which enables developers to apply ;$fj$ld~l~;;;jadvanced design techniques that maximize n?use.

~ .,,*,.;

1.&Y&AppJledReasoning Systems Corporation (ARS) Is an innovative devaJopar of highquality Smalltalk development tools, applimtion frameworks, Intelligent soflwarasystems, and relalsd servkas thatprovide advanced solutlons to oomplaxproblema.

SmaRtalk Products ● Consulting ● Education ● Mentorlng

Phons: (919) 781-7997 ● Fax (919) 781-4414E-mail: info@ arscorp.com

Introductory Price: $195To order Ml or for more informationon AIW’S family of productsandsetvices, please call 1-800-260-~ ore-mail [email protected].

to communicate directly with the infrastructure layer,but what is appropriate communication between thedomain and infrastructure layers? In general terms, thecommunication should preseme encapsulation bound-aries. A “microlayering” approach might work out best(Fig. 3). Just as novices are tempted to put all their logicin their Mediator code, an equally naive approach is to putall the database knowledge into the domain classesthemselves, or (slightly better) in their metaclasses.

A better approach to building connections betweendomain and infrastructure layers is to budd a layer of“helper” or “broker’’objects,t A “broker”* is an object thatserves as an adapter between the domain object that mustcommunicate to the outside world, and the communica-tion medium, be it a network protocol, a mail protocol likeSMTF! or a relational database, Again, the primary advan-tage here is the preservation of encapsulation; if you canencapsulate the knowledge of a protocol or interface intoone set of (reusable) objects, and provide an adapterbetween them and the domain layer, you will be better ableto change one without necessitating changes to the other.

t For an discussion of architectures for relational database interac-tion, see Vasan.4

* By “broker,” I’m not referring to a CORBA-style Object RequestBroker [ORB).A broker is anv obiect that adatxs an obiect modelto a non-object-oriented procedural interface. Broke~s must, bynecessitv, know a little about each world to bridqethe gapbetwee~ them,

July-August 1995

FINAL NOTESWhile applying a layered architecture to your applicationswilJ not be a panacea for all your software ills,”it may aUevi-ate some of the more grevious symptoms. Just remember toconsider the implications of each design decision to deter-mine if it violates proper layering or enhances the nmsabil-ity of the individual classes by supporting the architecture

AcknowledgementThe author thanks Bobby Woolf for pointing out the prop-er patterns that ApplicationModels should follow, and allhis peer reviewers at KSC for their help and advice.

References1.

2,

3.

4.

Tannenbaum, A. COMPUTER NIWWORKS,Prentice Hall,Englewood Cliffs, NJ, 1988, pp. 9-14.Garnrna, Helm, Johnson, and Vlissides. DESIGNPATTERNS:ELEMENTSOF REUSABLEOBJECT-ORIENTEDSOFTWARE,Addison-Wesley Reading, MA,1995.Wh-fs-Bock, R. Characterizing your application’s control style,SMALLTALKSOLUTIONS’95 CONFERENGFNcrrss, NewYork, 1995.Vaaan, R. Techniques for object and relational integration,OBJECTMAGAZINE3(1):52-53, 60, 1993.

Kyle Brown is a Senior Member of Technical Staff at KnowledgeSystems Corp. He has been developing industrial applications inSmalltalk for over five years. As part of his consulting practice, hehas built applications for Engineering, MIS, and scientific comput-ing. Since joining KSC, Kyle has enjoyed teaching the principles ofreuse and good O-O design to a variety of clients through the KSCSmalltalk Apprentice Program. He can be reached via email [email protected].

7

Page 8: Smalltalk Volume 4 Issue 9 - ESUG

Se~egating application anddomain

Tim Howard

THIS IS THE THIRD ARTICLE IN A SERIES of threededicated to the topic of segregating applicationinformation and domain information in

VisualWorks application development. The first articlepresented the case of why it is essential that an applica-tion have a strict segregation between its applicationinformation and its domain information. The secondarticle covered the implementation of domain objects,which are the keepers of the domain information, Thisthird article discusses the application classes, which pro-vide the user interface for the domain objects.

This article introduces what I refer to as the domain

adaptor architecture, which is a framework for buildingapplications in VisualWorks. This architecture is a spe-cialization of application model architecture and isdesigned to work specifically with domain objects. First Iwill introduce the domain adaptor, which is a special typeof application model developed for viewing and editing adomain object. Then I will discuss how domain adaptorsbind the user interface to the information in the domainobject. The full source code for the domain adaptor archi-tecture, along with examples, is available from thearchives at the University of Illinois (st.cs.uiuc.edu).

DOMAIN ADAPTORIn the second article of this series, I talked about domainobjects, the keepers of the domain information. Thesedomain objects do not exhibit model behavior nor dothey know how to present themselves in a user interface.Now what we need is a special type of application modelarchitecture that allows us to easily build applications fordisplaying and editing these domain objects. I refer tothis type of architecture as tbe domain aduptor architec-

ture because it adapts purely domain information to auser interface. At the center of the domain adaptor archi-tecture is the domain adaptor, A domain adaptor is a typeof application model that provides a user interface for adomain object and allows the user to view and edit thatdomain object.

Each class of domain adaptor is designed for a specificclass of domain object. For example, suppose we have thedomain class EmployeeReview, which describes all theinformation for a single employee review. To view aninstance of such a class (a domain object) we might createa type of domain adaptor called EmployeeReviewULTherecan be more than one domain adaptor class for each classof domain object, but each class of domain adaptor is

8

designed specifically for only one type of domain object.As an example, we can design EmployeeReviewUI,ShortFormEmployeeReviewUI, and LongFonnEmployee-ReviewIII to operate on an EmployeeReviewobject—eachpresenting the employee review information in a differentway, Each domain adaptor operates on only one domainobject at a time. Continuing with our example, an instanceof EmployeeReviewUIwill present to the user one instanceof EmployeeReviewfor viewing and/or editing.

The domain object on which a domain adaptor oper-ates is accessed and replaced using value model proto-col—the messages value and value:. In our example, whenthe user is done filling out the employee review in theuser interface, thereby populating the EmployeeReviewdomain object, we can access that domain object bysending value to the EmployeeReviewUIdomain adaptor.We can then place this domain object in a database, addit to a collection of such reviews, etc. When the user isready to read or edit the next employee review, we simplysend value: anEmployeeReview to the EmployeeReviewUIdomain adaptor. The domain adaptor then automaticallypopulates its user interface with the information in thenew domain object.

Because each type of domain adaptor is designed for aspecific type of domain object, it knows how to create anew instance of that type of domain object in the eventthat one is not provided at the time the user interface isopened. In the employee review example, the code:

EmployeeReviewUIopen

will open a window on a new instance of EmployeeReview,because one is not initially provided. If we already had apopulated instance of EmployeeReview,we would open aninterface on it with the following:

EmployeeReviewUIopenOn: anEmployeeReview.

The abstract implementation for all domain adaptors isdefined in DomainAdaptor:.DomainAdaptoris a subclass ofExtemaLApplicationModeland defines two instance vari-ables: domainChannel and domainIsChanging.

Because the superclass ExtendedApplicationModell is asubclass of ApplicationModel, all domain adaptors areapplication models and, therefore, define and operateuser interfaces. Furthermore, all domain adaptor classesinherit the development features defined inExtendedApplicationModel. The domainChannel instancevariable is a ValueHolder that references the current

The Smalltalk Report

Page 9: Smalltalk Volume 4 Issue 9 - ESUG

Oddly enough, a company with possibly the largestand most deployable Smalltalk/00 worldorce is

virtually unknown - Until Now.

● On-Sik SrnaUtall@O Pmgmmmg“ &Mentming ● GUI Front-EndDesign/Buildto kgacy Systems● On$ite CusmrnizedSrnaUtaIivOOTraining ● object Mcdelirtg,Analysis& Design● 00DBMS Dcvelcptnem 0bjeci5mre, Gernmne & Versant ● SmaUdl@bject Mq@ng to Sybasc,Oracle & DB2

❑✎✎✌:}. Call (800) 789-6595w Him [email protected].

Object/nte///gence CorporcrHon ● 9W Ridgefield Dr., Ste, 240 ● Ralelgh, NC 27609 ● (91 9)878-6695 Fax

domain object, The domainIsChanging instance variable isa Boolean that is true when a change of domain is inprogress. The DomainAdaptorclass implementation can bedivided into three parts: domain object management,aspect support protocol, and interface opening protocol.Domain object management involves managing thedomah object itself, The aspect support protocol is a setof methods that allow you to easily set up aspect modelsthat operate on the information in the domain object. Theinterface opening protocol is an extension of the interfaceopening protocol defined in ExtendedApplicationModel,which allows a domain adaptor to be opened and initial-ized to an existing domain object in a variety of ways.

&& dmnainintbmration

Figure 1,Application model object diagram.

July-August 1995

In the first article of this series, I presented an objectdiagram of an application model. For convenience, thisdiagram is provided again in Figure 1. Figure 2 is theobject diagram for a domain adaptor. Notice that inFigure 1 the domain information is logically related viathe application model. In Figure 2, however, the domaninformation is logically related via the domain object,Thus the domain information can be easily uncoupledfrom the application information and placed in a data-base, Likewise, another domain object, of the same type

applkatin

inh7m7ati0n

xdomain

object

integer string

Figure 2. Domain adaptor object diagram.

9

Page 10: Smalltalk Volume 4 Issue 9 - ESUG

I SEGREGATINGAPPLICATION8 DOMAIN

can be retreived from the database and plugged back intothe domain adaptor. Accessing the domain object andinserting a new domain obejct is as easy as sending themessages value and value:, respectively.

ADAPTING THE DOMAIN INFORMATIONIn designing a domain adaptor, our main goal is to defineaspect models that operate on the various aspects ofinformation in the domain object. When the variousinterface components bind with these aspect models, theresult is a user interface that views and edits the informa-tion in the domain object.

In the second article of this series, I categorized thedomti information into atomic objects (such as num-bers, strings, and dates), collections, and other domainobjects. Consider an Applicant domain object used todescribe someone applying for a job and having the fol-lowing instance variables:

Variable Typename stringssn stringreferences SortedCollechon of Stringsaddress Address

The Applicant domain object references objects of each ofthe three categories of domain information. The name andssn instance variables are atomic in nature. The referencesinstance variable is a collection. The address instance vari-able references yet another domain object, an Addressobject, whose instance variables are defined as follows.

Variable Typesheet string

aty string

state string

zip string

An object diagram for the Applicant domain object isshown in Figure 3.

To provide a user interface for viewing and editing anApplicant object, we need a special type of domain adap-tov therefore, we define the class ApplicantUI as a subclass

c3D-”+ci2kll,w-=

dTiiiD

addrasm

8sreal

~ dk . .

w ‘“”6atrlng

Figure 3. Applicant object diagram,

10

of DomainAdaptor.Each class of domain adaptor needs toimplement the domahCLassinstance method, which indi-cates the type of domain object for which the domainadaptor is designed. In our example, we would define thefollowing in the protocol “domain accessing”:

dontain(lass‘Applicant

We can also draw the user interface as is shown in Figure4. The address portion of the user interface is not explicit-ly drawn in this canvas but is actually a subcanvas, as willbe demonstrated shortly.

Now we need to define aspect methods for our domainadaptor which bind the information in the domain objectto the various components in the user interface, First wewill consider the atomic object%sn-ings, dates, integers,floats, and Booleans. Such information is usually present-ed to the user using input fields, text editors, check boxes,and radio buttons. VisualWorks already provides a mecha-nism, the AspectAdaptor,by which we can adapt a domainobject’s atomic information such that it can be displayedby these interface components. An AspectAdaptoris a valuemodel whose value actually belongs to some otherobject—in our case, the domain object. When severalAspectAdaptorobjects operate on the same domain object,it is convenient to keep that doman object in aValueHolder.Fortunately each domain adaptor has such a ValueHolder,its domahsChannelinstance variable. Because setting up anAspectAdaptor can be somewhat complicated, theDomahAdaptor class defines certain aspect support meth-ods to set up the AspectAdaptor for us. In the applicantexample, we need an AspectAdaptorfor both the name andssn attibutes of the domain object, Therefore, in the

!ame: Skills

iSN:

n)

street:

City:

Zip:

Figure 4. ApplicantUl user interface.

The Smalltalk Repott

Page 11: Smalltalk Volume 4 Issue 9 - ESUG

“aspects” protocol of the ApplicationUI class we define thefollowing two methods:

name‘self aspectAdaptorFor: #name

ssn‘self aspectAdaptorFo~ #ssn

Notice how simple these methods are. The methodaspecU@torFo~ a$mbol is defined in DomainAdaptorand itautomatically sets up an AspectAdaptor for the domainobject instance variable named by a$nnbol. The domainadaptor’s domahthannel instance variable is used as tbesubject channel for the AspectAdaptorso that whenever tbedomain object in domainllmnnel is replaced with another,the AspectAdaptoris automatically switched over to the newdomain object, and, furthermore, the corresponding inter-face component is updated with the new information. Auseful variation of the aspectAdaptorFor method is theaspecWaptorFor:changeMessage method, which will set upthe AspectAdaptorsuch that whenever its value is changed,a change message is dispatched to the application model.

The AspectAdaptorworks very well for the atomic typeinformation, but what about the collections contahed byour domain objects? Collections are typically presented tothe user in list components. For example, we want to dis-play the applicant’s skills in a list component and alsoallow the user to add and remove skills. What we need is acollection version of the Aspect4daptor. We need some-thing that will allow a domain adaptor not only to displaya domain object’s collection in a list component, but alsopermit the user to add and remove elements from thatcollection, Furthermore, when the current domain objectis replaced, this new type of adaptor must switch its focusto the collection in the new domti object and have thelist component redraw itself with the new information.For this purpose, I have created the CollecdonAdaptorclass.DomainAdaptordefines aspect support protocol for settingup a CollectionAdaptor. For example, to have ourApplicantUI show the skills of an applicant, we would addthe following method to “aspects” protocol of ApplicantUI:

skills

‘selfcollectionAdaptorFor:collection: #skills

We can now easily adapt the

#skills

atomic objects and collec-tions in our domain objects to the user interface managedby the domain adaptor. But what about domain objectsthat contain other domti objects? In ow example, ourApplicant object holds on to an Address object-which isitself a domain object. Do we have an adaptor for it?Yes, itscalled a domain adaptor! What kind of interface compo-nent do we use to display an Address object? A subcanvasmanaged by an Ad&essUI domain adaptor! The domainadaptor architecture is fully recursive. Furthermore, all

July-Au@st 1995

three types of adaptors operate on value model protocol.The messages value and value: access the domain informa-tion from the adaptor whether that information is atomic,a collection, or another domain object. In the applicantexample, we would add the following method to the“aspects” protocol of ApplicantUI:

address‘self domainAdaptorFoc #address modek AddressUI

This method automatically instantiates a domain adaptorof the type AddresslJI, This AddressUIdomain adaptor willoperate on the Address object contained by our Applicantobject and display that Address object in a subcanvas.AddressUI is just another domain adaptor originally

Street:

City:

Zip:

Fiaure 5.AddressUl user interface.

11

Page 12: Smalltalk Volume 4 Issue 9 - ESUG

I Database Solution ~I ~~.~n for Smalltdk II ~~~~~ A class library for ODBC I

IDatabase Access I

I . ODBC 2.x support for 50+databases■ PARTS Workbench visual &velopment components I

I■ Native ODBC data type support■ Online documentation, source included, no mntime fees I

I. programming examples and sample application.00 to RDBMS mapping f%unework,baaed on types & I

Ibrokers? ideal for complex client-server applications

I comptible with OTI’S ENVY/Developer I

Iversions Available for Windows, Windows-NT II 0S/2, VisualAge and Visual Smalltallc/E

“simple but elegant ...” - Australian Gilt Securities I

I 11 Also available:I So&talkClient Server Sol&on for SmaUtalk/V

A Windows Sockets Class LibraryI

designed as a window interface for an Address object, asshown in Figure 5.

It is important to emphasize that we are using anotherdomain adaptor, developed completely independently ofApplicantUI and Applicant objects, but that can be easilyincorporated into the ApplicantUI domain adaptor. Thisallows us to take either a bottom-up or top-downapproach to building user interfaces for our domainobjects. It also facilitates reuse because an AddressUI canbe used independently or incorporated into several otherapplications requiring an address. As domain objects

Table 1. Adapting interface components to domain information.

Domain Interface Model AdaptorInformation ComponentType

Wing, Number, Input Field AspectAdaptorDate

Text Text Editor AspectAdaptor

Symbol Radio Buttons AspectAdaptor

Boolean Check Box AspectAdaptor

OrderedColledon List CollectionAdaptorSortedCollection

DomainObject Subcanvas DomainAdaptor

DomainObject Window DomainAdaptor

12

become aggregations of other domain objects, their cor-responding domain adaptors are just mirror aggrega-tions of other domain adaptors. In this way domain adap-tors can be designed for even the most complicateddomain objects.

I would like to point out that all the aspect support pro-tocol in DomainAdaptoris defined in such a way that ouraspect models do not need corresponding instance vari-ables defined in the domain adaptor class. This providesfor a much cleaner class definition (see “Extending theApplication Model”). For a complete list of the aspect sup-port protocol and how it is used, browse the classDomainAdaptor.

Table 1 summarizes the types of domain information,the corresponding interface component used to displaythat information, and the adaptor used to connect thedomain information to the interface component.

SUMMARYThis article introduced the domain adaptor architecture,which is a framework for building VisualWorks applica-tions based on domain objects and a strict segregation ofapplication and domain information. The centerpiece ofthe domain adaptor architecture is the domain adaptor—an application model that knows how to operate on adomain object. The domain adaptor keeps its domainobject in a ValuHolder referred to as the domain channel.Each time the domain object is replaced by a new domainobject, the domain adaptor updates its interface with thenew information. A domain adaptor uses model adaptorsto bind information in its domain object to the interfacecomponents. h AspectAdaptorbinds simple informationto input fields, check boxes, and radio buttons. ACollectionAdaptor binds collections to list components.Domain adaptors are themselves model adaptors andbind contained domain objects to subcanvases, There is agreat deal more to the domain adaptor architecture thancan be presented in a single article. Not covered are suchtopics as the role of dialogs, the interface opening proto-col, chdd windows, buffered adaptors, and strategies andguidelines. If you program in VisualWorks, I stonglyencourage you to obtain the source code and work theexamples. After only a few hours of exploration, the mer-its of this approach to VisualWorks application develop-ment will be quite evident. The full source code for thedomain adaptor architecture framework and examplesare available from the archives at the University of Illinois(st.cs.uiuc.edu),

Reference1. Howard, T. and B. Kohl. Extending the application model, THE

SMALLTALKRF.PORT3(7):1, 4-7, 1994.

Tim Howard is the President and cofounder of FH Protocol, Inc.He is interested application development using O-O technolo-gies in general, and using the language of Smalltalk in particular.He can be reached at [email protected] or by phone at214,931.5319.

lhe Smalltalk Report

Page 13: Smalltalk Volume 4 Issue 9 - ESUG

Acasestudyinmakingcodereusable

SOMETIMES YOU CAN TELL at the start of a projectthat your code must be reusable. But more often,you don’t realize that something needs to be

reusable unti you try to reuse it, and you end up uying toadd reusability to existing code. This is not easy, becausereusability is a result of the design of a system, not just theresult of some coding tricks. So, making code reusableoften requires changing its design significantly.

Recently we needed to reuse theVisualWorks compiler toimplement a new breakpoint mechanism. Unfortunately,the compiler was not designed to be reused the way wewanted. As a result, we had to rewrite it to be more para-meterizable and easier to customize.

This column exposes some of the more arcane innerworkings of Smalltallc, and shows why it is both useful andpowerful to allow programmers reflective access to theseparts of the system. It also shows several common tech-niques for making Smalltalk programs more reusable. Thesolution described here is based on VisualWorks Version2.o, although it can be adapted to previous versions ofSmalltalk-80.

THE PROBLEMOur previous articlel described how to debug the behav-ior of individual objects using lightweight classes. Tomake debugging easier, and as something of a side pro-ject, we also introduced breakpoints, a common featureof modern programming environments that had so farbeen represented in Smalltalk-80 only by its poor cousin,the halt message. While the breakpoints we introducedhad several benefits over self halt—notably their indepen-dence from the Change hat and their ease of addition andremoval-they also had several limitations. In particular,

Bob Hinkle is an independent Smalltalk consultant and writer. Hiscurrent focus is the improvement of existing tools and the cre-ation of new tools to revitalize the Smalltalk environment. He canbe reached at hinkle@primenet, corn. Ralph Johnson learnedSmalltalk from the Blue Book in 1984. He wrote his first Smalltalkprogram in the fall of 1985 when he taught his first course onobject-oriented programming and design. He has been a fan ofSmalltalk ever since. He is the only author of DESIGN PAITERNS:ELEMENTS OF REUSABLE OSJECr-ORIEtWED SOWWARE to regularly pro-gram in Smalltal~ and continues to teach courses on object-ori-ented programming and desicmat the Universityof Illinois.

July-August 1995

the breakpoints could only be set at the ve~ beginning ofa method, and they were unconditional. We want toimplement breakpoints that can exist between any twostatements in any block and that can be either absolute orconditional. Conditional breakpoints stop execution onlyif some expression evaluates to true. This expression is ageneral block of Smalltalk code evaluated in the context ofthe breakpointed method, allowing access to method andblock parameters and temporaries.

These new requirements force changes to our previousimplementation. Because breakpoints can be conditional,we must be able to insert an arbitrary block of code any-where breakpoints are allowed, and provide an interfacefor users to enter and edit breakpoint condition strings.Because breakpoints can occur in the middle of a method,we need a more general mechanism for installing brealc-point code. We used to wrap a new breakpoint methodaround the unchanged original method, but now we mustinsert breakpoint code in the body of the breakpointedmethod, Furthermore, the code we insert must not onlywork correctly but also respect the source code map, sothat stepping through breakpointed methods in the debug-ger works as the user expects. Finally because breakpointscan occur within a method, their position must be indicat-ed graphically in a method’s source. Combined with ourcontinued desire to insert breakpoints without affectingthe ChangeI@ this implies the need for two levels of sourcecode for breakpointed methods one to display in browsers,and the other to store to and retrieve from disk.

While the current compiler, comprising Compiler,Parser, and their co-workers, is very powerful, we have toextend it significantly to overcome these various difficul-ties. We need to change the compilation process, so wecan insert our breakpoint code into the method’s bodyand produce methods with distinct display and storedsource texts. Extending an existing component this way isa typical step in system building, and many of the tech-niques for implementing design and redesign are equallytypical, falling into previously identified patterns (seeGammaz for a catalog of common patterns in the object-oriented world). We’ll apply patterns called Factory-Method, Strategy, and Visitor, as well as a program refac-toring technique we call Trail Splitting.

13

Page 14: Smalltalk Volume 4 Issue 9 - ESUG

I DEEPIN THE HEARTOF SMALLTALK

THE SMALLTALKCOMPILER #methodClass andBecause most of the changes in this project center around tion, instancesthe process of compiling code to produce new methods, MethodNodeHoldewe will examine how the compilation process currently #newCodeStieam,works to see how it can be extended. The current process These implementainvolves six major steps: called FactoryMet

1.2.

3.

4.

5.

6.

The user selects accept in the TesitViewof a Browser.The Browser passes its current text to the currentlyselected class using the message #compile: classified,which forwards to ClassDescription>>compile: classi-fied:notifying:.The class creates a new Compiler—the new compiler’sclass is actually defined in the class method#compilerClass, but this always returns Compiler-and

either to specify anew instance. Eitridden in subclassenew kinds of colla

Wile quite flextions. ProgramNodPattern:ifFailmeedSalways produce su

passesthe source text using themessage #compile: in:no~g:ifhik, It is both usefil and powerfuThe Compiler initializes itself to allow programmersand eventually calls themethod that does the work, reflective access to {the inne#hnslate:noPattem:ifFailmeed-SourceMap:handler:. workings] of the system.

(a) The Compiler creates aParser,which it uses to cre-ate a parse tree from the source text. The Parserworks with a ProgramNodeBuilderto create this tree,which consists of instances of the various sub-classes of ProgramNode.

(b)The compiler creates a new CodeSheam and tellsthe root of the parse Uee, using the #emitEffect:message, to generate byte codes into theCodeStream. The name scope for variables in theparse tree is resolved using a subinstance ofNameScopecreated by the compiler.

(c) The resulting CompiledMethodis packaged into aMethodNodeHolder, which is returned as theresult.

The Class obtains a CompiledMethod from theMethodNodeHolder using the message #generate(which is currently trivial, returning theCompiledMethodfrom step 4(c)).The Classupdates the Change Set, writes the sourcetext out to the Change List, sets the CompiledMethod’ssourcePointer, and adds the new method to itsMethodDitionay.

Most of the work is done in step 4. Each substep of 4 is amajor production point, a place where an importantobject is produced and returned to be used in the nextstep. Step 4(a) creates the parse tree, step 4(b) creates thebyte code stmarn, and step 4(c) creates the method itself.Nine classes of objects are instantiated in steps 4(a)through 4(c) (counting parse we nodes as subinstances ofProgramNode),and there is much built-in flexibility in theprocess. The compiler’s and the parser’s classes arespecified in #compilerClass and #preferredParserClass,respectively, Furthermore, new methods and blocks areinstantiated in CodeStream using the messages

will be stored in innew kinds of collabthese variables to ntion as a productiowith the three prodmay wish to transfoduction line to afftransform the inputhird the bytecodemethod itself. Ourduction points anfuture articles we wduction points and

REFACTORINGTHOur new compiler,mers to overridetransformation stapilation process. Ing each class of oany subset of theseizations. Also, theat each transformaclient. To supportrequires a new coles it should use anformation-stage minstance of the new

While thesemeterizedCompih2better to introduceSmalltallq as the

aggregate, is alread

14

#blockClass sent to the compiler. In addi-of CodeStream, NameScope, and

r are created by Compiler’s messages#scopeForClass:, and #newMethodHolder.tions are examples of a design patternhod, which works by using methods

class for instantiation or to produce aher way, Factory Methods can be over-s, making it relatively easy to intioduce

borators into a complex process.ible already this process has some lhnita-eBuilderis hard-coded into #hanslate:no-ourceMap:handler,and ProgramNodeBuildersbinstances of ProgramNode.More impor-

l

r

tantly while Factory Methods arehelpful, they do require subclassingto introduce new object types intothe compilation process. We willmake this process more flexible, sothat proganuners can define newbehavior at each production point,by taking advantage of the fact thatclasses are objects. The various class-es used in the compilation process

stance variables of a new ~ompiler~so thatomtors can be easily introduced by settingew values. Finally if we think of compila-n line, there are four stages intermingleduction points of step 4. At each stage, werm the object(s) flowing through the pro-

ect compilation. In the first stage we cant text, in the second the parse tree, in thesh-cam, and in the fourth the compiled

breakpoint project exploits two of the pro-d one of the intervening stages, and inill see uses for specializing the other pro-h-ansformation stages.

E SMALLTALKCOMPILERPararneterizedCompiler,allows program-

behavior at each production point andge, providing great flexibility in the com-t achieves this flexibility by parametrizi-bjects used during compilation, allowing

classes to be replaced with new special-ParameterizedCompilerlets you intervenetion stage by sending messages to itsthis flexibility the ParametedzedCompiler

laborator, who supplies it with the class-d responds (even if trivially) to tbe h-ans-

essages. This collaborator will be anclass MethodProducer.

tasks could be performed by Para-ritself, there are several reasons why it’s

a new object instead. The Compilerinentry point to the entire compilation

y a big, complex object, and adding new

lhe Smalltalk Report

Page 15: Smalltalk Volume 4 Issue 9 - ESUG

Help Designerfor Visua/Workiw

Help Designer Is not just a programmerstool - now any teammember can create high quetky on-line help. This powerfuldevelopment tool Is rich in features, provides flexible set of tools,and facMtatae the reuse of componentswlthln your applications.Here Is what you get

~ ~

@ Help Editor ● Context-sensltlve hslp* Help Viewer + Inllne and outllneIII Image Editor ● Tag Help

ill Text Editor ● Hypertext Ilnks and

m Help Manager referencesill Control Panel ● Popup definitions

● Help Custom Controls o Keyword searoh# History SUppOrt

FREE DEMO AVAILABLE 1 + Macro definitions● Access to font, paragraph,

TO ORDER CALL 212-7654S62 and cofor attributes● Embedded objscts

FAX REQUEST 212-765-5920● Run-time editing mode● Platform Independent help

files

GpGreenPoint, Inc.77 West 55 Street, Suite 110New Yoti, NY 10019EMail:75070.3353 @CompuServe.com

Iiuulwti is n IIdmwk 0rPwPk4 SW-

responsibilities only makes it bigger and more complexThis makes it diffm.dt to understand in its own right, andalso difficult to extend with new interventions, because theprogrammer must determine which methods and interac-tions have to do with the core job of compiling and whichare designed to be specialized. Specialization becomes eas-ier when the methods intended to be overridden are con-centratedwithin tie locus of a single object. This is an appli-cation of the Strategy pattern, which bundles algorithms indifferent objects, allowing them to be varied independentlyfrom their clients. Thus, different kinds of Behaviors canexploit this flexibility to create theh own compilation algo-rithms, by simply defining an extension of MethodProducerthat introduces new kinds of collaborators or new respons-es to Wmsformation-stage messages, For example, thelightweight classes of our previous articlel only need tointroduce a new kind of method that stores its source textlocally Supporting breakpoints requhes an altered parserand a new method class, as well as manipulation of theparse tree in the second transformation stage. In a futureproject to add active variables, we’ll use a MethodProducerwith a specialized parser, a new ProgramNodeBuilderthatprovides anew kind of RograrnNode,and anew extension ofNameScope.Each of these examples can be handled by aslightly modified MethodProducerthat, by interacting differ-ently with ParametetiCompih2r, specializes compilation tosuit each particular kind of Behavior.

The class definitions for these two new cooperativeclasses are as follows:

Object subclass: #MethodProducerinstanceVariableNames: ‘client’cl.assVariableNames:“poolllifionaries: “catego~ ‘Parametrized Compiler’

SmalltalkCompiler subclass: #ParameterizedCompilerimtanceVariableNernes: ‘producer parsertlass

builderClasscodeSheamClass nameScopeClass methodClassblock(lass holderClass’

classVariableNames: “poolllictionaries:”categogc ‘Parametrized Compiler’

Every class responds to the message #methodProducer byreturning the default MethodProducer for building theclass’ methods, just as they now define their default com-piler class. This class-specific MethodProducer is responsi-ble for creating anew compiler, and, if necessary for ini-tializing the instance variables that specify what classesare used during compilation and responding to messagesfrom the compiler at each transformation stage.

MethodRoducer and ParameterizedCompiler are intro-duced into the standard compilation process by changingthe compiling messages in ClassDestiption and Behavior.We redefine the method ClassDescription>>compile:classi-fied:noMying: (mentioned in step 2 above) and add a newmethod to which it will forward

July-Au@ 1995

I ,.. . .. . . . , ..-.COmplle: COCleClaSSliIed: neadmg nomymg: requestor

‘selfcompile: codeclassified: headingnotifying: requestorproduce~ (self methodProducerFoflext code)

compile: code cl.assfied: heatig notifying: requestorproducer: producer

‘producercompile: codein: selfclassiiled: headingnotifying: requestor

The actual MethodRoducer created in the first of the twomethods above is provided by implementing two addi-tional methods in Behavior

methodproducer‘MethodProducer new client self

methodProducerFoflext: aTextOrSting‘self methodproducer

The first method instantiates a MethodProducer of a typesuitable for the class, and classes can override thismethod to use new subclasses of MethodProducer.The sec-ond method, while trivial now, lets a class use differentMethodProducers depending on the method and/or sourcecode to be compiled.

15

Page 16: Smalltalk Volume 4 Issue 9 - ESUG

HOWTOCONTACTSIGSPUBLICATIONS% submitmaterialsfor publkation@Meproposals,outlines,and manuscripts;industrynew pressk-; productannouncements;Ietiersto lhe editor+end ia~~~ PaulWhtie,Edfiors@:=lK REPORT~=nds Dfme,su~e 509_~=$2c 3~2, canada@b@~.~12 Fax:613.225,5943m~-ople.on.(a~~! j~mletant’a

& q“- andto ordera subscriptionrenew,.@i&/@ress of anexistingsubscription

~ ,,5 ‘~; >2<,,;,,,:”: ;_.

~vB: ,,,.!

16

MOVING CODE TO MethodProducerThe MethodProducer responds to #compile:in:classfied:no-g: with a method similar to the old ClassDescription>>compileclassfied:no@ing:.

compile: code in: aClass classified: aProtocolno@ing:aRequestor ifPail: aBlock

I methodNode selector method IsourceCode:= code.Cursorexecute shovWhile: [

rnethodNode:= self ntiompilercompile: codein: aClassnotifying: aRequestorHPaih aBlock.

selector:= methodNode selector.method := methodNode generate.self storeSource: code method method class: allass

selecto~ selector classified: aprotocol.atis loadMethod: method selector:

selectorclassiiied: aprotocol].‘selector

The differences between this method and the old Class-Desc@on compilation method are the the underlinedmessages. First, MethodProducer uses a Factory Method,#hewCompiler,to create the compiler it will work with. Indefault cases, this method will return a ParameterizedCompilerthat uses the same group of collaborators as Compiler,socompilation will proceed much as it used to do. For morespecialized requirements, such as breakpoints and light-weight classes, #newCompilerwill be overridden to return aParametetiedCompilerwith new kinds of collaborators.

Unlike ClassDescription>> compile: classified: notifying:,which directly added the newly compiled source code tothe Change List, MethodProducer makes a separate call tostore source, which provides an easy way for future spe-cializations to extend or override (and which will beexploited to support both lightweight class methods andbreakpoint methods). MethodPtoducer defines the source-storing message by sending #storeSource:method: selec-tor:chssified to the designated class, which responds byupdating the Change Set and Change List. Frequently, ashappens here, moving a method from one class to anoth-er requires splitting off a portion that remains in the oldclass, where it is easier to access local instance variablesand conceptually more self-contained,

Finally ClassDescriptionimplements load.lkthod:selecto~classified: by classifying the selector under the specifiedprotocol in its ClassOrganizationand then adding the newmethod to its method dictionary. As with source storing,this behavior from the old compilation message is betterperformed by the ClassDescription itself than by aMethodProduceroperating on it.

PARAMETRIZING THE COMPILERParameterizedCompiler is quite similar to its superclass,SmaM-kCompiler. It adds accessor methods to set the value

Tire Smalltalk Reporl

Page 17: Smalltalk Volume 4 Issue 9 - ESUG

ApplyingOMTA Practical Step-by-Step Guide to Using the ObjectModeling Technique

KURT DERR

[ISBN,I-SII4S42-1O-OI

$44

To order a copy ofApplyfrsgOMT

call (609) 46S-%02or see our Home Pagehtqd/www.sigs,cam/

Applying OMT was writtentoillustrate the process forimplementing an applicationusingthe verypopularObjectModeling Technique (OMT)created by James Rumbaugh,Designed as a how-to guide,this book instructsreadersonthe implementation processand on practical approachesfor OMT. The includeddiskette provides relevantC++ and Smalkalkcode.

This is an eswntial rejkrencefor anyone wishing to learnobject-oriented analysis anddesign or who uses or wants kbegh exploration of theObject Modeling Technique.

mw AvailableatAdd bmk otors.DhiributedbyPrenticeHall.

of each of the classes used in the compilation process. Ituses five Factory Methods to instantiate its co-workers, pro-viding a locus for overriding in future subclasses. Instancesof Pwser, PrograrnNodeBuiider,and MethodNodeHolderareinstantiated simply by sending #new to the class. The othertwo methods are:

newCodeSheam‘codeStreamClass new owner: self

scopeForClass“self nameScopeClass forClas.s:class

These implementations show why Factory Methods some-times produce classes and sometimes produce instances:because different “factories” (i.e., classes) sometimes needdifferent messages and associated information to producevalid instances. ParameterizedCompiler overrides the keyworker method of step 4, #tmnsl.ate:noPattem:ifFailmeed-SourceMap:handle~, as follows:

translate: astream noPattem: noPattem ifFaikfailBlockneedSourceMap: map!%g handler: handler

I methodNode holder codeStieam method ImethodNode:=

self newParserparse: aStreamclass: classnoPattem: noPattemcontext: contextnotifying: handlerbuildec self newBuildersaveComments: mapFlagifFail: [AfailBlock value].

methodllod e:=producer transfonnhee: methodNodein: class.

handler selectoc methodNode selector. “save selectorin case oferror”

codeStream:= self newCodeSheam.codeStream class restart.signal

handle: [:ex IcodeSheam:= self newCodeSheam.ex restart]

do: [codeStream class: targetl%ss outerScope:seLfscopeForClass;

requestor: handler.mapFLagifTrue: [codeSheam saveSourceMap].noPattem

ifTrue: [methodNode emitValue:codeStreaminContext: context]

ifFalse: [methodNode emitiffect:codeStream].

method :=3D codeStream makeMethod:methodNode].

holder :=3D self newMethodHolder.holder node: methodNode.holder method: method.mapllag if True: [holder sourceInfo: codeSbeam

July-August 1995

sourceInfo].‘holder

There are two things to note herein contrast to the super-class’ implementation of this method. First, no classes arereferred to by name-they’re all accessed by the instanti-ation methods shown earlier, so that they can be easilychanged and specialized. Second, there is a new messagesend just after parsing, which is our second transforma-tion stage, (In a similar way messages can be added at theother stages so that the compiler’s producer can trans-form the objects flowing through the production points.)The producer working with this ParameterizedCompilier isgiven the newly obtained parse tree and the class it isbeing compiled in with the #-hansformTree:in: message.The producer is expected to return the pame tree thatshould be used for code generation. By default, Method-Producer will simply return the parse tree that is the firstparameter of this message, but in some cases (includingwhen breakpoints are present), it will need to be able tomanipulate the parse We.

A parse tree, as returned from the parser in step 4a, isrepresented by its root node, an instance of classMethodNode. That node, and all others in the tree, aresubinstances of the abstract superclass ProgramNode,which defines the common behavior of all members of aparse tree. Each superclass of ProgramNodehas a differentinstance layout. For example, a MethodNode contains asingle block as its child in the tree, while a messageNode

17

Page 18: Smalltalk Volume 4 Issue 9 - ESUG

!DEEPIN THE HEARTOF SMALLTALK

has both a receiver and an array of arguments as its chil-dren, This makes it hard to enumerate over a parse tree.

Fortunately help is provided in tbe form of Program-NodeEnumerator,an abstract class that outlines the proce-dure for enumerating over a parse tree. ProgramNode-Enumerator is an instance of a common design pattern, inthis case one called Visitor. The Visitor pattern representsan object that operates on each object in a complex, het-erogeneous sh-ucture, performing some function on eachmember that is dependent on the type of the member.However, ProgramNodeEnumeratoris only an abstract rep-resentation of a Visito~ it doesn’t acturdly do anythingwhen it “visits” the various nodes in a parse tree. We

out changing its basicintroducing abstract clasages, changing inheritationships, and so on. Pmake them easier toRefactorings area newfink and communicateestablish a basis for devwork. In our experience,ous paragraph is a codoing system reworlq aour system rework intrthinking about an exis

implement a concrete sub-class in the form of Program-NodeEvaluator,a class that pro-vides the normrd block-basedenumerations used in theCollefion classes, including#do: and #seleck.

The ProgramNodeEvaluatorinteracts with the ProgramNodesusing a technique called dou-ble-dispatching the evaluatorsends the generic #nodeDo:message to each node with the

ParameterizedCompiler

allows programmers to override

behavior at each production point

and transformation stage,providinggreatflexibility in the

compilation process.

evaluator itseJf as a parameter, which in turn sends back aclass-speciilc message to the evaluator, such as#doMessage:receiverxelectorargurnents: from a MessageNodeand #doAssignmentm.riablexnlue: horn an AssignmentNode.The evaluator implements these messages by sending itself#doNode for each node passed to it in the case of theAssignmenWode,that would mean tbe variable node and thevalue node, while in the case of the MessageNodeit includesthe receiver node and all the argument nodes. FinaJly theevaluator implements #doNode: by evaluating the blockwith the programNodeparameters as an argument and thensending #nodeDo: back to that node to contiue the enu-meration. The enumeration terminates because the variousleaf nodes, such as LiteralNode or VariableNode, have noRogramNodechildren for the evaluator to #doNode: on.

There is one tlnal issue to consider before our imple-mentation is complete. Prior to our work, parts of the sys-tem could compile a method by sending appropriatemessages to its target class, or they could parse or compilemethods by sending messages to an instance of a Parser orCompiler obtahed by the class’ #compilerClass message.Now, however, it is important that all method parsing andcompiling be done through the appropriate Method-Producer, so that any extensions or vruiations in the com-piled code are handled consistently and correctly. As aresult, we have to search through the image to find allplaces where Parser and Compilerare used directly to see ifthey are SW correct. If they are not, we must change thesite to use either the class or its MethodRoducer.

We use the term “refactoring” to describe a commonprocess that developers use to reorganize a program with-

in an object’s look-up#class message, which rate the object, definethings. Any method tha#class to obtain in#dispatchingClass had to

CONCLUSIONThis concludes the impble compilation framewMethodRoducer-Parametbreakpoints. Jn the prosystem increases the ebility as well as someMethodRoducers to be c

Authors’ noteSource code for the paraanonymous ftp fromParameterizedCompiler2trized Compiler41,st insupport).

References1. Me, B., V Jones, and

SwuxrAI,K REPORT2(9),2. Gamma, E. et al. DESIGN

OBJECT-ORIENTEDSOFW1994.

10

functionality+xamples includesses, renaming variables and mes-nce relations to composition rela-rogrammers refactor programs to

reuse, maintain, and understand.and useful way for programmers to

about what they do, and they alsoeloping tools to support refactoring

the process described in the previ-mmon refactoring applied whilend we call it lkail Splitting, Whenoduces one or more new ways ofting process, it splits one existing

hail into many. We must thenfind each place where the trailforla and point the way (bychanging code as necessary)down the correct path. We alsoapplied this refactoring in theimplementation of breakpointmethods (as we’Jl see nextissue) and when we intro-duced lightweight classes.1 Forthe latter, we created a newmessage, #dispactchingClass,which returned the first class

chain, as opposed to the existingeturned the class used to instanti-its layout, and many, many othert had previously sent the messageformation now returned bybe changed.

lementation of a new, more flexi-ork. Next issue, we wiJl use the

erizedCompiler pair to implementcess, we’Jl see how this new sub-nvironment’s programming flexi-

extensions that aJlow differentombined.

meterized compiler is available byst.cs.uiuc.edu. Look for the file

0,st in pub/st80_vw (or Parame-pub/st130_r41 for 0bjectWorks4.1

R.E.Johnson. Debugging objects, THE1993.PATTERNSELEMENtSOFRmxs.mm

A.IW,Addison-Wesley,Reading I@

The Smalltalk Report

Page 19: Smalltalk Volume 4 Issue 9 - ESUG

AmodestmetaproposalKent Beck

IJUSTGOTANIssuE OFSMMEMM REPORTthat had some-one’s written summary of one of the talks I gave atSmalltrdk Solutions. I sound like a wild-eyed, fire-

breathing, spiky-haired maniac! It is so strange to see howothers see me, especially in public. I’ll admit to being inrare form in New York, a little over the top on the outra-geous meter, but really...

The other shock this month was news of theParcPlace/Digitalk merger. I see the press release. I checkthe date. Nope, not April 1. Hmmm.. .1s this some kind ofelaborate joke (badly timed and in extremely bad taste)?

Now that I’m over the shock, I can see positives andnegatives in the deal. It makes sense for Digitalk because(as RobertYerex from ObjectShare pointed out) they got amuch better valuation than they would have on the openmarket. It makes sense for ParcPlace because their worstnightmare was Digitalk’s technology married to some-body with cash and marketing clout,

The outlook for customers isn’t so one-sided. If all goeswell, the current products will get their holes tilled.VisualWorks will get native widgets and better perfor-mance. V will get a better garbage collector and iidlerapplication model. DigitaJk’s culture of getting stuff outthe door mamied with ParcPlace’s culture of striving forelegance could be a potent brew. On the other hand, ifsales aren’t going well there will be a lot of pressure todrop one or the other image before PPD can architect anorderly transition.

AU this spells opportunity for the other vendors toinvoke that good old FUD factor, and pickup some quickmarket share. They’d better, because if they don’t and PPDstarts hitting on all cylinde%look out!

CLIENT 00CLI’ve gotten several questions about what it’s like to be aconsultant. By the time this is published, everyone on theplanet who knows how to write Smalltalk may already bea consultant, but just in case, I thought I’d provide a shortsketch of one of my clients and what I do for them.

Orient Overseas Container Ltd. (OOCL hereafter) is a

Kent Beck has been discovering Smalltalk idioms for ten years atTektronix, Apple Computer, and MasPar Computer. He is thefounder of First Class Software, which develops and distributesdeveloper tools for Smalltalk. He can be reached at First ClassSoftware, P.O. Box 226, Boulder Creek, CA 95006-0226,408.338,4649 (voice), 408.338.3666 (fax), or by email at70761,1216 (CompuServe).

July-August 1995

$1.5 billion (US) global container shipping companyheadquartered in Hong Kong. Their business is deliveringthose standard-sized containers you see pulled by truckson the highway from point A to point B, where A and Bcould be anywhere in the world. They own or lease hun-dreds of thousands of containers and chassis. They oper-ate 30 some container ships. They run terminals, depots,and transshipment yards all over the world. They interactwith hundreds of thousands of customers, all of whomrely on 00CL to get shipments delivered on time, Theyhandle more than one million shipments per year.

While these wen’t numbers to impress Federal Express(with a peak of three million shipments per d@), they arepretty respectable, especially when you factor in thetremendous amount of capital involved in the form ofcontainers, ships, and yards. Container shipping is heav-ily regulated worldwide, so small reductions in cost orimprovements in productivity make a huge difference onthe bottom line.

00CL3 current IS operation is cenhalized in HongKong, built around a large IBM mainframe. To gain flexi-bility, reduce cost, and better address local requirements(imagine having to satisfy a hundred different customsbureaucracies with one system), they decided to move toa more distributed, client/server system. They choseSmalltalk (VisudWorks) for the front-end implementa-tion language.

The project, IRIS-2, is medium-scale by IS standards.They plan to have around 40 developers when things arein full swing. They located in Silicon Valley to be closer toSmalltalk talent,

I’ve been involved with IRIS-2 since it began its life inthese United States, I’ve had a number of jobs as the pro-ject has matured:

● At tirst we were all just trying to figure out the architec-ture, so I was a design consultant. We slung CRC cards,acted the part of objects, and learned about each oth-ers’ specialities.

● As the design became clemer, David Ornstein and Iwrote an architectural prototype of a critical part of thedesign so we could be sure we weren’t just makingbeautiful diagrams.

● I helped design and deliver the “Smalltalk Boot Camp,”a three-day simulation of the entire software lifecycleintended to bring teams closer together and promotegood programming practices,

● OOCL has generously sponsored my pattern writing,

19

Page 20: Smalltalk Volume 4 Issue 9 - ESUG

I SMALLTALKIDIOMS

using the Smalltalk Best Practice Patterns I have beenworking on as part of their developer guidelines.

● I have been visiting about twice a month all along toreview code, suggest improvements, and tune perfor-mance.

1 have learned a number of interesting lessons for myselfand for projects like this, which are becoming the norm inthe Smalltalk world. On my part, I have learned:

● A stand-up lecture is useless for teaching. I have givena series of lectures about patterns that seemed to haveno impact, To address this, we held a “Pattern Bowl,”where teams were challenged to find patterns or theabsence of patterns in exisdng code. I think everyonelearned more in those two hours than in tens of hoursof lecture before.

“ Be outrageous. What we are doing is difficult. It is risky(does anyone know the source of the factoid that 50%of all software projects never deliver?) There is a lot atstake. Plodding along in a humdrum way doesn’t cut it.If I want to have impact I have to go for risk and flash,not “just the facts.” The Pattern Bowl is a good examp-le. We had prizes, applause, an obnoxious timekeeper(me), tension, competition, and the all-importantfuzzy animal to go into the keeping of the winningteam. Hokey? Yes, but it works.

“ Don’t be too hard on yourself. A consultant can onlydo so much. In the end, the success of the project isn’tmy responsibility. I’m responsible for doing the best Ican, and suggesting other things that I can see needdoing. When a deliverable slips, it doesn’t help to getcaught up in the emotion. It’s hard to care but not toomuch, but that’s what it takes to be effective.

This project has shown me that Smalltalk has some seri-ous holes. I have been swimming in Smalltalk for so longthat I no longer see the water. Newcomers to Smalltalkfind it anywhere from irritating to impossible. For themarket to grow, the vendors absolutely have to addressthe issues raised by new Smalltallcers.

For projects, I learned● Baby steps. Do one small thing then one slightly larg-

er thing, and on and on, The temptation to jump inwith both feet is overwhelming. The argument alwaysgoes “I have committed to this date. I can’t do it withbaby steps. I have to ramp up more quickly” The resultis always disaster. Always. OOCL has done a good job oftrying to stick to baby steps and of getting back to babysteps when they have gotten too big too fast.

● Program in pairs. The most productive form of pro-

grrimming I know (functionality/person/hour) is tohave two people working with one keyboard, mouse,and monitor. Our educational system trains us not to dothis and some upper managers have a hard time with it(“Why did we buy all those workstations and cubicles ifwe don’t use half of them?”), but it makes a biggerchange in productivity than any other single change.

● Follow standarda. There are two parts to this. First, youhave to have standards. In writig patterns, I’m deeply

20

embroiled inexactly what the standards should be, buthonestly it is far better to have adherence to good stan-dards than deviation from perfect standards. Second,you have to follow them. 00CL has recently put inplace a schedule of peer review that makes sure every-one’s code is seen by a critical audience at least everycouple of months, This ensures that everyone has amotivation to understand and follow the standards, ifonly to avoid being ripped in public.

There’s a lot more, both to the project and what I’velearned, but it wiU have to await another column. I’mrunning out of space and I still haven’t gotten to my tech-nical topic...

A MODEST META PROPOSAL“Mets programming? Isn’t that what PhD’s do to get the-sis? What does that have to do with getting my nextdeliverable out?” Even if you don’t know it, you’re proba-bly already doing some meta programming. Meta pro-gramming is writing programs that manipulate not yourobjects, the way usual programs do, but the representa-

tion of your objects. For example, the fact that eachobject has a hidden “class” instance variable, and youcan fetch any object’s class and ask it interesting ques-tions, is meta programming. IsKindOf, respondsTo:,instVarAt:—these are all messages about how the receiv-er is represented.

SmalltaJk makes meta programming easy. Too easy, infact. When you meta program, you are no longer reallyprogramming in SmalltaJk, you are inventing a new pro-gramming language that is an extension of SmalltallcUsed indiscriminately by application developers, metaprogramming is a disaster. Just as not everyone can writereusable software, not everyone can write new program-ming languages. When everyone is writing in their ownSmalltrdk increment, and all the increments are different,disaster lurks. You can no longer read a line of code andguess what it does correctly, Risk soars and so does thecost of maintenance,

On the other hand, the meta programming facilities ofSmalltalk can come in extremely handy, They can evensave a project. If having some new kind of control sbuc-ture vastly simplifies your program, chances are you canimplement it in Smalltalk and take advantage of it,

How, then to provide the needed facilities withoutexposing them unnecessarily? The problem as I see it isthat they are all implemented up there in Object. It’s justtoo easy to stumble across isKindOfi,use it to solve a short-term problem, and never discover the powerful polymor-phism lurking just around the corner. I propose to put upa waJl between application programmers and meta pro-gramming by introducing a new class, MetaObject, uponwhich all the current meta protocol in Object (and some inBehavior as well) will be heaped.

This is not an original idea. I got the idea in 1987 fromPatti Maes’ 00PSLA paper. I don’t remember the exacttitle any more, but it introduced the idea of meta objects.

The Smalltalk Report

Page 21: Smalltalk Volume 4 Issue 9 - ESUG

I’ve had the idea floating around in my head since then,but I didn’t do anythng about it until I was bored on aflight recently. Pulling out my trusty ThinkPad, I whippedtogether an implementation. I liked the result enough topublish it here.

MetaObject is an Adaptor on any object. An Adaptorchanges the protocol that an object accepts by interpos-ing an object with the changed protocol.

Class: MetaObjectsuperclass: Objectinstance variables: object

You create a MetaObject by giving it the object to adapr

MetaObject class>>on: anObject‘self new setObject: anObject

MetaObjecO>setObject: anObjectobject:= anObject

There is a Facade in Object, Obje@>meta, for creating aMetaObject. Clients will use this interface.

Obje@>meta‘MetaObject on self

The infamous isKindOf becomes “inheritsFrom:” inMetaObje&.

MetaObject~XnheritsFrom: aClass‘self objectClass includesBehavioc aClass

ObjectClassreplaces Obje@>class:

MetaObjecP>objectClass‘self object class

I don’t have space hereto show all the implementations ofthe MetaObject protocol. Table 1 shows the old and newmeta protocol. In some cases, I’m not thrilled with the

July-August 1995

new names. I’ll happily entertain suggestions for betterselectors.

This is certrdrdy not an exhaustive list. It’s just what Icame up within a couple of hours. It should be possible tomove more meta programming protocol in MetaObject.

Given this amount of protocol, I was able to quicklyproduce an Inspector that used a MetaObject to display andmodify instance variables.

MetaObject provides the following advantagess It discourages casual use of meta programming pro-

tocol. If you see “meta” in application code, you’ll knowto perk your ears up and make sure it really belongs.

● It collects scattered protocol. Some j4meta programming protocol is implemented in Object,

some in Behavior, some in Class. MetaObject brings it alltogether in one place.

. It is flexible. If a particular class needs a different kindof MetaObject for some reason, it can override “meta.”You might do this, for example, to give a uniform pro-gramming environment on Smalltalk and C++ objects,

● It simplifies ObjecL Let’s face it. Object is too darned big.VkualWorks 2 (the Envy version, anyway) defines 166methods on Object. Visual SmaUtalk Enterprise 3,0defines 348. IBM Smalltalk gets by with 101, MetaObjectis a step in the right direction.

MetaObject has the following disadvantages:● One more class. Don’t we have enough classes in the

base system already? We will have to teach people touse it and convert old code.

● One more object, Now, when you want to have accessto meta protocol you have to create a whole newinstance of MetaObject.

How about it? Next time you need meta programming,implement a little MetaObject first and see how it feels. Letme know if you like it,

Table 1. Old and new meta protocol.

Obiect meta messaee

class

changeClassToThatOEaclass(VisualWorka)

class aUInstVarNames

class aUlwtVarNames size

in.stVarAh aNumber

instVarAt aNumberput: anObject

allOwnersWeakly aBoolean(VmualWorks)

become: anObject

isKindOfiaclass

isMemberOfiaclass

MetaObject message

objectclass

objectllass: allass

keys

size

at aStn-ing

ak aStringput anObject

owners

.switchWith:anObject

inheritsFrom: aclass

instantiates: aclass

Extdanation

Return the class thereceiver instantiates.

Change the receiver’s class.

Return the named instance variables (MetaObjectlets you treatan object like a Dictionary).

Return the number of named instance variables,

Return the value of an instance variable.

Change the value of an instance variable.

Return a Collectionof all objects refering to the receiver.

Swap two objects identities.

Return whether the receiver inherits from acl.ass.

Return whether the receiver is an instance of aClass.

21

Page 22: Smalltalk Volume 4 Issue 9 - ESUG

IWAS RECENTLY ON A PANEL DISCUSSION atObjectWorld Boston about problems O-O softwareprojects encounter and how to recover from them or,

better yet, avoid them in the first place, It got me tothinking about the lessons we’ve learned and how theykeep coming back over and over again. It’s been awhilesince I listed a set of these topics, so here goes.

ERRORSAND RECOVERYThere are a number of problems we could discuss, cer-tainly too many to exhaustively list here. So in this sectionI’ll list some of the problems I see most frequently on theprojects I work on.

Missing modelThis problem results when you connect a graphical userinterface (GUI) directly to your existing database (DB).This design keeps you from achieving reuse and lowermaintenance costs when developing your software sys-tems. Object technology’s great potential is primarilyachieved by developing and leveraging a model of yourbusiness domain. This model is surfaced through theGUI. A database is merely persistent storage underneaththe object model.

If you need a quick ad hoc solution to some need inyour organization, you can by all means slam together anapplication that is all GUI and DB. Just don’t kid yourselfinto believing that you will have an easier time reusing,maintaining, and extending the application over time.

Some of the development products available todaymake leaving out the model between a GUI and DB veryeasy to accomplish. Interfacing objects to a relationaldatabase (RDBMS) used to require a “broker” layer ofsoftware to handle the data movement to and from objectstate data and database rows. IBM’sVisualAge is an exam-ple of one such product. VisualAge handles many of thedetails of accessing RDB row data. In fact, as Figure 1shows, you can make direct connections from GUI wid-gets to database row information.

Mark Lorenz is founder and president of Hatteras Software Inc., acompany that offers services and products to help other compa-nies use object technology effectively. He welcomes questionsand comments via e-mail at [email protected] or phonemail at919.319.3816.

22

Staffing behemothsThis problem occurs when you have offices ful of peopleand the project is just starling to develop an object model.It occurred on a project of mine a few years back. Anothermodeler and I showed up to begin developing an objectmodel. We were shown around the group and discoveredthat there were over 25 developers and all the surroundingsupport sti on the project, We gathered a couple of tech-nical leads and a couple of domain experts and the six ofus went into a conference room to start the rapid model-ing sessions. I asked the woman who eventually becamethe de facto chief architect on tbe project “what are all theother people doing while we’re in here?” The answer was“they have things to do.” Well, they basically wasted timewaiting for us to get far enough along with a model andsubsequent architecture of subsystems and contractualinterfaces, They were then put to good use.

My previous work discusses how to architect your sys-tem so that teams can work relatively independently andstill be productive in building a cohesive system. 1’2Using these techniques, you can effectively grow yourorganization and avoid the costly mistake of staffing toomany too soon.

Ill-behaved object modelM “object model” that has all data and no behaviors is atypical indication of this problem. A group Iiom a telepho-ny project once proudly marched me into a room to seetheir object model pasted onto a wall. The pages and pages

.

EB’K’qap--- ..........$=lDmhbnEeCwaY

resuh%blnd DeInbaseCmery

rwmnt%w ti msuHTablnd DnlnbnseOuary’

Figure 1.EuampleVkualAge application with no model.

The Smalltalk Report

Page 23: Smalltalk Volume 4 Issue 9 - ESUG

of output included every imaginable piece of state data thatcould be associated (and had been in their legacy data-base!) with the classes they had identified. And not oneclass had a single behavior in it! Figure 2 shows an exampleof what this type of model looks like. You can spot it fromacross the room, even if you can’t read the details, becausethe middle state portions of the class boxes are filled withtext and the bottom behavior portions are empty.

An object model must focus on behavior, as shown inFigure 3. I’ve purposely left all state data off this diagramto drive the point home that behaviors and their alloca-tion are essential to success. Certainly, you will want to(eventually) show state data in youI object model.

Missing managementThere are differences in managing a team developing O-Osystems using different processes and methodologiesrather than traditional techniques. Managers need train-ing in what to track, what it means, how to schedule, howto organize teams, and so on.

Figure 4 shows an example of basing schedules on usecases, scenario scripts, and subsystems. This is differentthan traditional schedules, which are generally based onfunctional line items. This new type of schedule hasdependencies on the team organization also. For example,most of the time one small team will work on one subsys-tem start-to-finish. This requires that work on businessscenarios that affect their subsystem be scheduled seriallyalong with other subsystem teams. Support subsystemscan be worked on independently, as long as they are readybefore dependent business scenarios need them.

Persistence black holeI have seen whole projects eaten alive by this problem.There are various facets to integrating O-O systems to

Customer Account

name number

address ● balancephoneNumber transactions

Transaction

numberIineltemsdatetotal

Figure 2. Example of a data model mistaken for an object model,

July-August 1995

legacy systems and databases, It requires brokering tomap between the object’s state data and the RDB rows,as shown in Figure 5. This is often just the tip of the ice-berg, however. When you start getting into issues of dis-tributed objects, shadow objects, system startup andshutdown, and error recovery, the situation gets muchmore complicated.

Basically you end up spending a large percentage ofyour time getting into the object database (ODBMS) andsupport tool businesses. You worry about how to handlelong DB transactions, rollback, and other issues. This obvi-ously takes tie away from your real business, such asbuilding a finance, insurance, or retail application,

Depending on your requirements and the productsavailable when you encounter this beast of a problem,you have different options, An easy one, if it meets yourneeds, is to use an ODBMS such as GemStone, Versant, orObjectStore.

AN OUNCE OF PREVENTIONPreventative measuringO-O metrics can assist you in vruious ways, from develop-ing better estimates for new projects to checking on the

quality of projects already underway. The goal is to findand resolve problems as soon as possible.

The 00 metrics that give you the most “bang for thebuck” are organized as follows:

● Method size-number of message sends_ Class size-number of methods and variables● Coupling-law of Demeter, global usage● Inheritance—method overrides, hierarchy nesting

depth● Complexity-McCabe for classes

See OBJECT-ORIENTEDSoF’IW.mEMETFUCS3for a completediscussion of each of these.

Customer Account

hasPhoneNumbec withdrawisPrefened deposithasCheckingAccount isOverdrawn

ownerbalance

Transaction

logTois5uspendedcommittotal

Figure 3.The same businessrepresented by a true object model.

23

Page 24: Smalltalk Volume 4 Issue 9 - ESUG

7

I PROJECTPRACTICALITIES !1

Design, don’t just codeMos~ proiect teams focus on coding issues, such as lan-guage- sfitax and tricks, instead o~what’s really impor-tan—the object model and design conventions. I recom-mend the following techniques for yom design (discussedin greater detail in RAPID Somvww DEVBLOPMENT2).

Instantiation integriq. This technique ensures thatyour model state is valid at all times through the use ofcustom class instantiation methods. For example, if yourbusiness rules require a SalesTransaction to have aCustomer associated with it, you might have a classmethod such as:

SalesTransation classfor aCustomer

“return an instance of myself with my customer setto aCustomer”

‘self newcustome~ aCustomer;yourself

Collection protection. This technique protects your statefrom mistakes made by your clients by passing themcopies of your information. For example, if a view classasks the Store for its employees, a copy of the Collection isreturned so that the real Collectioncannot be corrupted.

Storeemployees

“return a copy of my employee collection”

‘self myEmployeescopy

Laissez-fd?winitiukutim. This technique makes your

24

objects more robust by having them self-initialize as need- ~ed at runtime. It also allows for business rule enforcement ,.and ease of redesign because you have a point of controlfor state access.

~StoremyEmployees

“Private: return my collection of employees” .

1?

( myEmployeesisNil ) ifl’rue: [ selfmyEmployees: OrderedCoUetion new 10. ].

‘myEmployees

Invest in an object modelThe most important O-O software asset is your business’object model. It is absolutely essential to your successthat you spend time developing a model of your businessconcepts, relationships, and service requests beforedesign and implementation. Get O-O and domain expertsin a room, write use cases and scenario scripts, and drawobject model and collaboration diagrams.

Get mentoringThe fastest way to get your people over the learning curveis through mentoring. There is no replacement for directinteraction with people who have developed O-O systemsbefore. Developing a good O-O system takes a lot morethan a language class!

Run your project like a group of small projectsThe Standish Group did a study of 8,380 applications andfound that 78% of small company software projects wereSuccessful, whereas Ody 9% Of the large company pro-jects were successful The message tome is that the onlyrealistic way to run a large project is by dividing the teamup into relatively independent smaller teams.

,.,

,,.,

[:

,.

,:.

{.,

E!

\ ..:--- ~~~

Usacesel.

“&bayittil ““”-“-” ‘“

“tikl “ ‘“” “’ “’..- — . -.

Scenario 2

1‘--

.ernz” ““

-S&nirbl--””” ““”,.- *k,

Iusezeee2

Scenarb 3 fioio&pa. . . .

Scendo3!Jn2tast

sliindo30as&rmiaw

~a”~ 1. .. . . ..Conmmatlons Coniracis”

. .. . . . . .. . . . . . . ------w—~z

D&i&i brokirc&a&aFigure 4. Example schedule based on use cases.

bte

#.,

K.

~ !The Smalltalk Reporl

Page 25: Smalltalk Volume 4 Issue 9 - ESUG

JOURNAL OF OBJECT-OSUENTED PROGRAMMING (JOOP)

is the technical magazine designed to help programmersand developers better understand object technology anduse it more effectively. With each issue, you’lJ receive thelatest technical breakthroughs and information, usableresearch, innovative ideas, product news and reviews,and other useful advice nine times per year!

Edited by O-O expert Richard Wiener, JOURNAL OF

OBJECT-ORIENTED PROGFWMMRSG is filled with informa-tive articles and regular columns by top industry leadersincluding James Rumbaugh, Ivar Jacobson, DonaldFiresmith, Andrew Koenig and others.

?EibORENTED

WrJJnNcoumN mSIGSPublications, PO Box ECk19,Brentwood, TN 37024-9737

For faster serv@ call: 1-8C0-361-1279 or fax 615-370-4645.---------- -------- -------- ------------ ..-----

~ YES! Send me one year (9 issues) of JOOP for $69.Plus, FREE issues of Cross-P/atform Strategies end

ClientiServer Develope~

Methodof PaymentQ CheckEnclosed(payableto S/GSPublications)Q Charge My D Visa D Mastercard Q Amex

Card No. Exp. Dete

Signature

Neme

Company

Address

Country/Postal Code A50701

lmporlml: Non. L’.S.ordersmust bcprepaid Lr.S,ark include shipping. Cmladim and

Wrican orders pleased $25 for air wvire. Outside North America mid .$40. Che4s must

K pd in Lr.S.dollars drawn OH a L’.S. bank Pleaseallow 6-8 wckfor dchwy offirJI iNI,.

L==l 6Address

&&

View

objects

Modelobjects

DBBrokerlayer

DBRecord

DBMS

-. .,.. -“.. ,

Figure >. use or a utmroKer.

SUMMARYWe’ve gone over a number of the most common problemswe run into on O-O projects. We’ve discussed ways toresolve them when they happen and, more importantly,how to avoid them in the first place,

Terminology● behavio~ The services provided by an object to other

objects, through messaging and method invocation.● collaboration diagram Graphical representation of

the subsystem groupings of classes and the contractu-al relationships between subsystems and key classes.

s object modek Objects and their relationships requiredto represent your business domain and business rules.

● distributed object An object that resides on anotherprocessor.

● object database A persistent store that works seam-lessly with object definitions and/or instances.

s shadow objecti An object that has a proxy stand-in onthe local processor, but actually resides on anotherprocessor.

References1. Lorenz, M. Architecting large projects, THE SMALLTALK REPORT

4(6):2&29, 1995.2. Lorenz, M. RAPIDSOFTWAREDEVELOPMENT,SIGS Books, New

York,1995.3. Lorenz, M. and J. Kidd. OBJECT-OFIIENTSDSOFTWAREMETRICS,

Prentice Hall, Englewood Cliffs,NJ, 1994.4. The Standish Group International. Cwos, 1994.

July-August 1995 25

Page 26: Smalltalk Volume 4 Issue 9 - ESUG

Managingprojectdocuments

Jan Steinman BarbaraYates

IN OUR PREVIOUS COLUMN, we made a case for “con-tinuous documentation,” and outlined what thatentads. We also promised to give you some concrete

examples and source code, so you could begin to imple-ment a continuous documentation process.

First of all, we’ll need to change how classes storetheir comments.. ,WE INTERRUPT THIS COLUMN TOBRING YOU A BASE IMAGE CHANGE ALERT! ALLUSERS WITHIN 200 KILOBYTES OF THE IMAGE MUSTEVACUATE IMMEDIATELY! WHEN YOU ARE ALLOWEDTO RETURN, YOUR PRECIOUS, CAREFULLY CRAFTED,WORK-OF-ART CODE WILL TAKE ON STRANGE AND(we hope) WONDERFUL NEW BEHAVIOR! HAVE ANICE DAY!

Whew! We almost slipped one by the Base Image Policethere, but they caught us! So, let’s retitle this column andproceed.

MANAGING MODIFICATIONS (OR’’WHO CHANGEDbasicNew?”)Pity the poor Smalltalk vendors! You buy an object libraryin C++, and you typically get linkable object code-itworks, or it doesn’t, But when Smalltalk customers don’tlike what they got from their vendor, they simply changeit—which often introduces bugs, which are often subse-quently reported back to the vendor! (All of this applies tothird-party code as well.)

Consider the myriad ways that basic Smalltalk canbecome polluted:

● Beginner naivet4. “Delay:= Delay forSeconds: 1.”● Enough lmowledge to hurt yourself. A seasoned ST/V

user tries VisualWorks, and writes a cleanup methodthat does “MyClassalllnstances do: [inst I inst become:nil]. ”

● Enough lmowledge to make it look random, The same

Jan Steinman and Barbara Yates are co-founders of Bytesmiths, atechnical services company that has been helping companiesadopt Smalltalk since 1987. Between them, they have over 20 yearsSmalltalk experience. They can be reached at Barbara. [email protected] or [email protected].

26

code as above, but cleverly made conditional upon rarelow-memory conditions, and then forgotten.

● Unintentional overrides, Such as implementingnextPutAlk in a Stream subclass that normally inherits it.

● Forgotten halts and other test or debug code.

Beginners often put halts in system code (rather thanputting halts in their own code, then stepping into thesystem code), and sometimes they forget to take themout .

● Well-meaning changes gone awry. Such as the data-com specialist who changed Integer printOn: so that ifthe shift key is held down, they print in hexadecimal.(This one didn’t quite make it to production beforesomeone noticed strangeness when extending selec-tion in a table by shift-clicking,..)

“ Downright malicious. Nab, no Smallt alker wouldmake malicious changes, right? But if someone did, saya disgruntled soon-to-be former employee .,.

Always keep in mind that base changes are the enemy ofreuse. One of the big wins of reuse is that less testing isneeded when you reuse previously tested code, The downside is that changing code that is heavily reused increases

the testing burden, because you aren’t really sure all theuses of the changed code agree with each other.

Why are changes necessary?In team programming, base changes fall into two cate-gories. Personal changes are necessary for individualdevelopers. Individuals need to be able to experimentwith base changes before foisting them on their teamm-ates; they may experiment with base changes to betterunderstand the environment or they may simply want tocustomize their own environment. If you are using a codemanagement system (such as ENVY or Team/V), you gen-erally have numerous options for balancing the needs ofthe team for stability against the needs of the individualsfor experimentation.

The second category is where the trouble begins.Although you should do whatever you canto discourageit, sometimes you need to make project- or corporation-

wide base image changes. These changes might include:

The Smalltalk Report

Page 27: Smalltalk Volume 4 Issue 9 - ESUG

conh.nued on page 31

● Fixingbugsinvendor’s code. This is fairly unusual, but label if the windowif you do find a bug that is getting in your way, and it window is iconifiedhas an obvious fix, you will probably want to incorpo- Another useful erate it into your base. Also, maintainers love getting bug for an instance vareports with fixes, so if you fix the bug carefully, docu- selector so that itment it properly, and submit it with your bug report to change to “pluggabthe vendor, there’s a good chance it will be in the next behavior of your srelease from the vendor, which makes your re-integra- tially invisible to oltion job that much easier. A big problem w

● Make enhancements to the vendor-supplied tools. directly visible to sThis is the category for which the Base Image Police class directly accesscaught us! The combination of dynamic compilation than going throughand full source code means you can easily tailor the tandem, there willSmalltalk development environment to your organi- diagnose.zation’s specific needs, These kinds of changes have A4ethod overrides

little possibility of getting into a vendor’s product, have tremendous imand so they must be done in such a way that facili- Behavim basicNew w

tates re-integration with futurevendor releases,

● Make enhancements to the ven- “When Smalltalk customersdor-supplJed framework classes.

don’t like what they gotThis is similar to the previouscase with one important differ- from their vendo~ theyence: the changes you make toframework classes will be deliv- simply change it.”ered with your application, andso must be more robust thanchanges made to development tools. This shouldinvolve regression testing to ensure that the frameworkstill functions with previously written code.

Limit scope and impact of changesBase image changes can be categorized by their scope.You should carefully analyze your needs, and limit thescope of your change to the greatest degree possible. Forexample, it may first seem that you need to add aninstance variable to a base image class and add twomethods that use that new state, but further analysismight show that you really only need to change the use ofan existing instance variable, and then hide that changeby changing the methods that access that instance vari-able. The following change categories are roughly inorder of desirability.

Single-method, non-state changes are the best. Suchchanges should not change the arguments or answer ofthe method, but only its side-effects. The answered objectshould have the same behavior, and no additional con-straints should be placed or assumed on variables or sentmethods.

Encapsulated state changes put different objects ininstance variables, but manage those changes throughthe methods that access those variables. These changestend to have small impact on any given vendor release.For example, you might need something better than sim-ple truncation of window labels to use as icon labels, soyou could change the label instance variable to be a two-element Array that either answers a full, title-bar length

son tools will detecwell conflict with v

Finally there issuch methods—if athe change shouldn

Chan@g messa

get messy, and shouor returned objects,an Array rather thanyour particular cassomeone else’s code

Changing object

instance variables,you can make, andables by itself is nonecessary, most ofbehavior of the clasare what subclasses

Changing interclmight track down asoftware won’t knSmalltalk vendor’seither! If changes tdocument them weeventually will resu

“Conditionalize’’chaEspecially in the lbecomes increasing

July-August 1995

is open, or a custom short label if the.ncapsulated state change is arrangingriable that normally holds a methodcan hold a block. This can be a usefulle views” for increasing the dynamic

ystem, and if properly done, is essen-d code.ith this technique is that object state isubclasses. If some poorly written sub-es the state you have changed, rather

the access methods you changed inbe trouble, and it may be difficult to

don’t seem like changes, but they canpact. (If you don’t believe us, override

ith a new implementation in the Objectclass, then purposely introduce abug and see what trouble that

causes!)Overrides are tempting, becausethey do not change actual baseimage code, but for that same rea-

son an override is difficult to trackand debug. They are more troublewhen re-integrating new vendorreleases—none of your compari-

t the override as a change, but it mayendor changes in the new release.usually a reason for the inheritance ofn override seems atmactive, be sure that’t actually go into the inherited method,ge arguments or return objects begins told be avoided. Constraining argumentssuch as requiring that an argument beany kind of collection, might work for

e, but it is certain to eventually breakthat didn’t share your assumption.shape, or the number or ordering ofis one of the most invasive changes

is to be avoided, Adding instance vari-t terrible, but if such a change is reallythe time it is because the fundamentals is being changed—behavior changes

are for!ass interf~es is really dangerous. Youll uses in your context, but thhd-partyow about your change, and your

next release certainly won’t knowhis extreme are required, be certain toll, to ease the inevitable problems thatlt.

ngesatter categories mentioned above, itly important to factor your change in

27

Page 28: Smalltalk Volume 4 Issue 9 - ESUG

Group”

The American Funds Group is one of the mostsuccessful mutual fund or animations in the world.

L1Since 1931,we have provi ed our shareholderswithconsistently superior investment results and out-standing service. Share in the continued growth ofour Norfolk, VA OffIce.

We have been a financial indust~ leader in Small-talk developmentfor over 5 years. We are currentlydevelopinga large client serverbasedcustomer serv-ice system. This application is being created usingthe latest object oriented methods and is in the be-ginning stages of development. Ideal candidates willhave the opportunity to be a part of the design teamwhose responsibilities will include these initialphases of development.

We offer a competitive salary and excellentbenefits package including

● Medical, dental and vision care coverage. Educatioti assistance. An outstanding company-paid retirement plan

Positions are currently available for:

This positon requires 2 to 5 yeara of Smalltalk ex-perience including 00A and OOD. Job responsi-bilities will include leading in the overall designand creation of class and object hierarchies.

*_,,..,,:::, ..

In this position, you will develop GUI baaed clientserver applications. At least one year of Smalltalk ex-perience is required.

If you are interested in applying for any of thepositions listed above, please aend your resumeand salary history to:

The American Funds Group(Please specify position)5300 Robin Hood RoadNorfo@ Wrginia 23513

EQUAL OPPORTUNIW EMPUIYER

entd mporationIhalprovkksanericellenlworkingenviromne;ttialwill

ckallengeycarratdilii andsharpenyourskills.We ore K.SC.We on yearfularr.

f%sently, we are ding 10aupoenlourteclmicalbninkrgandmowhingsMswilfrprofessionalswhohavetwo@usyearsof demmtstratedeqmi-

eomwith00A&D, IBM Srnalhrdkm VktrdAgerParcPlaceVisudkk&DigitalkSmalltalW~ and Envy.

Ass leader in supplyingmu htum 500 cliint Lmsewith Objd Oriented

MakeNo Compromises.Join a leader inObjectTechnology.WareKnowledgeSystemsGnpomtiaLhe mlmmledgedleaderinobjmx Oriented Tedrmlogywvires.Workingmrtbetuningedgeoftecb-mlogy,wearepoisedtomovetogmalerheighlsoftecknicaldiversky,clientserviceability, ad employer opporh@. We are pmfesaional, team

~-~ ~vm 10excellence, but roostof all, we are an emolovA-

WhMions,Knowled& Syslmts Cufmradon is able 10offer a very cont@i-tive salary, so excdenl lmetils pdrage and mmy opporluniliis to growwith the Ie&r. Pke seodlfm ymr rover le4ter,mume, sod salaryrtqirements tm Knowledge SystemsCmpora600, 4KII Wemn Parkwayr

Cary,NC 27513; or cdl (919) 431_, Fax(919)677-3 [email protected] EqladOpmmlnityEqloyerl

SMALLTALKPOSITIONS

DIGITALK is seeking experienced Smalltalk instructors andconsultants for our world-class Professional Services team.At DIGITALK you will work with one. of the world’s lead-ing development teams, use state-of-the-art prnducts and

assist companies on the forefront of adopting object tech-

nology in client-server applications.

Requirements for Senior Consultants are: solid experience

with Smalltalk (3-5 years) and/or PARTS Workbench

Experience. 00ALD experience and GUI design skills.

Mainframe database experience is a big plus. Requirements

for instructors are: previous training experience ‘in a relat-

~d field (2-4 years), understanding of 00 cnncepts and

5malltalk.

Positions are available in varioua sites throughout the U.S.

Compensation includes competitive salary, bonuses, equity

participation, 401(k) and family medical coverage. All posi-

tinna require travel. DIGI’14LK is an equal opportunity

employer.

Please forward your resume to:

Dkector of Enterprise ServicesDigitalk, Inc.

7585 S.W. Mohawk DriveTmdatin, OR 97062faxl (503) 691-2742

internet: hollvfddirritalk, com

28The Smalltalk Report

Page 29: Smalltalk Volume 4 Issue 9 - ESUG

.bjedSpace

ObjectTechnologyProfessionalsObjectSpace, Inc. is a cutting-edge leader in the

object-oriented arena with awesome technological capabilityand extraordinarily talented people dedicated to the creation

and deployment of advanced technologies.

Progressive growth has created immediate career opportunitiesfor Obiect Tec~ who are highly technical and are

committed to excellence.

We have requirements for Object Technologists who havestrong object-oriented backgrounds and two years of

experience in one or more of the following:

Smalltalk Distributed Smalltalkc++ EsrdWorks

Fusion EsrualAgeRumbaugh Booth

We offer competitive compensation, performance-based andtravel bonuses rmd a complete benefits package.

For consideration, send a resume to:

ObjectSpace,Inc.14881 Quorum Drive, Suite 400

Dallas, Texas 752401-800-OBJECT1

Fax (214) 663-3959jobs @objectspace. com

. . LISTEN, even though you’re not “looking” now.Exceptional career-advancing opportunities for aparticular person occur infrequently. The best time toinvestigate a new opportunity is when you don’t have to!

You cart increase your chances of becoming aware ofsuch opportunities by getting your resume into our full-text database which indexes every word in your resume.(We use a scanner and OCR software to enter it.) Later,we will advise you when one of our search assignmentsis art exact match with your expcriertw and interests, a freeservice to you.

Founded in 1974, we are a San Francisco Bay Areabased employer-retained recruiting and placement firmspecializing in Object-Oriented software developmentprofessionals at the MTS to Director level throughoutthe U.S. and Canada.

We would like to establish a relationship with you forthe long-term, as we have with hundreds of other

Object-Oriented professionals.

$&?@ $A $~Established 1974

Internet [email protected] URL hltp//www.d.naLcom/-lji

voice 510-787-2110 FAX/BBS(8Nl} 510-787-3191P.O. Box S17,Crockett, Cdihmi. 94525

If you want to see the Future, take a look at our past: 185

years of smart decisions have made us one of the few, true

long-term success stories. That success continues today

with superb ratings and bold new products, making ITT

Hartford the smart decision for those with an eye on their

future. We are currently seeking technical professionals to

join our Gmporate Object Group located in Hartford, CT.

The selected candidate will be responsible for the constmc-

tion of corporate-level “infrastructure” object classes to pro-

vide utility functions and be leveraged by segment developers.

You will review and harvest classes deemed appropriate For

inclusion into the class library Other duties include work-

ing with the Corporate Object Group and assisting project

Y

teams in velnping classes to meet specific needs. Ex@ence

with +, Smalltalk and relational database products is

~e cial. Experience developing classes in an insurancez

~-”to in;eg;ate Smalltalk classes into

re required.

-~’”

Id

e responsible fnr ject database

%

&pning f. . e corporation. Duti ~include ins . ,

!3+ .pg SII Obj=t ~ ase for the o-

9ing product “-

support pers

Smalltalk and”

is required. Experien

&qThis individual will SZS;q

trahon of class speci “o

repository, Tasks in he]

1easy navigation th

multiple classes wi

for Iibrsry users

internal publicati

library is desiq

ParcPlace VI?

July-August 1995 29

Page 30: Smalltalk Volume 4 Issue 9 - ESUG

If you’d like to play a

significant role in a large

object-oriented project...we’d like to hear from you. 00CL’S IRIS-2 project

takes a strong software architecture approach to

building an integrated information infrastructure.

The IRIS2 development team is based in SantaClara, CA. OOCL, an industry leader in the container-ized shipping business with over 140 offices around

the world and 2000 employees, offers reliable trans-portation services to its customers via a global net-work of ocean and intermodal routes.

Smalltalk Developers

We are looking for experienced VisualWorks/

Smalltalk system analysts/designers and developers

with strong interest in domain modeling, user inter-face design, and persistence and distribution tech-nologies. You will have the opportunity to work with

a highly skilled, highly motivated Smalltalk develop-ment team in an environment which emphasizestechnical excellence, teamwork and professionalgrowth. If you are 00 fluent and eager to join theleague of the very best in Smalltalk development,we’d like to talk to you.

Productivity Tools and Release Engineer

We are building a team to provide the 00 tools andinfrastructure for software delivery. If you have expe-rience in configuration management, release engi-neering, and tools and utilities development, you canplay a role in helping us build quality into our devel-

opment process.

00CL offers competitivecompensationpackagesand thetechnicaland analyticalchallengesyou expect in a state-of-the-artenvironment.Applyby sendingyour resumetoLori Motko via a-mail, indicating (he position of interest, at

motkolo @ oocl.tom, or mail to 00CL, 2860 San Tomas

Expwy, Santa Clara, CA 95051, or fax to (406) 654-8196,

Dedicated to Quality Service

Smalltalk RothWell Smalltalk RothWell

SMALLTALKPROFESSIONALS

This is your opportunity to jointhe finest team of Smalltalkprofessionals in the country!

RothWell Internationalhas challenging projectsacross the US and abroad.

Excellent compensation andimmediate participation in theEmployee Stock Plan.-.

(CHECK OUT OURw NEW WEB PAGE!)

http:llwww.nvi.cornl

BOX 270566 Houston TX 77277

(713) 660-8080;Fax (713) 661-1156

(800) 256-9712; [email protected] RothWell Smalltalk RothWell

objectWare Corporation is a Chicago-basedsoftware consulting company with nationwidepresence in the telecommunications industry,Qualified individuals will have hands-onSmalltalk experience and familiarity with OMT.

Experience with UNIX and ODBMS are pre-ferred.

We will challenge you to enhance your skills,while providing you an opportunity to grow.objectWare offers salaries commensurate withyour experience. For further consideration pleasesubmit your resume with salary requirements to:

Sam CinquegraniobjectWare Corporation1618 N. Orchard StreetChicago, Illnois 60614e-mail: flda@interaccess. com

objectWae Corporation

30 The Smalltalk Report

Page 31: Smalltalk Volume 4 Issue 9 - ESUG

MANACINGOBJECTScontinued~m page 27

away that makes it easy to back out. For example, if youwant to add some special processing to what happenswhen you compile a method, it is tempting to simply putyour modifications irdine, but a better way is to make allyour modifications in a separate method, then condition-ally send that message if it exists, by using testing meth-ods such as respondsTo: or canUnderstand:. Note that thesetests can have a performance impact, but so can a brokenchange that you can’t isolate!

This “base-change boundary” is one of the few placeswe tolerate the use of isKindOfi.Using isKindOfi as part of your

We use two techniqimage modules; both hplace. The simplest is toexample becomes “RI .have a number of changoften prepend some i“Bytesmiths R1,43.0. ” Ewith new vendor releases

At the system level, aevery change or additionmethod, is highly useful.

program logic is contrary togood O-O design, because it “Keep in mind that yourimposes the sending method’s base image changes are notviewpoint on another objectrather than obtaining the other the main development stream;object’s willing collaboration.

they are a branch!”However, at the base-changeboundary, isKindOfi is useful fortesting the existence of basechanges, so that they can be easily backed out withoutchanging the base once again. It still isn’t good O-O design,but it’s a bit more justified when used to veri@ moduleinterface boundaries.

Another useful technique for managing changes is tomake them conditional upon an arbitrary “signature”method. For example, you might implement hasBeen-Hacked in Object, and then bracket your changes inside“(selfrespondsTo: #hasBeenHacked) ifllue: [...].” This way ifa particular module of enhancements is present, they areused by changed base methods, but if not, the basechanges skip the conditional changes.

Positive identificationThere are two principle reasons to keep track of exactlywhat you changed: it will make your integration with thenext new release from the vendor less painful, and it willhelp you to back out a change if it proves to be a mistake,Identification needs to happen at the method, module,and system levels.

For method changes, we’ve implemented a “hot key”that inserts “Modifiedby [user] on [date]: .“ where “user” and“date” are properly filled in, and the tumor is positionedbefore the period to encourage the user to further describethe change. We use this two ways. In a short method, wesimply place it after the normal method comment. In along method, we bracket our changes by placing this hot-key comment both before and after the change.

Common code management systems allow versionnames for code modules. Keep in mind that your baseimage changes are not the main development stream;they are a branch! So if you modify a code componentthat the vendor named R1.43, you should not call yourversion R1.44 because that will most likely collide with thevendor’s next release!

to demonstrate this in aing why and how the chuman activity.

Organizational issuesIn organizations withteams, there is usually ahas the authority to decidthe base image will be“Keeper” is particularly icorporate-wide version

A trial period for chacannot always tell thatall the development tereports a problem withKeeper can then modi@the problem.

Even when there isintegrity of the base imawho is the sole developethe base classes, also basrience, a trial of about onweeks) is a good idea.

CONCLUSIONNow that you know howthat is limited in scopintegratable, documentreturn you to your regunext issue, we’ll give youto practice with as we pruous documentation.”

July-August 1995

ues for naming changed baseelp indicate a branch has takenappend a “dot level,” so the above

43.0”. This can get messy if youes from different sources, so we

dentifying information, such asither way makes re-integration

easier.separate document that records

, organized by module, class, andThese release notes are necessaryeven if your source code man-agement system provides aver-sion comparison tool; it is veryuseful to have a linear docu-ment to review when thingsstart breaking!

In some cases, your codemanagement comparison facil-ities can be harnessed to surveychanges and build templatesfor these release notes (we planfuture column), but document-

hange was made will remain a

multiple Smalltalk developmentn individual or a committee thate whether a particular change to

allowed. This role of base imagemportant when there is a sharedof all base image classes.nges is a good idea. The Keepera particular change is benign toams’ applications. If any teama change to the base image, the

or back out the change to correct

only one Smalltalk team, thege is usually guarded by a Keeper,r allowed to release changes toed on a trial period. In our expe-e development cycle (six to eight

to make base changes in a waye, conditional, identifiable, re-ed, and “back-outable,” welarly scheduled column. In thesome actual base image changesoceed with examples of “contin-

31

Page 32: Smalltalk Volume 4 Issue 9 - ESUG

JUST PUB II MIID!

AbouttheAuthor,,,,Mark Lorenz is the founder andpresidentof Hatteras%~ftwme,Inc.d company that specializesin helpingprojectsuseobject

technology successfully.‘Th; author ha_salreadypublishedtwo popularbooks onobjecttechnology entitled OI!.IECT-ORIENTEII

SOHWWREDEVELOPMENTA Pw\mc~I.GUIDEandOR.IEL’T-ORIENTELISommw ME-I-WC-S(PrenticeHall) and also writes a regularcolumn forTHE SMALLTALKREPOKTcalled“ProjectPracticalityies.”

Available at selected book stores.

Distributed by Prentice Hall,

RAPID SOFTWARE DEVELOPMENT WITH 5MALLTALKcovers the spectrumof O-O analysis, design, and implementation techniques andprovides a proven process for architecting large software sys-tems. By using detailed examples of an extended Responsibility-Driven Design (RDD) methodology and Smalltalk, readers willfind techniques derived from real O-O projects that are directlyapplicable to on-going projects of any size.

The author provides readers with specific guidelines that coulddramatically cut costs and keep projects on-time. Specifically,the author provides readers with project patterns that work,illustrations of design patterns, O-O metrics with example codeto test design quality and of course, numerous Smalltalk codeexamples.

Readerswill,,,9

Speed up the development process by fostering reuse

Significantly reduce debugging time

Gain step-by-step instruction on how to makethe object model more robust

Learn how to distribute responsibilities withinthe object model more effectively

Discover a practical day-by-day breakdownof a rapid modeling session

See how to organize the development team most efficiently

n!ilm.

*m.

■ =

■ ■

------------------------ ---------------------------- ----------- --------------- h---------- ----

This book will prove invaluable to anyone interested in speedingup the consistent development of high-quality object-orientedsoftware systems based in Smalltalk.

SIGS BOOKS ORDER FORM~ YES! Pleaserush me copy(ies) of I&m 50FTWARE

DEVELOPME~ WITH S,MAI.LTALKat the low price $24 per

COPY. (ISFIN 1-8 S4L142-1 2-7; Appmx 200 pgs,)

Monry-back Guarantee: [f 1am not completely satistird, 1may returnthe book(s) within 14 days and receive a complete rrfund, promptly andwithout question.

~ Check payable to SIGS Bmks

Q Visa Q American Express Q Mastercard

Card# Exp.

Sigmture

SIIIPPINGANDHmDuNG: For U5 orders, please mtd $5 for shipping and handling;Canada and Mexico ❑kl 510; outside North America add $15. lr.mw.rmm NY 5taIr

residents add appliiablr s-ales tax. Please Aow 4-6 weeks fur delivery,

Address

City/State/Zip

Ccmntry/Wstal Code

Phone Fax

SINDTO:116$Books,P.0,Box99415

(oIlitssywond,Ml08108-9910

m

S I G_SPhone609.WI.960ZFax:609.488.6180 BOO-KS