TweetFollow Us on Twitter

September 90 - Assertions in MacApp

Assertions in MacApp

James Plamondon

Have you ever loved someone you couldn't have? Someone of such rare grace, beauty, and elegance that his or her charms were beyond the appreciation of many of your peers, whose tastes, shall we say, were not nearly as refined and discriminating as your own?

Such is my love affair with Bertrand Meyer's object-oriented language, Eiffel. Well described in his book, Object-oriented Software Construction (Prentice-Hall, 1988), Eiffel is a paragon of elegance, power, and simplicity. Every time I waste an hour fighting Pascal's USES clause, or stuff some routine into UObject to get around single inheritance, or write yet another list class (because TList only handles object references), or consider (out of desperation, not desire) turning to C++, I long for the simple solutions Eiffel would provide.

But my love is as hopeless as it is deep-there is, at the time of this writing, no implementation of Eiffel available for the Mac. There's a stripped-down A/UX version nearing completion, and a full Mac OS version planned for a January release-however, these are still in vapor form. Until they solidify-and mature into the complete implementations they almost certainly will not be, in their initial releases-my love must remain unrequited, its fires banked, but still glowing.

Until then, I will continue to console myself with Object Pascal. There are three reasons why I do so:

  • Object Pascal has a sterling virtue that even Eiffel can't claim: it's the lingua franca of MacApp.
  • If you can't be with the one you love, baby… love the one you're with!
  • MacApp's comprehensive utilities mask some of Object Pascal's deficiencies such that, if the bar's dark, the beer's cheap, and you squint a little bit, Object Pascal can look just enough like Eiffel to get you interested.

I'm going to address one aspect of that resemblance in this annotated compilation of MacApp.Tech$ links: assertions. An integral part of Eiffel, assertions are the means by which the semantics of an abstract data type are enforced. For example, Eiffel's preconditions (one kind of assertion) ensure that a method is never called with invalid arguments. Likewise, postconditions ensure that a routine has always done what it was supposed to have done before it returns. Loop variants and invariants ensure loop termination. While not allowing the direct production of formal, mathematical proofs directly from code, the Eiffel assertion mechanism is a powerful weapon in the commercial programmer's arsenal against bugs.

Neither Object Pascal nor MacApp directly address these issues. However, hidden away in the purdah of UMacAppUtilities, unmentioned, undocumented, and generally ignored, are the seeds of an assertion mechanism: the Assertion() global routine, and the gPrecondition global constant/variable. The use of these features are the topic of the discussion below.

Finally, I'm going to start this compilation out of sequence, with my response to a link from Mr. Cooley of After Hours Software. His link (which is, unfortunately, missing from the archives) requested an explanation of what assertions are and what they're good for. My response was actually the end of this thread, but in a zen-like manner not uncommon in programming, the end is really the beginning.

Please note that italicized comments in brackets [like these] have been added by me for the purpose of annotation.

5/2/90
POWERUP.ENG Power Up Software,PRT
Dear Mr. Cooley,

Pretty much everything I know about assertions I learned from Bertrand Meyer's book, Object-Oriented Software Construction, published in 1988 by Prentice-Hall.

The first four chapters of this book are the best discussion I've found anywhere of what makes some software "good" and other software "bad," and how OOP facilitates the production of "good" software.

A lot of the rest of the book is a discussion of other OOP issues - multiple inheritance, genericity (aka parameterized types), garbage collection, classes vs. types, exception handling, assertions, etc.. These issues are discussed in the context of Meyer's language, Eiffel, which I think is the greatest programming language ever, because of its elegant encapsulation of all of the ideas presented in the book. [Hear, hear.] (A number of companies are currently planning to produce Eiffel for the Mac; it already is available for A/UX.)

Assertions are statements of fact that are checked at runtime. If the asserted boolean condition evaluates to FALSE, then a run-time exception is raised - essentially a break into the debugger.

Assertions fall into three rough categories: class invariants, pre- and post- conditions, and other assertions.

The class invariant is checked after every method call, to ensure that the basic characteristics of the class are maintained (that an empty stack contains no elements, for example).

A method's preconditions are checked before entry into the method, to make sure that the method is being called in a valid fashion. For example, one cannot meaningfully pop from an empty stack, so the Pop() method would have a precondition stating that the stack was not empty. If it were empty when Pop() was called, then the assertion would be false, and an exception would be raised.

Likewise, a postcondition ensures that the method does what it is supposed to do. Pop() would include a postcondition stating that, after the method was done, the stack would contain one fewer element than before Pop() was called.

Other assertions include loop assertions (variants and invariants) and the check assertion, which is like the Assertion() routine in MacApp.

All of the assertions are present to ensure that the code does what it is supposed to do. They also enhance the code readability and maintainability, by making it crystal clear what each method is supposed to do, and under what circumstances it can be expected to do it.

That's a quick guide to assertions in Eiffel. They existed in other languages before Eiffel - as a number of people have pointed out to me - but the Eiffel implementation is pretty slick, nonetheless. For a more detailed discussion, I'd definitely see Meyer's book.

Looking forward to Mac Eiffel (later this year? Early in '91? That pesky memory manager sure causes problems!),

James Plamondon

[With that overview of assertions out of the way, we can return to the beginning of the thread.]

4/19/9
POWERUP.ENG Power Up Software,PRT
Dear Steve,

I was wandering around in MacApp 2.0B12 today, and I stumbled across a few interesting things that made me think that somebody has been taking a close look at Eiffel.

First, in UFailure, I found an the following procedure:

Assertion(condition: Boolean; description: StringPtr);

which is only ever called in TApplication.Idle(), as follows:

Assertion(gTarget <> NIL, AtStr('gTarget <> nil'));

Then, wandering further, I encountered two variables (or constants, depending on the state of qDebug): gPreCondition and gPostCondition, which are defined in UMacAppUtilities.p and initialized (to TRUE) in DoRealInitToolBox(), which is in UMacAppUilities.inc1.p. These entities are never referred to anywhere else in MacApp.

These look awfully useful - but the fact that they are not used anywhere in MacApp suggests that they are not safe to use in one's application. So, what's up?

James Plamondon

4/19/9
A14 Carnegie Mellon, Rob Chandok,PRA

James writes: I was wandering around in MacApp 2.0B12 today, and I stumbled across a few interesting things that made me think that somebody has been taking a close look at Eiffel.

I find it interesting that people think Eiffel invented assertions programming languages. While Eiffel is "way cool," it isn't the first language to think about assertions.

I find it more useful to think about good features in terms of the abstract concept, since that is the real importance. You can do assert(boolean,string) in any language. We have such a built-in procedure in our Pascal teaching environment. But we didn't get it from Eiffel.

There has been other interesting work in programming languages before Eiffel, although Eiffel is a well thought out language designed by a smart person. Besides, real assertions would and some way of saying "there exists" and "for all." :-)

Rob

4/19/9
ALGER Alger, Jeff,VCA
Rob,

Amen. There is too much "discovery" of old ideas out there, and assertion is one of them. All major languages are Turing machines, so there is no difference between what you can, in theory, do from one language to another. The differences are all in degree of difficulty to accomplish certain objectives versus execution time and space.

On the subject of "for all" and "there exists," that (sigh) would be a welcome addition to Object Pascal, but requires a good deal more infrastructure than OP provides. Specifically, OP does not have the concept of a set of objects, let alone placing all objects into "master" sets based on class or anything else.

I liked the term "syntactic sugar" applied to assertions in Eiffel, but would take that one step further. Objects in OP are, to me, syntactic sugar plus a little bit of dispatch glue, not objects in the same sense as Smalltalk, CLOS, Object Prolog, etc., etc., etc. "Even" C++ allows allocation and deallocation of storage of objects to be determined separately from the behavior of the objects themselves (a class behavior), class variables, and a number of other blue-blood OOP features. In C++, one can at least conveniently superimpose maintenance of class sets and, therefore, "for all" and "there exists," without changing the public interface to a class's objects. C++ has its problems, too, but the point here is that one can and should do MUCH better than OP.

Ah, nothing like stirring up a little controversy in the morning.

Jeff Alger, Exis

4/19/9
V0683 Amoco Tech, Eric Berdahl,VAR

Yes, the Assertion mechanism is nice to have, especially since OPascal doesn't have language support for the mechanism (I actually think that Eiffel's construct is more syntactic sugar than anything else).

[Every expression we write, unless we're writing in machine language, is "syntactic sugar." Implementing assertions at the library level detracts from their utility (compared to implementing them at the language level), even if it can be done. As I tell my son at the dinner table, if you mix your food together on the plate, it loses something, even if it's going to get all mixed up by the time it gets to your stomach!]

If they [assertions] aren't safe to use, you couldn't prove it by me. I've been using assertions for a while with no consequences. Remember, though, that assertions are things that really are conceived of and placed during object design. If they were added anytime after a significant amount of MacApp design took place, they may not be very easily placed.

[Virginity, once lost, is rarely restored.]

Eric Berdahl

4/20/9
POWERUP.ENG Power Up Software,PRT
Dear Rob, Jeff, and Gentlepersons Everywhere,

Touché! You are correct both in that assertions are not new to Eiffel, and that "there is too much re-discovery of old ideas out there." I first encountered language-based assertions in Eiffel, though, and was not aware that they had been supported in any earlier languages. Thank you for your correction.

I am reminded of a girl whom I once overheard asking a friend, "Did you know that Paul McCartney was in a band before Wings?" [Yes, it's a true story, I swear!] [Ed: I must be slow or something. What band?]

James Plamondon

4/19/9
MACAPP.TEST MacApp SQA Team
James,

As one of the people trying to figure out how you ensure the correctness of a product like MacApp, I am intrigued by Eiffel's assertion mechanism. The routine you found (which was there in B9) is a small step, but it's worth noting that since Eiffel has language support for this stuff, they can add things like the "old" and "nochange" notations (p.115 of the good book), as in

ensure
Size = old fSize + 1

Just because MacApp doesn't use a routine doesn't mean you shouldn't (OK, so we forgot the VAR parameter in GetPortTextStyle and didn't catch it because we didn't use it, but anyway...). [So that's why one of my program's features didn't work! I just wrote it yesterday evening, using GetPortTextStyle, and I was wondering what I was doing wrong!]

Please share your suggestions for assertions with us. Do you think we should have a boolean function TObject.ClassInvariant? Homework: Write preconditions and postconditions for TApplication.TrackMouse.

Richard Rodseth, MacApp Quality

4/20/9
POWERUP.ENG Power Up Software,PRT
Dear Richard, et al.,

I would not know where to begin to write preconditions and postconditions for TApplication.TrackMouse()!

Assertions may work best for container classes (stacks, lists, tables, etc.), which have a mathematically definable nature. TList looks like the best place to start using it-especially given the wide use of lists in MacApp.

Now that I know that there are no impediments to the use of the routine Assertion(), I may very well start using Assertion() in my own code. […and so I have; the little buggers are sprinkled though my code like salt on popcorn.]

Of course, it would help if one could change the values of gPreCondition and gPostCondition from the Debug menu… but I'll leave that as an exercise for the reader. [Hint: use the UDebug routine DebugFlag().]

As to TObject.ClassInvariant(), it sounds like a great idea. Perhaps the following suggestion is possible:

  • Add the field fCheckInvariant (a boolean) to TObject (but only if qDebug is true).
  • Allow the user to set the state of TClassName.fCheckInvariant for each class, independently, in the MacApp debugger.
  • If TClassName.fCheckInvariant were true, then the MacApp debugger would call TClassName.ClassInvariant() (polymorphically, of course) after each call to a method of TClassName (other than ClassInvariant()). The MacApp programmer would NOT have to call TClassName.ClassInvariant() herself; that would defeat the purpose.

[Actually, the CheckInvariant flags would probably be better implemented using a table of boolean values, indexed by class ID.]

This might be exceedingly slow, but it would also be exceedingly nifty. The programmer would, of course, have to write her own ClassInvariant() overrides. Likewise, any precondition and postcondition assertions would have to be written by the programmer, and included in her code, since they would vary from method to method.

Now, if we can just add multiple inheritance and genericity to MacApp (while shovelling in some added simplicity, as Steve Friedrich would say), we can make MacApp and Object Pascal a real working system.

Looking forward to a Mac version of ANY LANGUAGE WHICH SUPPORTS ALL THE THINGS I LIKE ABOUT EIFFEL (but not necessarily Eiffel itself-one must keep an open mind, after all), I remain

James Plamondon

4/20/9
A14 Carnegie Mellon, Rob Chandok,PRA

Rich Rodseth's notes about corrrectness are interesting. Here are some more points about assertions.

While Eiffel can do things like

Size = old fSize + 1

doesn't it seem odd that you have to specify that and the code to add 1 to fSize? The difficulty to me is that you don't want two separate representations of your program–specification and implementation. In this case, you have to make sure that both your code and your invariant is correct. Seems like you might introduce bugs in the invariants as easily as in the code.

[…and that's a very good point. I have indeed written incorrect assertions and wondered why the heck they were (a) flagging errors that weren't errors (easily located and fixed), or (b) not flagging real errors (a much more subtle and insidious problem). I am open to suggestion on ways around this, which aren't themselves error-prone.]

But this is the real world, I know. I haven't seen any language that handle this, although I know of some promising research directions.

In addition, the idea of TObject.ClassInvariant is founded in the premise that inheritance requires the subclass to maintain the behavior of the superclass. This is contrary to many uses of inheritance. Let's see if I can rattle off some ideas off the top of my head.

There are two "kinds" of inheritance: protocols and base class. If you inherit in the protocol style, you are basically saying that "subclass S is just another kind of superclass T, with different internal details, and if you send message M to S, it will behave within the definition of T." I can fully define what the "sort" message will do, no matter what subclass of a sortable class I send the message to.

That doesn't jive with TApplication.TrackMouse, which is an example of inheriting in the "base class" style. No one could possible know what the message TrackMouse is going to do for any subclass of TApplication.

Bruce Horn and I have spent much time arguing over these issues. In addition, you might think about inheritance in this way: If you want to enforce pre/post conditions in the superclass, should the superclass control when the OVERRIDDEN methods get called? For example, just because you override DRAW, should that prevent your superclass's DRAW from being called ? What if DRAW is responsible for maintaining the superclass invariant? Imagine a world where a method call could either percolate up via calls to INHERITED (like object pascal) or down from the superclasses (which is similar to wrappers).

Well, that's enough for now. Suffice to say that invariants are tough. We can barely prove tiny programs correct, it's no wonder we don't know how to specify a language even for executing assertions.

[This is certainly true. Meyer has taken a lot of heat about Eiffel's assertions not being a "complete" formal system for automatic generation of proofs of correctness. But it was never intended nor presented to be such a mechanism-rather, it's just a means by which more robust code can be written. They're not perfect, but they're a big step in the right direction-and if you're dying of thirst, even muddy water looks good!]

I remain, as perplexed as ever,
Rob

Annotator's Summary

The UFailure routine Assertion() is there to be used. It is a powerful and convenient means of ensuring that some condition is true at runtime. I use it frequently to check handles vs. NIL, check values for correctness, and anything else that can be summed up in a BOOLEAN statement. If the condition is FALSE at runtime, the program drops into the MacApp debugger, and asks if you want to signal failure. If included in non-debug code, an Assertion() failure signals a silent failure. Using assertions liberally has saved me hours-days, by now-of debugging time.

The Boolean gPrecondition is a global variable (initialized to TRUE) if qDebug is TRUE, else it is a global constant (with the value FALSE). By adding a call to DebugFlag() in your application's initialization routine, you can toggle this flag on and off in the MacApp debugger. To use it, place the assertions which check a routine's arguments for validity inside an IF gPrecondition statement. In qDebug mode, these assertions will only be checked if the variable gPrecondition (as set by you in the debugger) is TRUE. In non-qDebug mode, gPrecondition is a constant with the value FALSE, so the assertions are stripped out by the linker.

Eiffel is not a perfect language; even blinded by infatuation as I am, I can see that. But Object Pascal-whose charms have long since begun to fade-could do far worse than to imitate Eiffel's standard of beauty.

[Ed: James can be contacted (for what would no doubt be a lengthy discussion] at AppleLink address POWERUP.ENG.]

 
AAPL
$116.47
Apple Inc.
+0.16
MSFT
$47.98
Microsoft Corpora
-0.72
GOOG
$537.50
Google Inc.
+2.67

MacTech Search:
Community Search:

Software Updates via MacUpdate

Cobook 3.0.7 - Intelligent address book....
Cobook Contacts is an intuitive, engaging address book. Solve the problem of contact management with Cobook Contacts and its simple interface and powerful syncing and integration possibilities.... Read more
StatsBar 1.9 - Monitor system processes...
StatsBar gives you a comprehensive and detailed analysis of the following areas of your Mac: CPU usage Memory usage Disk usage Network and bandwidth usage Battery power and health (MacBooks only)... Read more
Cyberduck 4.6 - FTP and SFTP browser. (F...
Cyberduck is a robust FTP/FTP-TLS/SFTP browser for the Mac whose lack of visual clutter and cleverly intuitive features make it easy to use. Support for external editors and system technologies such... Read more
Maya 2015 - Professional 3D modeling and...
Maya is an award-winning software and powerful, integrated 3D modeling, animation, visual effects, and rendering solution. Because Maya is based on an open architecture, all your work can be scripted... Read more
Evernote 6.0.1 - Create searchable notes...
Evernote allows you to easily capture information in any environment using whatever device or platform you find most convenient, and makes this information accessible and searchable at anytime, from... Read more
calibre 2.11 - Complete e-library manage...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital... Read more
Herald 5.0.1 - Notification plugin for M...
Note: Versions 2.1.3 (for OS X 10.7), 3.0.6 (for OS X 10.8), and 4.0.8 (for OS X 10.9) are no longer supported by the developer. Herald is a notification plugin for Mail.app, Apple's Mac OS X email... Read more
Firetask 3.7 - Innovative task managemen...
Firetask uniquely combines the advantages of classical priority-and-due-date-based task management with GTD. Stay focused and on top of your commitments - Firetask's "Today" view shows all relevant... Read more
TechTool Pro 7.0.6 - Hard drive and syst...
TechTool Pro is now 7, and this is the most advanced version of the acclaimed Macintosh troubleshooting utility created in its 20-year history. Micromat has redeveloped TechTool Pro 7 to be fully 64... Read more
PhotoDesk 3.0.1 - Instagram client for p...
PhotoDesk lets you view, like, comment, and download Instagram pictures/videos! (NO Uploads! / Image Posting! Instagram forbids that! AND you *need* an *existing* Instagram account). But you can do... Read more

Latest Forum Discussions

See All

Ubisoft Gives Everyone Two New Ways to E...
Ubisoft Gives Everyone Two New Ways to Earn In-Game Stuff for Far Cry 4 Posted by Jessica Fisher on November 21st, 2014 [ permalink ] | Read more »
Golfinity – Tips, Tricks, Strategies, an...
Dig this: Would you like to know what we thought of being an infinite golfer? Check out our Golfinity review! Golfinity offers unlimited ways to test your skills at golf. Here are a few ways to make sure your score doesn’t get too high and your... | Read more »
Dark Hearts, The Sequel to Haunting Meli...
Dark Hearts, The Sequel to Haunting Melissa, is Available Now Posted by Jessica Fisher on November 21st, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Meowza! Toyze Brings Talking Tom to Life...
Meowza! | Read more »
Square Enix Announces New Tactical RPG f...
Square Enix Announces New Tactical RPG for Mobile, Heavenstrike Rivals. Posted by Jessica Fisher on November 21st, 2014 [ permalink ] With their epic stories and gorgeous graphics, | Read more »
Quest for Revenge (Games)
Quest for Revenge 1.0.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.0 (iTunes) Description: The great Kingdom of the west has fallen. The gods ignore the prayers of the desperate. A dark warlord has extinguished... | Read more »
Threadz is a New Writing Adventure for Y...
Threadz is a New Writing Adventure for You and Your Friends Posted by Jessica Fisher on November 21st, 2014 [ permalink ] In the tradition of round-robin storytelling, | Read more »
SteelSeries Stratus XL Hardware Review
Made by: SteelSeries Price: $59.99 Hardware/iOS Integration Rating: 4 out of 5 stars Usability Rating: 4.5 out of 5 stars Reuse Value Rating: 4.25 out of 5 stars Build Quality Rating: 4.5 out of 5 stars Overall Rating: 4.31 out of 5 stars | Read more »
ACDSee (Photography)
ACDSee 1.0.0 Device: iOS iPhone Category: Photography Price: $1.99, Version: 1.0.0 (iTunes) Description: Capture, perfect, and share your photos with ACDSee. The ACDSee iPhone app combines an innovative camera, a powerful photo... | Read more »
ProTube for YouTube (Entertainment)
ProTube for YouTube 2.0.2 Device: iOS Universal Category: Entertainment Price: $1.99, Version: 2.0.2 (iTunes) Description: ProTube is the ultimate, fully featured YouTube app. With it's highly polished design, ProTube offers ad-free... | Read more »

Price Scanner via MacPrices.net

Save up to $400 with Apple refurbished 2014 1...
The Apple Store has restocked Apple Certified Refurbished 2014 15″ Retina MacBook Pros for up to $400 off the cost of new models. An Apple one-year warranty is included with each model, and shipping... Read more
New 13-inch 1.4GHz MacBook Air on sale for $8...
 Adorama has the 2014 13″ 1.4GHz/128GB MacBook Air on sale for $899.99 including free shipping plus NY & NJ tax only. Their price is $100 off MSRP. B&H Photo has the 13″ 1.4GHz/128GB MacBook... Read more
Apple Expected to Reverse Nine-Month Tablet S...
Apple and Samsung combined accounted for 62 percent of the nearly 36 million branded tablets shipped in 3Q 2014, according to early vendor shipment share estimates from market intelligence firm ABI... Read more
Stratos: 30 Percent of US Smartphone Owners t...
Stratos, Inc., creator of the Bluetooth Connected Card Platform, has announced results from its 2014 Holiday Mobile Payments Survey. The consumer survey found that nearly one out of three (30 percent... Read more
2014 1.4GHz Mac mini on sale for $449, save $...
 B&H Photo has lowered their price on the new 1.4GHz Mac mini to $449.99 including free shipping plus NY tax only. Their price is $50 off MSRP, and it’s the lowest price available for this new... Read more
Check Apple prices on any device with the iTr...
MacPrices is proud to offer readers a free iOS app (iPhones, iPads, & iPod touch) and Android app (Google Play and Amazon App Store) called iTracx, which allows you to glance at today’s lowest... Read more
64GB iPod touch on sale for $249, save $50
Best Buy has the 64GB iPod touch on sale for $249 on their online store for a limited time. Their price is $50 off MSRP. Choose free shipping or free local store pickup (if available). Sale price for... Read more
15″ 2.2GHz Retina MacBook Pro on sale for $17...
 B&H Photo has the 2014 15″ 2.2GHz Retina MacBook Pro on sale for $1799.99 for a limited time. Shipping is free, and B&H charges NY sales tax only. B&H will also include free copies of... Read more
New Logitech AnyAngle Case/Stand Brings Flexi...
Logitec has announced the newest addition to its suite of tablet products — the Logitech AnyAngle. A protective case with an any-angle stand for iPad Air 2 and all iPad mini models, AnyAngle is the... Read more
Notebook PC Shipments Rise Year-Over-Year as...
According to preliminary results from the upcoming DisplaySearch Quarterly Mobile PC Shipment and Forecast Report, the global notebook PC market grew 10 percent year-over-year in Q3’14 to 49.4... Read more

Jobs Board

*Apple* Solutions Consultant (ASC)- Retail S...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Project Manager, *Apple* Financial Services...
**Job Summary** Apple Financial Services (AFS) offers consumers, businesses and educational institutions ways to finance Apple purchases. We work with national and Read more
*Apple* Store Leader Program - College Gradu...
Job Description: Job Summary As an Apple Store Leader Program agent, you can continue your education as you major in the art of leadership at the Apple Store. You'll Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.