Interfaces for Strongly-Typed Object-Oriented Programming

Total Page:16

File Type:pdf, Size:1020Kb

Interfaces for Strongly-Typed Object-Oriented Programming Interfaces for Strongly-Typed Object-Oriented Programming Peter S. Canning, William R. Cook, Walter L. Hill, Walter G. Olthoff Hewlett-Packard Laboratories P.O.Box 10490, Palo Alto, CA 94303-0971 Abstract of untyped object-oriented languages like Smalltalk. In- terpreting interfaces as types in a polymorphic lambda This paper develops a system of explicit interfaces calculus is our main technique for moving towards that for object-oriented programming. The system provides goal, We have implemented a type-checker for a typed the benefits of module interfaces found in languages programming language and are using it to test the feasi- like Ada and Modula-2 while preserving the expressive- bility and value of interfaces for object-oriented pro- ness that gives untyped object-oriented languages like gramming. Smalltalk their flexibility. Interfaces are interpreted as polymorphic types to make the system sufficiently pow- Explicit interfaces are useful for clarifying the erful. We use interfaces to analyze the properties of in- role of inheritance in object-oriented programming lan- heritance, and identify three distinct kinds of inheritance guages. Using recent work on the semantics of inherit- in object-oriented programming, corresponding to ob- ance, we describe three distinct kinds of inheritance in jects, classes, and interfaces, respectively. Object inter- object-oriented programming, corresponding respective- faces clarify the distinction between interface contain- ly, to objects, classes, and interfaces. Interface inherit- ment and inheritance and give insight into limitations ance is important in reinforcing the difference between caused by equating the notions of type and class in many interface compatibility and implementation inheritance. typed object-oriented programming languages. Interfac- es also have practical consequences for design, specifica- It also gives insight into the limitations of typed ob- tion, and maintenance of object-oriented systems. ject-oriented languages that equate the notions of type and class. 1. Introduction In a more practical vein, this work addresses im- portant needs and opportunities in object-oriented soft- An important contribution of languages like Ada, ware development. At Hewlett-Packard, large-scale ob- Mesa, and Modula-2 is the explicit separation of the in- ject-oriented software development has suggested the terface and implementation of program modules. The in- need for the benefits that interfaces provide. Object in- terface provides a boundary between the implementa- terfaces provide a useful framework for specifying ob- tions of an abstraction and its clients. It limits the jects when designing a system. Checking them should amount of implementation detail visible to clients. It yield significant gains in productivity and quality in ob- also specifies the functionality that implementations ject-oriented software development. Interfaces may also must provide. be the basis of new tools for organizing object-oriented systems. In this paper we develop a system of explicit in- terfaces for object-oriented programming. The primary In Section 2, we review the significance of inter- goal for the system of object interfaces presented here is faces in large-scale software development. Section 3 de- to allow interface compatibility to be checked at com- velops the notion of object interface in contrast with pile-time (eliminating the possibility of certain run- object implementation and shows the essential role time errors) while preserving the power and flexibility played by polymorphic types. Section 4 discusses vari- Permission to copy without fee all or part of this material is granted provided ous forms of inheritance in object-oriented program- that the copies are not made or distributed for direct commercial advantage, ming, and the difference between the interface and im- the ACM copyright notice and the title of the publication and its date appear, plementation hierarchies in typed object-oriented pro- and notice is given that copying is by permission of the Association for Computing Machinery. To copy otherwise, or to republish, requires a fee gramming. Section 5 briefly compares this work with and/or specific permission. other approaches to typed object-oriented programming. 0 1989 ACM 089791-333-7/89/0010/0457 $1.50 October 1-6, 1989 OOPSLA ‘89 Proceedings 457 2, Interfaces ent, they admit an analogous type-theoretic interpreta- tion. In all these cases, interface checking reduces to “The most important recent development in type-checking, for which there is an existing technolo- programming languages is the introduction of gy. Interfaces consisting only of operation names and an explicit notion of interface to stand be- types are weaker than complete behavioral specifica- tween the implementation of an abstraction and its clients.” tions. Nevertheless, this compromise has proven success- ful in practice, both in terms of expressiveness, user ac- Burstall and Lampson, 1984 ceptance and automated support from compilers and pro- When analyzing and designing software systems, gramming environments. interfaces enforce conceptual discipline and provide mod- ular specifications and documentation. Checking interfac- 30, Objects and Their Interfaces es may detect conceptual as well as superficial errors. Interfaces are also used in code to declare or annotate variable or operation names, making programs easier to understand and maintain. They provide for generic mod- 3.1. Introduction ules and allow categorizing implementations, support- In this section we develop the notion of separat- ing reuse and library administration. In all these forms, ing interface from implementation in object-oriented interfaces include the idea of a contractual agreement be- programming. Our language model for object-oriented tween providers and users of system components, and programming is patterned after Smalltalk- [GR83]. what it means for the terms of the agreement to be sat- Object-oriented systems are characterized by objects isfied. On the other hand, the contract is given in an ab- which group together data and the operations for manip- stract form that deliberately disregards details of how ulating that data. The operations, called method& can be to accomplish its provisions. invoked only by sending messages to the object. Sending Ideally, interfaces should contain a formal de- a message names the operation and supplies necessary ar- scription of the behavior of operations, for example as a guments, but does not determine how the operation is logical theory. Module connections would then be vali- implemented, The target of the message (the receiver) dated by theorem proving. There is much work in pro- determines what action takes place when the message is gram specification and validation that is motivated by received. Since the data (instance variables) in an object this model lEM85, GHW85]. However, this approach can be accessed only by the methods of that object, and requires mechanical theorem proving support which is methods can be invoked only by sending messages, ob- currently an obstacle for including it in practical pro- jects are encapsulated data abstractions. gramming languages. Moreover, the application of speci- Our goal is to provide a language with the flexi- fication and validation techniques to object-oriented pro- bility of Smalltalk, but with the additional structure gramming is not yet well understood. and protection that comes from making interfaces ex- Interfaces have been used in a variety of ways in plicit, and verifying the safety of message sends at com- traditional software development. During design, inter- pile-time. The rest of this section describes object im- faces are typically semi-formal descriptions of how an plementations and then object interfaces. The basic ideas abstraction interacts with the rest of a system. Together in this section have appeared in previous work, as dis- with appropriate naming and documentation conven- cussed in Section 5. In our treatment of recursive and tions, they provide partial specifications. In the imple- polymorphic interfaces, we have attempted greater con- mentation phase, interfaces usually describe the names sistency with object-oriented programming. and the parameter and result types of operations sup- plied by a module as in Ada, Mesa, and Modula-2. In Ada, for example, one distinguishes between package 3.2. Object Implementations specification and package body. The package specification As described above, an object is a collection of in- presents an interface as a list of type, procedure and otb- stance variables and methods. Each method provides a er declarations. Explicit interfaces are important in real- concrete implementation of some abstract operation. A izing data abstraction, data encapsulation and separate compilation. method can implement an operation by manipulating the instance variables, giving them new values or sending In Ada, Mesa, and Modula-2, the module inter- messagesto them, or by sending messages to self. Fig- faces can be interpreted as types [BL84]. While the ob- ure 1 shows an example of a definition of an object ject interfaces discussed below are structurally differ- October l-6, 1989 458 OOPSLA ‘89 Proceedings instance will have, the code for each method, and how object origin implements Point to create instances. Figure 3 shows a class for objects variable rho:Real := 0.0 similar to the object from Figure 1. variable theta:Real := 0.0 class polargoint(x:Real, y:Real) method x0 returns
Recommended publications
  • Interface Types for Haskell
    Interface Types for Haskell Peter Thiemann and Stefan Wehr Institut f¨urInformatik, Universit¨atFreiburg, Germany {thiemann,wehr}@informatik.uni-freiburg.de Abstract. Interface types are a useful concept in object-oriented pro- gramming languages like Java or C#. A clean programming style advo- cates relying on interfaces without revealing their implementation. Haskell’s type classes provide a closely related facility for stating an in- terface separately from its implementation. However, there are situations in which no simple mechanism exists to hide the identity of the imple- mentation type of a type class. This work provides such a mechanism through the integration of lightweight interface types into Haskell. The extension is non-intrusive as no additional syntax is needed and no existing programs are affected. The implementation extends the treat- ment of higher-rank polymorphism in production Haskell compilers. 1 Introduction Interfaces in object-oriented programming languages and type classes in Haskell are closely related: both define the types of certain operations without revealing their implementations. In Java, the name of an interface also acts as an interface type, whereas the name of a type class can only be used to constrain types. Interface types are a proven tool for ensuring data abstraction and information hiding. In many cases, Haskell type classes can serve the same purpose, but there are situations for which the solutions available in Haskell have severe drawbacks. Interface types provide a simple and elegant solution in these situations. A modest extension to Haskell provides the simplicity and elegance of interface types: simply allow programmers to use the name of a type class as a first- class type.
    [Show full text]
  • Metaclasses: Generative C++
    Metaclasses: Generative C++ Document Number: P0707 R3 Date: 2018-02-11 Reply-to: Herb Sutter ([email protected]) Audience: SG7, EWG Contents 1 Overview .............................................................................................................................................................2 2 Language: Metaclasses .......................................................................................................................................7 3 Library: Example metaclasses .......................................................................................................................... 18 4 Applying metaclasses: Qt moc and C++/WinRT .............................................................................................. 35 5 Alternatives for sourcedefinition transform syntax .................................................................................... 41 6 Alternatives for applying the transform .......................................................................................................... 43 7 FAQs ................................................................................................................................................................. 46 8 Revision history ............................................................................................................................................... 51 Major changes in R3: Switched to function-style declaration syntax per SG7 direction in Albuquerque (old: $class M new: constexpr void M(meta::type target,
    [Show full text]
  • Chapter 8. Deploying an Osgi Service
    Chapter 8. Deploying an OSGi Service The OSGi core framework defines the OSGi Service Layer, which provides a simple mechanism for bundles to interact by registering Java objects as services in the OSGi service registry. One of the strengths of the OSGi service model is that any Java object can be offered as a service: there are no particular constraints, inheritance rules, or annotations that must be applied to the service class. This chapter describes how to deploy an OSGi service using the OSGi blueprint container. The Blueprint Container ........................................................................................................... 92 Blueprint Configuration ................................................................................................... 93 Defining a Service Bean .................................................................................................. 95 Exporting a Service ........................................................................................................ 98 Importing a Service ...................................................................................................... 104 Publishing an OSGi Service .................................................................................................... 113 Accessing an OSGi Service ..................................................................................................... 118 FUSE ESB Deploying into the OSGi Container Version 4.2 91 Chapter 8. Deploying an OSGi Service The Blueprint Container Blueprint Configuration
    [Show full text]
  • Mixin-Based Programming in C++1
    Mixin-Based Programming in C++1 Yannis Smaragdakis Don Batory College of Computing Department of Computer Sciences Georgia Institute of Technology The University of Texas at Austin Atlanta, GA 30332 Austin, Texas 78712 [email protected] [email protected] Abstract. Combinations of C++ features, like inheritance, templates, and class nesting, allow for the expression of powerful component patterns. In particular, research has demonstrated that, using C++ mixin classes, one can express lay- ered component-based designs concisely with efficient implementations. In this paper, we discuss pragmatic issues related to component-based programming using C++ mixins. We explain surprising interactions of C++ features and poli- cies that sometimes complicate mixin implementations, while other times enable additional functionality without extra effort. 1 Introduction Large software artifacts are arguably among the most complex products of human intellect. The complexity of software has led to implementation methodologies that divide a problem into manageable parts and compose the parts to form the final prod- uct. Several research efforts have argued that C++ templates (a powerful parameteriza- tion mechanism) can be used to perform this division elegantly. In particular, the work of VanHilst and Notkin [29][30][31] showed how one can implement collaboration-based (or role-based) designs using a certain templatized class pattern, known as a mixin class (or just mixin). Compared to other techniques (e.g., a straightforward use of application frameworks [17]) the VanHilst and Notkin method yields less redundancy and reusable components that reflect the structure of the design. At the same time, unnecessary dynamic binding can be eliminated, result- ing into more efficient implementations.
    [Show full text]
  • Generic Programming
    Generic Programming July 21, 1998 A Dagstuhl Seminar on the topic of Generic Programming was held April 27– May 1, 1998, with forty seven participants from ten countries. During the meeting there were thirty seven lectures, a panel session, and several problem sessions. The outcomes of the meeting include • A collection of abstracts of the lectures, made publicly available via this booklet and a web site at http://www-ca.informatik.uni-tuebingen.de/dagstuhl/gpdag.html. • Plans for a proceedings volume of papers submitted after the seminar that present (possibly extended) discussions of the topics covered in the lectures, problem sessions, and the panel session. • A list of generic programming projects and open problems, which will be maintained publicly on the World Wide Web at http://www-ca.informatik.uni-tuebingen.de/people/musser/gp/pop/index.html http://www.cs.rpi.edu/˜musser/gp/pop/index.html. 1 Contents 1 Motivation 3 2 Standards Panel 4 3 Lectures 4 3.1 Foundations and Methodology Comparisons ........ 4 Fundamentals of Generic Programming.................. 4 Jim Dehnert and Alex Stepanov Automatic Program Specialization by Partial Evaluation........ 4 Robert Gl¨uck Evaluating Generic Programming in Practice............... 6 Mehdi Jazayeri Polytypic Programming........................... 6 Johan Jeuring Recasting Algorithms As Objects: AnAlternativetoIterators . 7 Murali Sitaraman Using Genericity to Improve OO Designs................. 8 Karsten Weihe Inheritance, Genericity, and Class Hierarchies.............. 8 Wolf Zimmermann 3.2 Programming Methodology ................... 9 Hierarchical Iterators and Algorithms................... 9 Matt Austern Generic Programming in C++: Matrix Case Study........... 9 Krzysztof Czarnecki Generative Programming: Beyond Generic Programming........ 10 Ulrich Eisenecker Generic Programming Using Adaptive and Aspect-Oriented Programming .
    [Show full text]
  • Interface Evolution Via Virtual Extension Methods Brian Goetz Fourth Draft, June 2011
    Interface evolution via virtual extension methods Brian Goetz Fourth draft, June 2011 1. Problem statement Once published, it is impossible to add methods to an interface without breaking existing implementations. (Specifically, adding a method to an interface is not a source- compatible change.) The longer the time since a library has been published, the more likely it is that this restriction will cause grief for its maintainers. The addition of closures to the Java language in JDK 7 place additional stress on the aging Collection interfaces; one of the most significant benefits of closures is that it enables the development of more powerful libraries. It would be disappointing to add a language feature that enables better libraries while at the same time not extending the core libraries to take advantage of that feature1. V1 of the Lambda Strawman proposed C#-style static extension methods as a means of creating the illusion of adding methods to existing classes and interfaces, but they have significant limitations – for example, they cannot be overridden by classes that implement the interface being extended, so implementations are stuck with the “one size fits all” implementation provided as an extension2, and they are not reflectively discoverable. 2. Virtual extension methods3 In this document, we outline a mechanism for adding new methods to existing interfaces, which we call virtual extension methods. Existing interfaces can be augmented without compromising backward compatibility4 by adding extension methods to the interface, whose declaration would contain instructions for finding the default implementation in the event that implementers do not provide a method body.
    [Show full text]
  • Dynamic Interfaces
    Dynamic Interfaces Vasco T. Vasconcelos Simon J. Gay Antonio´ Ravara Departamento de Informatica´ Department of Computing Science SQIG at Instituto de Telecomunicac¸oes˜ Faculdade de Cienciasˆ da University of Glasgow, UK Department of Mathematics, IST, Universidade de Lisboa, Portugal [email protected] Technical University of Lisbon, Portugal [email protected] [email protected] Nils Gesbert Alexandre Z. Caldeira Department of Computing Science Departamento de Informatica´ University of Glasgow, UK Faculdade de Cienciasˆ da [email protected] Universidade de Lisboa, Portugal [email protected] Abstract 1. Introduction We define a small class-based object-oriented language in which Standard class-based object-oriented languages present the pro- the availability of methods depends on an object’s abstract state: grammer with the following view: an object is declared to belong to objects’ interfaces are dynamic. Each class has a session type which a certain type, and the type defines various methods; it is therefore provides a global specification of the availability of methods in possible at any time to call any of the methods described in the type. each state. A key feature is that the abstract state of an object However, there are often semantic reasons why it is not appropriate may depend on the result of a method whose return type is an to call a particular method when the object is in a particular inter- enumeration. Static typing guarantees that methods are only called nal state. For example: with a stack, one should not attempt to pop when they are available.
    [Show full text]
  • Java Application Programming Interface (API) Java Application Programming Interface (API) Is a List of All Classes That Are Part of the Java Development Kit (JDK)
    Java Application Programming Interface (API) Java application programming interface (API) is a list of all classes that are part of the Java development kit (JDK). It includes all Java packages, classes, and interfaces, along with their methods, fields, and constructors. These prewritten classes provide a tremendous amount of functionality to a programmer. A programmer should be aware of these classes and should know how to use them. A complete listing of all classes in Java API can be found at Oracle’s website: http://docs.oracle.com/javase/7/docs/api/. Please visit the above site and bookmark it for future reference. Please consult this site often, especially when you are using a new class and would like to know more about its methods and fields. If you browse through the list of packages in the API, you will observe that there are packages written for GUI programming, networking programming, managing input and output, database programming, and many more. Please browse the complete list of packages and their descriptions to see how they can be used. In order to use a class from Java API, one needs to include an import statement at the start of the program. For example, in order to use the Scanner class, which allows a program to accept input from the keyboard, one must include the following import statement: import java.util.Scanner; The above import statement allows the programmer to use any method listed in the Scanner class. Another choice for including the import statement is the wildcard option shown below: import java.util.*; This version of the import statement imports all the classes in the API’s java.util package and makes them available to the programmer.
    [Show full text]
  • A Metaobject Protocol for Fault-Tolerant CORBA Applications
    A Metaobject Protocol for Fault-Tolerant CORBA Applications Marc-Olivier Killijian*, Jean-Charles Fabre*, Juan-Carlos Ruiz-Garcia*, Shigeru Chiba** *LAAS-CNRS, 7 Avenue du Colonel Roche **Institute of Information Science and 31077 Toulouse cedex, France Electronics, University of Tsukuba, Tennodai, Tsukuba, Ibaraki 305-8573, Japan Abstract The corner stone of a fault-tolerant reflective The use of metalevel architectures for the architecture is the MOP. We thus propose a special implementation of fault-tolerant systems is today very purpose MOP to address the problems of general-purpose appealing. Nevertheless, all such fault-tolerant systems ones. We show that compile-time reflection is a good have used a general-purpose metaobject protocol (MOP) approach for developing a specialized runtime MOP. or are based on restricted reflective features of some The definition and the implementation of an object-oriented language. According to our past appropriate runtime metaobject protocol for implementing experience, we define in this paper a suitable metaobject fault tolerance into CORBA applications is the main protocol, called FT-MOP for building fault-tolerant contribution of the work reported in this paper. This systems. We explain how to realize a specialized runtime MOP, called FT-MOP (Fault Tolerance - MetaObject MOP using compile-time reflection. This MOP is CORBA Protocol), is sufficiently general to be used for other aims compliant: it enables the execution and the state evolution (mobility, adaptability, migration, security). FT-MOP of CORBA objects to be controlled and enables the fault provides a mean to attach dynamically fault tolerance tolerance metalevel to be developed as CORBA software. strategies to CORBA objects as CORBA metaobjects, enabling thus these strategies to be implemented as 1 .
    [Show full text]
  • Create Mixins with Interfaces and Extension Methods by Bill Wagner
    Create Mixins with Interfaces and Extension Methods by Bill Wagner Mixins are small utility classes that define some useful functionality that will usually become part of something larger. For example, a class that implements a serial number to uniquely identify an object, or a timestamp that reports when an object was created. In C++, these mixin classes would be created using regular class definitions, and larger classes that wanted to use the mixin behavior would simply inherit from the mixin, in addition to any base classes it needed. Because the .NET Framework does not support multiple inheritance, we’ve typically used interface to define mixins. That works, but it’s not as powerful. One of the limitations of using interfaces to define mixin behavior is that every class that implements an interface must reimplement every method defined in that interface. That leads many developers to creating minimal interface definitions. (IEqualityComparer<T> has one method, IComparable<T> has only method). In those instances, the interface’s full functionality is completely defined in those small methods. But, what about cases where your interface can, or should, contain many more methods in order to support the developers that want to use the interface? That’s a perfect use case for extension methods. By creating extension methods using the interface, you can inject many more methods into the public definition of the interface, without forcing every developer to re-create those methods whenever he or she implements that interface. I’ve created a simple example based on strings that represent file paths. I often write classes that contain files or directories, usually for offline caches, or similar needs.
    [Show full text]
  • Variable-Arity Generic Interfaces
    Variable-Arity Generic Interfaces T. Stephen Strickland, Richard Cobbe, and Matthias Felleisen College of Computer and Information Science Northeastern University Boston, MA 02115 [email protected] Abstract. Many programming languages provide variable-arity func- tions. Such functions consume a fixed number of required arguments plus an unspecified number of \rest arguments." The C++ standardiza- tion committee has recently lifted this flexibility from terms to types with the adoption of a proposal for variable-arity templates. In this paper we propose an extension of Java with variable-arity interfaces. We present some programming examples that can benefit from variable-arity generic interfaces in Java; a type-safe model of such a language; and a reduction to the core language. 1 Introduction In April of 2007 the C++ standardization committee adopted Gregor and J¨arvi's proposal [1] for variable-length type arguments in class templates, which pre- sented the idea and its implementation but did not include a formal model or soundness proof. As a result, the relevant constructs will appear in the upcom- ing C++09 draft. Demand for this feature is not limited to C++, however. David Hall submitted a request for variable-arity type parameters for classes to Sun in 2005 [2]. For an illustration of the idea, consider the remarks on first-class functions in Scala [3] from the language's homepage. There it says that \every function is a value. Scala provides a lightweight syntax for defining anonymous functions, it supports higher-order functions, it allows functions to be nested, and supports currying." To achieve this integration of objects and closures, Scala's standard library pre-defines ten interfaces (traits) for function types, which we show here in Java-like syntax: interface Function0<Result> { Result apply(); } interface Function1<Arg1,Result> { Result apply(Arg1 a1); } interface Function2<Arg1,Arg2,Result> { Result apply(Arg1 a1, Arg2 a2); } ..
    [Show full text]
  • On the Interaction of Object-Oriented Design Patterns and Programming
    On the Interaction of Object-Oriented Design Patterns and Programming Languages Gerald Baumgartner∗ Konstantin L¨aufer∗∗ Vincent F. Russo∗∗∗ ∗ Department of Computer and Information Science The Ohio State University 395 Dreese Lab., 2015 Neil Ave. Columbus, OH 43210–1277, USA [email protected] ∗∗ Department of Mathematical and Computer Sciences Loyola University Chicago 6525 N. Sheridan Rd. Chicago, IL 60626, USA [email protected] ∗∗∗ Lycos, Inc. 400–2 Totten Pond Rd. Waltham, MA 02154, USA [email protected] February 29, 1996 Abstract Design patterns are distilled from many real systems to catalog common programming practice. However, some object-oriented design patterns are distorted or overly complicated because of the lack of supporting programming language constructs or mechanisms. For this paper, we have analyzed several published design patterns looking for idiomatic ways of working around constraints of the implemen- tation language. From this analysis, we lay a groundwork of general-purpose language constructs and mechanisms that, if provided by a statically typed, object-oriented language, would better support the arXiv:1905.13674v1 [cs.PL] 31 May 2019 implementation of design patterns and, transitively, benefit the construction of many real systems. In particular, our catalog of language constructs includes subtyping separate from inheritance, lexically scoped closure objects independent of classes, and multimethod dispatch. The proposed constructs and mechanisms are not radically new, but rather are adopted from a variety of languages and programming language research and combined in a new, orthogonal manner. We argue that by describing design pat- terns in terms of the proposed constructs and mechanisms, pattern descriptions become simpler and, therefore, accessible to a larger number of language communities.
    [Show full text]