Multiple Dispatch As Dispatch on Tuples Gary T

Total Page:16

File Type:pdf, Size:1020Kb

Multiple Dispatch As Dispatch on Tuples Gary T Computer Science Technical Reports Computer Science 7-1998 Multiple Dispatch as Dispatch on Tuples Gary T. Leavens Iowa State University Todd Millstein Iowa State University Follow this and additional works at: http://lib.dr.iastate.edu/cs_techreports Part of the Systems Architecture Commons, and the Theory and Algorithms Commons Recommended Citation Leavens, Gary T. and Millstein, Todd, "Multiple Dispatch as Dispatch on Tuples" (1998). Computer Science Technical Reports. 131. http://lib.dr.iastate.edu/cs_techreports/131 This Article is brought to you for free and open access by the Computer Science at Iowa State University Digital Repository. It has been accepted for inclusion in Computer Science Technical Reports by an authorized administrator of Iowa State University Digital Repository. For more information, please contact [email protected]. Multiple Dispatch as Dispatch on Tuples Abstract Many popular object-oriented programming languages, such as C++, Smalltalk-80, Java, and Eiffel, do not support multiple dispatch. Yet without multiple dispatch, programmers find it difficult to express binary methods and design patterns such as the ``visitor'' pattern. We describe a new, simple, and orthogonal way to add multimethods to single-dispatch object-oriented languages, without affecting existing code. The new mechanism also clarifies many differences between single and multiple dispatch. Keywords Multimethods, generic functions, object-oriented programming languages, single dispatch, multiple dispatch, tuples, product types, encapsulation, modularity, static typechecking, subtyping, inheritance, Tuple language Disciplines Systems Architecture | Theory and Algorithms Comments Copyright © 1998 by the Association for Computer Machinery, Inc., 1998. Permission to make digital or hard copies of part or all of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or ommec rcial advantage, the copyright notice, the title of this publication, and its date appear, and notice is given that copying is by permission of ACM, Inc. To copy otherwise, to republish, to post on servers, or to redistribute to lists, requires prior specific permission and/or a fee. This article is available at Iowa State University Digital Repository: http://lib.dr.iastate.edu/cs_techreports/131 Multiple Dispatch as Dispatch on Tuples Gary T. Leavens and Todd D. Millstein TR #98-03b April 1998, Revised May, July 1998 To appear in OOPSLA ‘98 Object-Oriented Programming, Systems, Langauges, and Applications, Vancouver, British Columbia, October 18-22, 1998. Keywords: Multimethods, generic functions, object-oriented programming languages, single dispatch, multiple dispatch, tuples, product types, encapsulation, modularity, static typechecking, subtyping, inheritance, Tuple language. 1994 CR Categories: D.3.1 [Programming Languages] Formal Definitions and Theory — semantics; D.3.2 [Programming Languages] Language Classifications — object-oriented languages; D.3.3 [Programming Languages] Language Constructs and Features — abstract data types, control structures, procedures, functions, and subroutines; D.3.m [Programming Languages] Miscellaneous — multimethods, generic functions, single dispatch, multiple dispatch, type systems; F.3.3 [Logics and Meanings of Programs] Studies of Program Constructs — control primitives, type structure. Copyright © 1998 by the Association for Computing Machinery, Inc., 1998. Permission to make digital or hard copies of part or all of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commerical advantage, the copyright notice, the title of this publication, and its date appear, and notice is given that copying is by permission of ACM, Inc. To copy otherwise, to republish, to post on servers, or to redistribute to lists, requires prior specific permission and/or a fee. Department of Computer Science 226 Atanasoff Hall Iowa State University Ames, Iowa 50011-1040, USA Multiple Dispatch as Dispatch on Tuples Gary T. Leavens Todd D. Millstein Department of Computer Science, Department of Computer Science and Engineering, Iowa State University, University of Washington, 229 Atanasoff Hall, Ames, Iowa, 50011 USA Box 352350, Seattle, WA 98195-2350 USA [email protected] [email protected] +1 515 294-1580 +1 206 543-5118 ABSTRACT tuple gives multiple dispatch. To illustrate the idea, we have * Many popular object-oriented programming languages, such designed a simple class-based OO language called Tuple . as C++, Smalltalk-80, Java, and Eiffel, do not support While perhaps not as elegant as a language built directly with multiple dispatch. Yet without multiple dispatch, multiple dispatch, we claim the following advantages for our programmers find it difficult to express binary methods and mechanism: design patterns such as the “visitor” pattern. We describe a 1. It can be added to existing single dispatch languages, new, simple, and orthogonal way to add multimethods to such as C++ and Java, without affecting either (a) the single-dispatch object-oriented languages, without affecting semantics or (b) the typing of existing programs written existing code. The new mechanism also clarifies many in these languages. differences between single and multiple dispatch. 2. It retains the encapsulation mechanisms of single- dispatch languages. Keywords 3. It is simple enough to be easily understood and Multiple dispatch, multimethods, generic functions, typing, remembered, we believe, by programmers familiar with single dispatch, binary methods, semantics, language design, standard single dispatch. Tuple. 4. It is more uniform than previous approaches of 1 INTRODUCTION incorporating multiple dispatch within a single- dispatching framework. Single dispatch, as found in C++ [Stroustrup 97], Java [Arnold & Gosling 98, Gosling et al. 96], Smalltalk-80 To argue for the first two claims, we present the semantics of [Goldberg & Robson 83], and Eiffel [Meyer 92, Meyer 97], the language in two layers. The first layer is a small, class- selects a method using the dynamic class of one object, the based single-dispatching language, SDCore, of no interest in message’s receiver. Multiple dispatch, as found in CLOS itself. The second layer, Tuple proper, includes SDCore and [Chapter 28, Steele 90] [Paepcke 93], Dylan [Shalit 97, adds multiple dispatch by allowing messages to be sent to Feinberg et al. 97], and Cecil [Chambers 92, Chambers 95], tuples. generalizes this idea, selecting a method based on the Our support for the third claim is the simplicity of the dynamic class of any subset of the message’s arguments. mechanism itself. If, even now, you think the idea of sending Multiple dispatch is in many ways more expressive and messages to tuples is clearly equivalent to multiple dispatch, flexible than single dispatch in object-oriented (OO) then you agree. To support the fourth claim, we argue below programming [Bobrow et al. 86, Chambers 92, Castagna 97, that our mechanism has advantages over others that solve the Moon 86]. same problem of incorporating multiple dispatch into In this paper we propose a new, simple, and orthogonal way existing single-dispatching languages. of adding multiple dispatch to existing languages with single The rest of this paper is organized as follows. In Section 2 we dispatch. The idea is to add tuples as primitive expressions describe the single-dispatching core of Tuple; this is needed and to allow messages to be sent to tuples. Selecting a only to show how our mechanism can be added to such a method based on the dynamic classes of the elements of the language. In Section 3 we describe the additions to the single- dispatching core that make up our mechanism and support our first three claims. Section 4 supports the fourth claim by comparison with related work. In Section 5 we offer * With apologies to Bruce et al., whose TOOPLE language [Bruce et al. 93] is pronounced the same way. 1 class Point { inheritance causes no problems with respect to the new ideas fields (xval:int, yval:int) we are advocating.) method x():int { xval } method y():int { yval } We use a standard syntax for message sends. For example, if method distanceFrom(l:Line):int { ... } p1 is an instance of Point or a subclass, then the } expression p1.distanceFrom(ln2) invokes the instance’s distanceFrom method with the argument class ColorPoint inherits Point { ln2. Within the method body, the keyword self refers to fields (colorval:Color) method color():Color { colorval } the receiver of the message, in this case p1. } Dynamic dispatching is used to determine which method to Figure 1: The classes Point and ColorPoint. invoke. In particular, the receiver’s class is first checked for a method implementation of the right name and number of arguments. If no such method exists, then that class’s some conclusions. In Appendix A we give the concrete immediate superclass is checked, and so on up the syntax of Tuple, and in Appendix B we give the language’s inheritance hierarchy until a valid implementation is found formal typing rules. (or none is found and a message-not-understood error occurs). 2 SDCORE, THE SINGLE-DISPATCHING CORE OF TUPLE For simplicity, and to ease theoretical analysis, we have not In this section, we introduce the syntax and semantics of included assignment and mutation in SDCore. Again, these SDCore by example. could be easily added. 2.1 Syntax and Semantics 2.2 Type Checking for SDCore The single-dispatching
Recommended publications
  • MANNING Greenwich (74° W
    Object Oriented Perl Object Oriented Perl DAMIAN CONWAY MANNING Greenwich (74° w. long.) For electronic browsing and ordering of this and other Manning books, visit http://www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact: Special Sales Department Manning Publications Co. 32 Lafayette Place Fax: (203) 661-9018 Greenwich, CT 06830 email: [email protected] ©2000 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Library of Congress Cataloging-in-Publication Data Conway, Damian, 1964- Object oriented Perl / Damian Conway. p. cm. includes bibliographical references. ISBN 1-884777-79-1 (alk. paper) 1. Object-oriented programming (Computer science) 2. Perl (Computer program language) I. Title. QA76.64.C639 1999 005.13'3--dc21 99-27793 CIP Manning Publications Co. Copyeditor: Adrianne Harun 32 Lafayette
    [Show full text]
  • Homework 2: Reflection and Multiple Dispatch in Smalltalk
    Com S 541 — Programming Languages 1 October 2, 2002 Homework 2: Reflection and Multiple Dispatch in Smalltalk Due: Problems 1 and 2, September 24, 2002; problems 3 and 4, October 8, 2002. This homework can either be done individually or in teams. Its purpose is to familiarize you with Smalltalk’s reflection facilities and to help learn about other issues in OO language design. Don’t hesitate to contact the staff if you are not clear about what to do. In this homework, you will adapt the “multiple dispatch as dispatch on tuples” approach, origi- nated by Leavens and Millstein [1], to Smalltalk. To do this you will have to read their paper and then do the following. 1. (30 points) In a new category, Tuple-Smalltalk, add a class Tuple, which has indexed instance variables. Design this type to provide the necessary methods for working with dispatch on tuples, for example, we’d like to have access to the tuple of classes of the objects in a given tuple. Some of these methods will depend on what’s below. Also design methods so that tuples can be used as a data structure (e.g., to pass multiple arguments and return multiple results). 2. (50 points) In the category, Tuple-Smalltalk, design other classes to hold the behavior that will be declared for tuples. For example, you might want something analogous to a method dictionary and other things found in the class Behavior or ClassDescription. It’s worth studying those classes to see what can be adapted to our purposes.
    [Show full text]
  • TAMING the MERGE OPERATOR a Type-Directed Operational Semantics Approach
    Technical Report, Department of Computer Science, the University of Hong Kong, Jan 2021. 1 TAMING THE MERGE OPERATOR A Type-directed Operational Semantics Approach XUEJING HUANG JINXU ZHAO BRUNO C. D. S. OLIVEIRA The University of Hong Kong (e-mail: fxjhuang, jxzhao, [email protected]) Abstract Calculi with disjoint intersection types support a symmetric merge operator with subtyping. The merge operator generalizes record concatenation to any type, enabling expressive forms of object composition, and simple solutions to hard modularity problems. Unfortunately, recent calculi with disjoint intersection types and the merge operator lack a (direct) operational semantics with expected properties such as determinism and subject reduction, and only account for terminating programs. This paper proposes a type-directed operational semantics (TDOS) for calculi with intersection types and a merge operator. We study two variants of calculi in the literature. The first calculus, called li, is a variant of a calculus presented by Oliveira et al. (2016) and closely related to another calculus by Dunfield (2014). Although Dunfield proposes a direct small-step semantics for her calcu- lus, her semantics lacks both determinism and subject reduction. Using our TDOS we obtain a direct + semantics for li that has both properties. The second calculus, called li , employs the well-known + subtyping relation of Barendregt, Coppo and Dezani-Ciancaglini (BCD). Therefore, li extends the more basic subtyping relation of li, and also adds support for record types and nested composition (which enables recursive composition of merged components). To fully obtain determinism, both li + and li employ a disjointness restriction proposed in the original li calculus.
    [Show full text]
  • Julia: a Fresh Approach to Numerical Computing
    RSDG @ UCL Julia: A Fresh Approach to Numerical Computing Mosè Giordano @giordano [email protected] Knowledge Quarter Codes Tech Social October 16, 2019 Julia’s Facts v1.0.0 released in 2018 at UCL • Development started in 2009 at MIT, first • public release in 2012 Julia co-creators won the 2019 James H. • Wilkinson Prize for Numerical Software Julia adoption is growing rapidly in • numerical optimisation, differential equations, machine learning, differentiable programming It is used and taught in several universities • (https://julialang.org/teaching/) Mosè Giordano (RSDG @ UCL) Julia: A Fresh Approach to Numerical Computing October 16, 2019 2 / 29 Julia on Nature Nature 572, 141-142 (2019). doi: 10.1038/d41586-019-02310-3 Mosè Giordano (RSDG @ UCL) Julia: A Fresh Approach to Numerical Computing October 16, 2019 3 / 29 Solving the Two-Language Problem: Julia Multiple dispatch • Dynamic type system • Good performance, approaching that of statically-compiled languages • JIT-compiled scripts • User-defined types are as fast and compact as built-ins • Lisp-like macros and other metaprogramming facilities • No need to vectorise: for loops are fast • Garbage collection: no manual memory management • Interactive shell (REPL) for exploratory work • Call C and Fortran functions directly: no wrappers or special APIs • Call Python functions: use the PyCall package • Designed for parallelism and distributed computation • Mosè Giordano (RSDG @ UCL) Julia: A Fresh Approach to Numerical Computing October 16, 2019 4 / 29 Multiple Dispatch using DifferentialEquations
    [Show full text]
  • Comp 411 Principles of Programming Languages Lecture 19 Semantics of OO Languages
    Comp 411 Principles of Programming Languages Lecture 19 Semantics of OO Languages Corky Cartwright Mar 10-19, 2021 Overview I • In OO languages, OO data values (except for designated non-OO types) are special records [structures] (finite mappings from names to values). In OO parlance, the components of record are called members. • Some members of an object may be functions called methods. Methods take this (the object in question) as an implicit parameter. Some OO languages like Java also support static methods that do not depend on this; these methods have no implicit parameters. In efficient OO language implementations, method members are shared since they are the same for all instances of a class, but this sharing is an optimization in statically typed OO languages since the collection of methods in a class is immutable during program evaluation (computation). • A method (instance method in Java) can only be invoked on an object (the receiver, an implicit parameter). Additional parameters are optional, depending on whether the method expects them. This invocation process is called dynamic dispatch because the executed code is literally extracted from the object: the code invoked at a call site depends on the value of the receiver, which can change with each execution of the call. • A language with objects is OO if it supports dynamic dispatch (discussed in more detail in Overview II & III) and inheritance, an explicit taxonomy for classifying objects based on their members and class names where superclass/parent methods are inherited unless overridden. • In single inheritance, this taxonomy forms a tree; • In multiple inheritance, it forms a rooted DAG (directed acyclic graph) where the root class is the universal class (Object in Java).
    [Show full text]
  • Dynamic Dispatch
    CS 3110 Lecture 24: Dynamic Dispatch Prof. Clarkson Spring 2015 Today’s music: "Te Core" by Eric Clapton Review Current topic: functional vs. object-oriented programming Today: • Continue encoding objects in OCaml • Te core of OOP – dynamic dispatch – sigma calculus Review: key features of OOP 1. Encapsulation 2. Subtyping 3. Inheritance 4. Dynamic dispatch Review: Counters class Counter {! protected int x = 0;! public int get() { return x; }! public void inc() { x++; }! }! Review: Objects • Type of object is record of functions !type counter = {! !get : unit -> int;! !inc : unit -> unit;! !} • Let-binding hides internal state (with closure) !let x = ref 0 in {! !get = (fun () -> !x);! !inc = (fun () -> x := !x+1);! !}! Review: Classes • Representation type for internal state: !type counter_rep = {! !!x : int ref;! !}! • Class is a function from representation type to object: !let counter_class (r:counter_rep) = {! !!get = (fun () -> !(r.x));! !!inc = (fun () -> (r.x := !(r.x) + 1));! !}! • Constructor uses class function to make a new object: !let new_counter () =! !!let r = {x = ref 0} in! ! !counter_class r !! Review: Inheritance • Subclass creates an object of the superclass with the same internal state as its own – Bind resulting parent object to super • Subclass creates a new object with same internal state • Subclass copies (inherits) any implementations it wants from superclass 4. DYNAMIC DISPATCH This class SetCounter {! protected int x = 0;! public int get() { return x; }! public void set(int i) { x = i; }! public void inc()
    [Show full text]
  • Concepts in Programming Languages Practicalities
    Concepts in Programming Languages Practicalities I Course web page: Alan Mycroft1 www.cl.cam.ac.uk/teaching/1617/ConceptsPL/ with lecture slides, exercise sheet and reading material. These slides play two roles – both “lecture notes" and “presentation material”; not every slide will be lectured in Computer Laboratory detail. University of Cambridge I There are various code examples (particularly for 2016–2017 (Easter Term) JavaScript and Java applets) on the ‘materials’ tab of the course web page. I One exam question. www.cl.cam.ac.uk/teaching/1617/ConceptsPL/ I The syllabus and course has changed somewhat from that of 2015/16. I would be grateful for comments on any remaining ‘rough edges’, and for views on material which is either over- or under-represented. 1Acknowledgement: various slides are based on Marcelo Fiore’s 2013/14 course. Alan Mycroft Concepts in Programming Languages 1 / 237 Alan Mycroft Concepts in Programming Languages 2 / 237 Main books Context: so many programming languages I J. C. Mitchell. Concepts in programming languages. Cambridge University Press, 2003. Peter J. Landin: “The Next 700 Programming Languages”, I T.W. Pratt and M. V.Zelkowitz. Programming Languages: CACM (published in 1966!). Design and implementation (3RD EDITION). Some programming-language ‘family trees’ (too big for slide): Prentice Hall, 1999. http://www.oreilly.com/go/languageposter http://www.levenez.com/lang/ ? M. L. Scott. Programming language pragmatics http://rigaux.org/language-study/diagram.html (4TH EDITION). http://www.rackspace.com/blog/ Elsevier, 2016. infographic-evolution-of-computer-languages/ I R. Harper. Practical Foundations for Programming Plan of this course: pick out interesting programming-language Languages.
    [Show full text]
  • Characteristics of Mathematical Modeling Languages That
    www.nature.com/npjsba ARTICLE OPEN Characteristics of mathematical modeling languages that facilitate model reuse in systems biology: a software engineering perspective ✉ Christopher Schölzel 1 , Valeria Blesius1, Gernot Ernst2,3 and Andreas Dominik 1 Reuse of mathematical models becomes increasingly important in systems biology as research moves toward large, multi-scale models composed of heterogeneous subcomponents. Currently, many models are not easily reusable due to inflexible or confusing code, inappropriate languages, or insufficient documentation. Best practice suggestions rarely cover such low-level design aspects. This gap could be filled by software engineering, which addresses those same issues for software reuse. We show that languages can facilitate reusability by being modular, human-readable, hybrid (i.e., supporting multiple formalisms), open, declarative, and by supporting the graphical representation of models. Modelers should not only use such a language, but be aware of the features that make it desirable and know how to apply them effectively. For this reason, we compare existing suitable languages in detail and demonstrate their benefits for a modular model of the human cardiac conduction system written in Modelica. npj Systems Biology and Applications (2021) 7:27 ; https://doi.org/10.1038/s41540-021-00182-w 1234567890():,; INTRODUCTION descriptions of experiment setup or design choices6–8. A recent As the understanding of biological systems grows, it becomes study by curators of the BioModels database showed that only 8 more and more apparent that their behavior cannot be reliably 51% of 455 published models were directly reproducible .Inan 9 predicted without the help of mathematical models. In the past, extreme case, Topalidou et al.
    [Show full text]
  • Strategic Location and Dispatch Management of Assets in a Military Medical Evacuation Enterprise Phillip R
    Air Force Institute of Technology AFIT Scholar Theses and Dissertations Student Graduate Works 6-19-2019 Strategic Location and Dispatch Management of Assets in a Military Medical Evacuation Enterprise Phillip R. Jenkins Follow this and additional works at: https://scholar.afit.edu/etd Part of the Operations and Supply Chain Management Commons Recommended Citation Jenkins, Phillip R., "Strategic Location and Dispatch Management of Assets in a Military Medical Evacuation Enterprise" (2019). Theses and Dissertations. 2292. https://scholar.afit.edu/etd/2292 This Dissertation is brought to you for free and open access by the Student Graduate Works at AFIT Scholar. It has been accepted for inclusion in Theses and Dissertations by an authorized administrator of AFIT Scholar. For more information, please contact [email protected]. Strategic Location and Dispatch Management of Assets in a Military Medical Evacuation Enterprise DISSERTATION Phillip R. Jenkins, Capt, USAF AFIT-ENS-DS-19-J-037 DEPARTMENT OF THE AIR FORCE AIR UNIVERSITY AIR FORCE INSTITUTE OF TECHNOLOGY Wright-Patterson Air Force Base, Ohio DISTRIBUTION STATEMENT A APPROVED FOR PUBLIC RELEASE; DISTRIBUTION UNLIMITED. The views expressed in this document are those of the author and do not reflect the official policy or position of the United States Air Force, the United States Department of Defense or the United States Government. This material is declared a work of the U.S. Government and is not subject to copyright protection in the United States. AFIT-ENS-DS-19-J-037 STRATEGIC LOCATION AND DISPATCH MANAGEMENT OF ASSETS IN A MILITARY MEDICAL EVACUATION ENTERPRISE DISSERTATION Presented to the Faculty Graduate School of Engineering and Management Air Force Institute of Technology Air University Air Education and Training Command in Partial Fulfillment of the Requirements for the Degree of Doctor of Philosophy Phillip R.
    [Show full text]
  • Specialising Dynamic Techniques for Implementing the Ruby Programming Language
    SPECIALISING DYNAMIC TECHNIQUES FOR IMPLEMENTING THE RUBY PROGRAMMING LANGUAGE A thesis submitted to the University of Manchester for the degree of Doctor of Philosophy in the Faculty of Engineering and Physical Sciences 2015 By Chris Seaton School of Computer Science This published copy of the thesis contains a couple of minor typographical corrections from the version deposited in the University of Manchester Library. [email protected] chrisseaton.com/phd 2 Contents List of Listings7 List of Tables9 List of Figures 11 Abstract 15 Declaration 17 Copyright 19 Acknowledgements 21 1 Introduction 23 1.1 Dynamic Programming Languages.................. 23 1.2 Idiomatic Ruby............................ 25 1.3 Research Questions.......................... 27 1.4 Implementation Work......................... 27 1.5 Contributions............................. 28 1.6 Publications.............................. 29 1.7 Thesis Structure............................ 31 2 Characteristics of Dynamic Languages 35 2.1 Ruby.................................. 35 2.2 Ruby on Rails............................. 36 2.3 Case Study: Idiomatic Ruby..................... 37 2.4 Summary............................... 49 3 3 Implementation of Dynamic Languages 51 3.1 Foundational Techniques....................... 51 3.2 Applied Techniques.......................... 59 3.3 Implementations of Ruby....................... 65 3.4 Parallelism and Concurrency..................... 72 3.5 Summary............................... 73 4 Evaluation Methodology 75 4.1 Evaluation Philosophy
    [Show full text]
  • Subclassing and Dynamic Dispatch
    Subclassing and Dynamic Dispatch 6.170 Lecture 3 This lecture is about dynamic dispatch: how a call o.m() may actually invoke the code of different methods, all with the same name m, depending on the runtime type of the receiver object o. To explain how this happens, we show how one class can be defined as a subclass of another, and can override some of its methods. This is called subclassing or inheritance, and it is a central feature of object oriented languages. At the same time, it’s arguably a rather dangerous and overrused feature, for reasons that we’ll discuss later when we look at subtyping. The notion of dynamic dispatch is broader than the notion of inheritance. You can write a Java program with no inheritance in which dynamic dispatch still occurs. This is because Java has built- in support for specifications. You can declare an object to satisfy a kind of partial specification called an interface, and you can provide many implementations of the same interface. This is actually a more important and fundamental notion than subclassing, and it will be discussed in our lecture on specification. 1 Bank Transaction Code Here is the code for a class representing a bank account: class Account { String name; Vector transv; int balance; Account (String n) { transv = new Vector (); balance = 0; name = n; } boolean checkTrans (Trans t) { return (balance + t.amount >= 0); } void post (Trans t) { transv.add (t); balance += t.amount; } } and a class representing a transaction: class Trans { int amount; 1 Date date; ... } 2 Extending a Class by Inheritance Suppose we want to implement a new kind of account that allows overdrafts.
    [Show full text]
  • Topic 9: Type Checking • Readings: • Chapter 13.5, 13.6 and 13.7
    Recommended Exercises and Readings • From Haskell: The craft of functional programming (3rd Ed.) • Exercises: • 13.17, 13.18, 13.19, 13.20, 13.21, 13.22 Topic 9: Type Checking • Readings: • Chapter 13.5, 13.6 and 13.7 1 2 Type systems Static vs. Dynamic Typing • There are (at least) three different ways that we can compare type • Static typing systems • The type of a variable is known at compile time • Static vs. dynamic typing • It is explicitly stated by the programmer… • Strong vs. weak typing • Or it can be inferred from context • Explicit vs. implicit typing • Type checking can be performed without running the program • Used by Haskell • Also used by C, C++, C#, Java, Fortran, Pascal, … 3 4 Static vs. Dynamic Typing Static vs. Dynamic Typing • Dynamic typing • Static vs. Dynamic typing is a question of timing… • The type of a variable is not known until the program is running • When is type checking performed? • Typically determined from the value that is actually stored in it • At compile time (before the program runs)? Static • Program can crash at runtime due to incorrect types • As the program is running? Dynamic • Permits downcasting, dynamic dispatch, reflection, … • Used by Python, Javascript, PHP, Lisp, Ruby, … 5 6 Static vs. Dynamic Typing Static vs. Dynamic Typing • Some languages do a mixture of both of static and dynamic typing • Advantages of static typing • Most type checking in Java is performed at compile time… • … but downcasting is permitted, and can’t be verified at compile time • Generated code includes a runtime type check • A ClassCastException is thrown if the downcast wasn’t valid • Advantages of dynamic typing • Most type checking in C++ is performed at compile time.
    [Show full text]