Docsity

Project for An Eiffel Tutorial - Organization Programming Language | CSE 452, Study Guides, Projects, Research of Programming Languages

Partial preview of the text

Download Project for An Eiffel Tutorial - Organization Programming Language | CSE 452 and more Study Guides, Projects, Research Programming Languages in PDF only on Docsity!

An Eiffel Tutorial

Interactive Software Engineering

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.

4 AN EIFFEL TUTORIAL §

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:

  • Reliability : producing bug-free systems, which perform as expected.
  • Reusability : making it possible to develop systems from prepackaged, high- quality components, and to transform software elements into such reusable components for future reuse.
  • Extendibility : developing software that is truly soft — easy to adapt to the inevitable and frequent changes of requirements and other constraints.
  • Portability : freeing developers from machine and operating system peculiarities, and enabling them to produce software that will run on many different platforms.
  • Maintainability : yielding software that is clear, readable, well structured, and easy to continue enhancing and adapting.

2 GENERAL PROPERTIES

Here is an overview of the facilities supported by Eiffel:

  • Completely object-oriented approach. Eiffel is a full-fledged application of object technology, not a “hybrid” of O-O and traditional concepts.
  • External interfaces. Eiffel is a software composition tool and is easily interfaced with software written in such languages as C, C++, Java and C#.
  • Full lifecycle support. Eiffel is applicable throughout the development process, including analysis, design, implementation and maintenance.
  • Classes as the basic structuring tool. A class is the description of a set of run-time objects, specified through the applicable operations and abstract properties. An Eiffel system is made entirely of classes, serving as the only module mechanism.
  • Consistent type system. Every type is based on a class, including basic types such as integer, boolean, real, character, string, array.
  • Design by Contract. Every system component can be accompanied by a precise specification of its abstract properties, governing its internal operation and its interaction with other components.
  • Assertions. The method and notation support writing the logical properties of object states, to express the terms of the contracts. These properties, known as assertions, can be monitored at run-time for testing and quality assurance. They also serve as documentation mechanism. Assertions include preconditions, postconditions, class invariants, loop invariants, and also appear in “check” instructions.

§2 GENERAL PROPERTIES 5

  • Exception handling. You can set up your software to detect abnormal conditions, such as unexpected operating system signals and contract violations, correct them, and recover
  • Information hiding. Each class author decides, for each feature, whether it is available to all client classes, to specific clients only, or just for internal purposes.
  • Self-documentation. The notation is designed to enable environment tools to produce abstract views of classes and systems, textual or graphical, and suitable for reusers, maintainers and client authors.
  • Inheritance. You can define a class as extension or specialization of others.
  • Redefinition. An inherited feature (operation) can be given a different implementation or signature.
  • Explicit redefinition. Any feature redefinition must be explicitly stated.
  • Subcontracting. Redefinition rules require new assertions to be compatible with inherited ones.
  • Deferred features and classes. It is possible for a feature, and the enclosing class, to be specified — including with assertions — but not implemented. Deferred classes are also known as abstract classes.
  • Polymorphism. An entity (variable, argument etc.) can become attached to objects of many different types.
  • Dynamic binding. Calling a feature on an object always triggers the version of the feature specifically adapted to that object, even in the presence of polymorphism and redefinition.
  • Static typing. A compiler can check statically that all type combinations will be valid, so that no run-time situation will occur in which an attempt will be made to apply an inexistent feature to an object.
  • Assignment attempt (“type narrowing”). It is possible to check at run time whether the type of an object conforms to a certain expectation, for example if the object comes from a database or a network.
  • Multiple inheritance. A class can inherit from any number of others.
  • Feature renaming. To remove name clashes under multiple inheritance, or to give locally better names, a class can give a new name to an inherited feature.
  • Repeated inheritance : sharing and replication. If, as a result of multiple inheritance, a class inherits from another through two or more paths, the class author can specify, for each repeatedly inherited feature, that it yields either one feature (sharing) or two (replication).
  • No ambiguity under repeated inheritance. Conflicting redefinitions under repeated inheritance are resolved through a “selection” mechanism.
  • Unconstrained genericity. A class can be parameterized, or “generic”, to describe containers of objects of an arbitrary type.

§3 THE SOFTWARE PROCESS IN EIFFEL 7

3 THE SOFTWARE PROCESS IN 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.

Clusters and the cluster model

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

8 AN EIFFEL TUTORIAL §

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

10 AN EIFFEL TUTORIAL §

Compilation technology

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.

Quality and functionality

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,

§4 HELLO WORLD 11

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.

4 HELLO WORLD

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

§5 THE STATIC PICTURE: SYSTEM ORGANIZATION 13

5 THE STATIC PICTURE: SYSTEM ORGANIZATION

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.

Systems

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.)

Classes

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:

  • In a banking system, a class ACCOUNT may have features such as deposit, adding a certain amount to an account, all_deposits, yielding the list of deposits since the account’s opening, and balance, yielding the current balance, with properties stating that deposit must add an element to the all_deposits list and update balance by adding the sum deposited, and that the current value of balance must be consistent with the lists of deposits and withdrawals.
  • A class COMMAND in an interactive system of any kind may have features such as execute and undo, as well as a feature undoable which indicates whether a command can be undone, with the property that undo is only applicable if undoable yields the value true.

14 AN EIFFEL TUTORIAL §

  • A class LINKED_LIST may have features such as put, which adds an element to a list, and count, yielding the number of elements in the list, with properties stating that put increases count by one and that count is always non-negative.

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.

Class relations

Two relations may exist between classes:

  • You can define a class C as a client of a class A to enable the features of C to rely on objects of type A.
  • You may define a class B as an heir of a class A to provide B with all the features and properties of A, letting B add its own features and properties and modify some of the inherited features if appropriate.

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.

16 AN EIFFEL TUTORIAL §

External software

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.

6 THE DYNAMIC STRUCTURE: EXECUTION MODEL

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

§6 THE DYNAMIC STRUCTURE: EXECUTION MODEL 17

Objects, fields, values and references

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:

  • When a field is an object, it will in most cases be an atomic object, as on the figure where the first field from the top is an integer and the third a character. But a field can also be a composite object, in which case it is called a subobject.
  • A reference is either void or uniquely identifies an object, to which it is said to be attached. In the preceding figure the second field from the top is a reference — attached in this case, as represented by the arrow, to the enclosing object itself. The bottom field is a void reference.

235

'C'

Composite object

( with 4 fields including self- reference and void reference )

§6 THE DYNAMIC STRUCTURE: EXECUTION MODEL 19

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.

A simple class

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

20 AN EIFFEL TUTORIAL §

(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:

  • Only deposit and deposit_count, which include a do … clause, are routines.
  • balance and all_deposits, which are simply declared with a type, are attributes. Note that even for attributes it is recommended to have a header comment.
  • Routine deposit_count is declared as returning a result (of type INTEGER); so it is a function. Routine deposit has no such result and hence is a procedure.

Creating and initializing objects

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