




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































































Manual identification
Title: An Eiffel Tutorial , ISE Technical Report TR-EI-66/TU.
Publication history
First published July 2001. Corresponds to release 5.0 of the ISE Eiffel environment.
Author
Bertrand Meyer.
Software credits
See acknowledgments in book Eiffel: The Language.
Cover design
Rich Ayling.
Copyright notice and proprietary information
Copyright © Interactive Software Engineering Inc. (ISE), 2001. May not be reproduced in any form (including electronic storage) without the written permission of ISE. “Eiffel Power” and the Eiffel Power logo are trademarks of ISE. All uses of the product documented here are subject to the terms and conditions of the ISE Eiffel user license. Any other use or duplication is a violation of the applicable laws on copyright, trade secrets and intellectual property.
Special duplication permission for educational institutions
Degree-granting educational institutions using ISE Eiffel for teaching purposes as part of the Eiffel University Partnership Program may be permitted under certain conditions to copy specific parts of this book. Contact ISE for details.
About ISE ISE (Interactive Software Engineering) helps you produce software better, faster and cheaper. ISE provides a wide range of products and services based on object technology, including ISE Eiffel, a complete development environment for the full system lifecycle. ISE’s training courses, available worldwide, cover key management and technical topics. ISE’s consultants are available to address your project needs at all levels. ISE’s TOOLS (Technology of Object-Oriented Languages and Systems) conferences, http://www.tools- conferences.com , are the meeting point for anyone interested in the software technologies of the future. ISE originated one of the earliest .NET products and offers a full range of .NET services and training at http://www.dotnetexperts.com. For more information Interactive Software Engineering Inc. ISE Building, 360 Storke Road Goleta, CA 93117 USA Telephone 805-685-1006, Fax 805-685- Internet and e-mail ISE maintains a rich source of information at http://eiffel.com , with more than 1200 Web pages including online documentation, downloadable files, product descriptions, links to ISE partners, University Partnership program, mailing list archives, announcements, press coverage, Frequently Asked Questions, Support pages, and much more. Visit http://contact.eiffel.com to request information about products and services. To subscribe to the ISE Eiffel user list, go to www.talkitover.com/eiffel/users. Support programs ISE offers a variety of support options tailored to the diverse needs of its customers. See http://support.eiffel.com for details.
Although the language is the most visible part, Eiffel is best viewed as a method , which guides system analysts and developers through the process of software construction. The Eiffel method is focused on both productivity (the ability to produce systems on time and within budget) and quality, with particular emphasis on the following quality factors:
Here is an overview of the facilities supported by Eiffel:
Eiffel, as noted, supports the entire lifecycle. The underlying view of the system development lifecycle is radically different not only from the traditional “Waterfall” model (implying a sequence of discrete steps, such as analysis, global design, detailed design, implementation, separated by major changes of method and notation) but also from its more recent variants such as the spiral model or “rapid prototyping”, which remain predicated on a synchronous, full-product process, and retain the gaps between successive steps.
Clearly, not everyone using Eiffel will follow to the letter the principles outlined below; in fact, some highly competent and successful Eiffel developers may disagree with some of them and use a different process model. In the author’s mind, however, these principles fit best with the language and the rest of the method, even if practical developments may fall short of applying their ideal form.
Unlike earlier approaches, the Eiffel model assumes that the system is divided into a number of subsystems or clusters. It keeps from the Waterfall a sequential approach to the development of each cluster (without the gaps), but promotes concurrent engineering for the overall process, as suggested by the following picture:.
Cluster 1 Cluster 2
Cluster n
PROJECT TIME
The cluster model : sequential and concurrent engineering
The Eiffel techniques developed below, in particular information hiding and Design by Contract, make the concurrent engineering process possible by letting the clusters rely on each other through clearly defined interfaces, strictly limiting the amount of knowledge that one must acquire to use the cluster, and permitting separate testing. When the inevitable surprises of a project happen, the project leader can take advantage of the model’s flexibility, advancing or delaying various clusters and steps through dynamic reallocation of resources.
Each of the individual cluster lifecycles is based on a continuous progression of activities, from the more abstract to the more implementation-oriented:
You may view this picture as describing a process of accretion (as with a stalactite), where each steps enriches the results of the previous one. Unlike traditional views, which emphasize the multiplicity of software products — analysis document, global and detailed design documents, program, maintenance reports … —, the principle is here to treat the software as a single product which will be repeatedly refined, extended and improved. The Eiffel language supports this view by providing high-level notations that can be used throughout the lifecycle, from the most general and software- independent activities of system modeling to the most exacting details of implementation tuned for optimal run-time performance.
These properties make Eiffel span the scope of both “object-oriented methods”, with their associated notations such as UML and supporting CASE tools (whereas most such solutions do not yield an executable result), and “programming languages” (whereas most such languages are not suitable for design and analysis).
*V&V: Validation and Verification
Analysis
Design
Implemen- tation
V & V * Genera- lization
Individual cluster lifecycle
The preceding goals benefit from the ability to check frequently that the current iteration is correct and robust. Eiffel supports efficient compilation mechanisms through such mechanisms as the Melting Ice Technology in ISE’s EiffelStudio. The Melting Ice achieves immediate recompilation after a change, guaranteeing a recompilation time that’s a function of the size of the changes , not of the system’s overall size. Even for a system of several thousand classes and several hundred thousand lines, the time to get restarted after a change to a few classes is, on a typical modern computer, a few seconds.
Such a “melt” (recompilation) will immediately catch (along with any syntax errors) the type errors — often the symptoms of conceptual errors that, if left undetected, could cause grave damage later in the process or even during operation. Once the type errors have been corrected, the developers should start testing the new functionalities, relying on the power of assertions — explained in “DESIGN BY CONTRACTTM^ , ASSERTIONS, EXCEPTIONS”, page 38 — to kill the bugs while they are still larvae. Such extensive unit and system testing, constantly interleaved with development, plays an important part in making sure that the “current demo” is trustworthy and will eventually yield a correct and robust product.
Throughout the process, the method suggests maintaining a constant quality level: apply all the style rules, put in all the assertions, handle erroneous cases (rather than the all too common practice of thinking that one will “make the product robust” later on), enforce the proper architecture. This applies to all the quality factors except possibly reusability (since one may not know ahead of time how best to generalize a component, and trying to make everything fully general may conflict with solving the specific problem at hand quickly). All that varies is functionality : as the project progresses and clusters come into place, more and more of the final product’s intended coverage becomes available. The project’s most common question , “Can we ship something yet?”, translates into “Do we cover enough?”, not “Is it good enough?” (as in “Will it not crash?”).
Of course not everyone using Eiffel can, any more than in another approach, guarantee that the ideal just presented will always hold. But it is the theoretical scheme to which the method tends. It explains Eiffel’s emphasis on getting everything right: the grandiose and the mundane, the structure and the details. Regarding the details, the Eiffel books cited in the bibliography include many rules, some petty at first sight, about such low-level aspects as the choice of names for classes and features (including their grammatical categories), the indentation of software texts, the style for comments (including the presence or absence of a final period), the use of spaces. Applying these rules does not, of course, guarantee quality; but they are part of a quality-oriented process,
along with the more ambitious principles of design. In addition they are particularly important for the construction of quality libraries, one of the central goals of Eiffel.
Whenever they are compatible with the space constraints, the present chapter and the rest of this book apply these rules to their Eiffel examples.
When discovering any approach to software construction, however ambitious its goals, it is reassuring to see first a small example of the big picture — a complete program to print the famous “Hello World” string. Here is how to perform this fascinating task in the Eiffel notation.
You write a class HELLO with a single procedure, say make, also serving as creation procedure. If you like short texts, here is a minimal version:
In practice, however, the Eiffel style rules suggest a better documented version:
The two versions perform identically; the following comments will cover the more complete second one.
Note the absence of semicolons and other syntactic clatter or clutter. You may in fact use semicolons to separate instructions and declarations. But the language’s syntax
class HELLO create make feature make is do print ("Hello World%N ") end end
indexing description: "Root for trivial system printing a message" author: "Elizabeth W. Brown" class HELLO create make feature make is -- Print a simple message. do io. put_string ("Hello World ") io. put_new_line end end -- classHELLO
We now look at the overall organization of Eiffel software.
References to ISE-originated libraries appearing in subsequent examples include: EiffelBase , the fundamental open-source library covering data structures and algorithms; the kernel library , a subset of EiffelBase covering the most basic notions such as arrays and strings; and EiffelVision 2 , an advanced graphics and GUI library providing full compatibility across platforms (Unix, Windows, VMS) with native look-and-feel on each.
An Eiffel system is a collection of classes, one of which is designated as the root class. One of the features of the root class, which must be one of its creation procedures, is designated as the root procedure.
To execute such a system is to create an instance of the root class (an object created according to the class description) and to execute the root procedure. In anything more significant than “Hello World” systems, this will create new objects and apply features to them, in turn triggering further creations and feature calls.
For the system to make sense, it must contains all the classes on which the root depends directly or indirectly. A class B depends on a class A if it is either a client of A, that is to say uses objects of type A, or an heir of A, that is to say extends or specializes A. (These two relations, client and inheritance, are covered below.)
The notion of class is central to the Eiffel approach. A class is the description of a type of run-time data structures ( objects ), characterized by common operations ( features ) and properties. Examples of classes include:
We may characterize the first of these examples as an analysis class, directly modeling objects from the application domain; the second one as a design class, describing a high-level solution; and the third as an implementation class, reused whenever possible from a library such as EiffelBase. In Eiffel, however, there is no strict distinction between these categories; it is part of the approach’s seamlessness that the same notion of class, and the associated concepts, may be used at all levels of the software development process.
Two relations may exist between classes:
If C is a client of A, A is a supplier of C. If B is an heir of A, A is a parent of B. A descendant of A is either A itself or, recursively, a descendant of an heir of A; in more informal terms a descendant is a direct or indirect heir, or the class itself. To exclude A itself we talk of proper descendant. In the reverse direction the terms are ancestor and proper ancestor.
The client relation can be cyclic; an example involving a cycle would be classes PERSON and HOUSE, modeling the corresponding informal everyday “object” types and expressing the properties that every person has a home and every home has an architect. The inheritance (heir) relation may not include any cycle.
In modeling terms, client roughly represents the relation “has” and heir roughly represents “is”. For example we may use Eiffel classes to model a certain system and express that every child has a birth date (client relation) and is a person (inheritance).
Distinctive of Eiffel is the rule that classes can only be connected through these two relations. This excludes the behind-the-scenes dependencies often found in other approaches, such as the use of global variables, which jeopardize the modularity of a system. Only through a strict policy of limited and explicit inter-class relations can we achieve the goals of reusability and extendibility.
The subsequent sections will show how to write Eiffel classes with their features. In an Eiffel system, however, not everything has to be written in Eiffel: some features may be external , coming from languages such as C, C++, Java, C# Fortran and others. For example a feature declaration may appear (in lieu of the forms seen later) as
to indicate that it is actually an encapsulation of a C function whose original name is _ fstat. The alias clause is optional, but here it is needed because the C name, starting with an underscore, is not valid as an Eiffel identifier.
Similar syntax exists to interface with C++ classes. ISE Eiffel includes a tool called Legacy++ which will automatically produce, from a C++ class, an Eiffel class that encapsulates its facilities, making them available to the rest of the Eiffel software as bona fide Eiffel features.
These mechanisms illustrate one of the roles of Eiffel: as an system architecturing and software composition tool, used at the highest level to produce systems with robust, flexible structures ready for extendibility, reusability and maintainability. In these structures not everything must be written in the Eiffel language: existing software elements and library components can play their part, with the structuring capabilities of Eiffel (classes, information hiding, inheritance, clusters, contracts and other techniques seen in this presentation) serving as the overall wrapping mechanism.
A system with a certain static structure describes a set of possible executions. The run- time model governs the structure of the data ( objects) created during such executions.
The properties of the run-time model are not just of interest to implementers; they also involve concepts directly relevant to the needs of system modelers and analysts at the most abstract levels.
file_status (filedesc:INTEGER):INTEGER is -- Status indicator forfiledesc external "C" alias "_fstat" end
A class was defined as the static description of a a type of run-time data structures. The data structures described by a class are called instances of the class, which in turn is called their generating class (or just “ generator ”). An instance of ACCOUNT is a data structure representing a bank account; an instance of LINKED_LIST is a data structure representing a linked list.
An object , as may be created during the execution of a system, is an instance of some class of the system.
Classes and objects belong to different worlds: a class is an element of the software text; an object is a data structure created during execution. Although is possible to define a class whose instances represent classes (as class E_CLASS in the ISE libraries, used to access properties of classes at run time), this does not eliminate the distinction between a static, compile-time notion, class, and a dynamic, run-time notion, object.
An object is either an atomic object (integer, real, boolean, double) or a composite object made of a number of fields , represented by adjacent rectangles on the conventional run-time diagrams:
Each field is a value. A value can be either an object or an object reference:
235
'C'
Composite object
( with 4 fields including self- reference and void reference )
argument, such as balance; a query with arguments, such as balance_on ( d), returning the balance at date d, can only be a function.
From the outside, there is no difference between a query implemented as an attribute and one implemented as a function: to obtain the balance of an account a, you will always write a. balance. In the implementation suggested above, a is an attribute, so that the notation denotes an access to the corresponding object field. But it is also possible to implement a as a function, whose algorithm will explore the lists of deposits and withdrawals and compute their accumulated value. To the clients of the class, and in the official class documentation as produced by the environment tools, the difference is not visible.
This principle of Uniform Access is central to Eiffel’s goals of extendibility, reusability and maintainability: you can change the implementation without affecting clients; and you can reuse a class without having to know the details of its features’ implementations. Most object-oriented languages force clients to use a different notation for a function call and an attribute access. This violates Uniform Access and is an impediment to software evolution, turning internal representation changes into interface changes that may disrupt large parts of a system.
The following simple class text illustrates the preceding concepts
indexing description: "Simple bank accounts" class ACCOUNT feature -- Access balance:INTEGER -- Current balance deposit_count:INTEGER is -- Number of deposits made since opening do if all_deposits /=Void then Result :=all_deposits. count end end
(The {NONE} qualifier and the invariant clause, used here to make the example closer to a real class, will be explained shortly. DEPOSIT_LIST refers to another class, which can be written separately using library classes.)
It’s easy to deduce, from a feature’s syntactic appearance, the category to which it belongs. Here:
Classes, as noted, are a static notion. Objects appear at run time; they are created explicitly. Here is the basic instruction to create an object of type ACCOUNT and attach it to x:
feature -- Element change deposit (sum:INTEGER) is -- Addsum to account. do if all_deposits=Void then create all_deposits end all_deposits. extend (sum) balance :=balance + sum end
feature {NONE} -- Implementation all_deposits:DEPOSIT_LIST -- List of deposits since account’s opening. invariant consistent_balance: (all_deposits /=Void) implies (balance =all_deposits. total) zero_if_no_deposits: (all_deposits =Void) implies (balance =0) end -- classACCOUNT
create x