SML Modules and Abstract Data Types (Adts)

Total Page:16

File Type:pdf, Size:1020Kb

SML Modules and Abstract Data Types (Adts) SML Modules and Overview of Modules and ADTs Hiding implementa-on details is the most important strategy Abstract Data Types (ADTs) for wriCng correct, robust, reusable soEware. Topics: These slides are lightly edited versions of Ben Wood’s Fall ‘15 slides, some of which are based on Dan Grossman’s material from the University of Washington. • ML structures and signatures. • AbstracCon for robust library and client+library code. • AbstracCon for easy change. • ADTs and funcCons as data. CS251 Programming Languages Spring 2019, Lyn Turbak Department of Computer Science Wellesley College SML Modules and ADTS 2 structure Name = struct bindings end Hiding with funcLons structure (module) procedural abstrac.on namespace management and code organizaLon structure MyMathLib = Hiding implementaCon details is the most important strategy for struct wriCng correct, robust, reusable soEware. fun fact 0 = 1 | fact x = x * fact (x-1) fun double x = x*2 Can you tell the difference? fun double x = x+x val half_pi = Math.pi / 2 val y = 2 - double 4; fun double x = x*y fun doubler x = x * 2 fun double x = val it : int = 8 let fun help 0 y = y val twelve = doubler (fact 3) | help x y = end help (x-1) (y+1) in help x x end outside: “Private” top-level funcCons would also be nice... val facts = List.map MyMathLib.fact • share a "private" helper funcCon [1,4,MyMathLib.doubler 3, MyMathLib.twelve] SML Modules and ADTS 3 SML Modules and ADTS 4 signature NAME = structure Name :> NAME = sig binding-types end ascripLon struct bindings end signature (opaque – will ignore other kinds) type for a structure (module) Ascribing a signature to a structure • Structure must have all bindings with types as declared in signature. List of bindings and their types: signature MATHLIB = variables (incl. funcCons), type synonyms, datatypes, excepCons sig Separate from specific structure. val fact : int -> int Real power: val half_pi : real val doubler : int -> int Abstrac-on and Hiding signature MATHLIB = val twelve : int sig end val fact : int -> int val half_pi : real structure MyMathLib :> MATHLIB = val doubler : int -> int struct val twelve : int fun fact 0 = 1 end | fact x = x * fact (x-1) val half_pi = Math.pi / 2 fun doubler x = x * 2 val twelve = doubler (fact 3) SML Modules and ADTS 5 end SML Modules and ADTS 6 Hiding with signatures Abstract Data Type type of data and operaLons on it MyMathLib.doubler unbound (not in environment) outside module. Example: raConal numbers supporCng add and toString signature MATHLIB2 = sig structure Rational = val fact : int -> int struct val half_pi : real datatype rational = Whole of int val twelve : int | Frac of int*int end exception BadFrac structure MyMathLib2 :> MATHLIB2 = (* see rationals.sml for full code *) struct fun fact 0 = 1 fun make_frac (x,y) = ... | fact x = x * fact (x-1) fun add (r1,r2) = ... val half_pi = Math.pi / 2.0 fun toString r = ... fun doubler x = x * 2 end fun twelve = doubler (fact 3) end SML Modules and ADTS 7 SML Modules and ADTS 8 Library spec and invariants More on invariants External properCes [externally visible guarantees, up to library writer] • Disallow denominators of 0 Our code maintains (and relies) on invariants. • Return strings in reduced form (“4” not “4/1”, “3/2” not “9/6”) • No infinite loops or excepCons Maintain: • make_frac disallows 0 denominator, removes negaCve denominator, and ImplementaCon invariants [not in external specifica9on] reduces result • All denominators > 0 • add assumes invariants on inputs, calls reduce if needed • All rational values returned from funcCons are reduced Rely: • gcd assumes its arguments are non-negaCve Signatures help enforce internal invariants. • add uses math properCes to avoid calling reduce • toString assumes its argument is in reduced form SML Modules and ADTS 9 SML Modules and ADTS 10 A first signature Problem: clients can violate invariants With what we know so far, this signature makes sense: • Helper funcCons gcd and reduce not visible outside the module. Create values of type Rational.rational directly. signature RATIONAL_CONCRETE = signature RATIONAL_CONCRETE = A7empt #1 sig sig datatype rational = Whole of int datatype rational = Whole of int | Frac of int*int | Frac of int*int ... exception BadFrac end val make_frac : int * int -> rational val add : rational * rational -> rational Rational.Frac(1,0) val toString : rational -> string Rational.Frac(3,~2) end Rational.Frac(40,32) structure Rational :> RATIONAL_OPEN = ... SML Modules and ADTS 11 SML Modules and ADTS 12 SoluLon: hide more! Abstract the type! (Really Big Deal!) Client can pass them around, but can ADT must hide concrete type defini5on so clients cannot Type rational exists, manipulate them only through module. create invariant-viola5ng values of type directly. but representa-on absolutely hidden. signature RATIONAL = Success! (#3) This agempt goes too far: type rational is not known to exist sig type rational Only way to make 1st rational. exception BadFrac signature RATIONAL_WRONG = A7empt #2 Only opera-ons val make_frac : int * int -> rational sig on rational. val add : rational * rational -> rational exception BadFrac val toString : rational -> string val make_frac : int * int -> rational end val add : rational * rational -> rational structure Rational :> RATIONAL = ... val toString : rational -> string end structure Rational :> RATIONAL_WRONG = ... Module controls all opera-ons with rational, so client cannot violate invariants. SML Modules and ADTS 13 SML Modules and ADTS 14 Abstract Data Type Abstract type of data + operaLons on it Abstract Data Types: two key tools Outside of implementaCon: • Values of type rational can be Powerful ways to use signatures for hiding: created and manipulated only through ADT opera-ons. • Concrete representa-on of values of type rational is absolutely hidden. 1. Deny bindings exist. Especially val bindings, fun bindings, constructors. signature RATIONAL = sig 2. Make types abstract. type rational Clients cannot create or inspect values of the type directly. exception BadFrac val make_frac : int * int -> rational val add : rational * rational -> rational val toString : rational -> string end structure Rational :> RATIONAL = ... SML Modules and ADTS 15 SML Modules and ADTS 16 A cute twist Signature matching rules In our example, exposing the Whole constructor is no problem structure Struct :> SIG type-checks if and only if: In SML we can expose it as a funcCon since the datatype binding in the • Every non-abstract type in SIG is provided in Struct, as specified module does create such a funcCon • SCll hiding the rest of the datatype • Every abstract type in SIG is provided in Struct in some way • SCll does not allow using Whole as a pagern • Can be a datatype or a type synonym signature RATIONAL_WHOLE = • Every val-binding in SIG is provided in Struct, possibly with a more sig general and/or less abstract internal type type rational • 'a list -> int more general than string list -> int • example soon exception BadFrac val Whole : int -> rational • Every excepCon in SIG is provided in Struct. val make_frac : int * int -> rational val add : rational * rational -> rational val toString : rational -> string Of course Struct can have more bindings (implicit in above rules) end SML Modules and ADTS 17 SML Modules and ADTS 18 PairRaLonal (alternaLve concrete type) Allow different implementa.ons to be equivalent A key purpose of abstracCon: structure PairRational = • No client can tell which you are using struct • Can improve/replace/choose implementaCons later type rational = int * int • Easier with more abstract signatures (reveal only what you must) exception BadFrac fun make_frac (x,y) = … UnreducedRational in adts.sml. fun Whole i = (i,1) (* for RATIONAL_WHOLE *) • Same concrete datatype. fun add ((a,b)(c,d)) = (a*d + b*c, b*d) • Different invariant: reduce fracCons only in toString. fun toString r = ... (* reduce at last minute *) • Equivalent under RATIONAL and RATIONAL_WHOLE, end but not under RATIONAL_CONCRETE. PairRational in adts.sml. • Different concrete datatype. • Equivalent under RATIONAL and RATIONAL_WHOLE, but cannot ascribe RATIONAL_CONCRETE. SML Modules and ADTS 19 SML Modules and ADTS 20 Some interesLng details Cannot mix and match module bindings • Internally make_frac has type int * int -> int * int, Modules with the same signatures sCll define different types externally int * int -> rational • Client cannot tell if we return argument unchanged These do not type-check: • Rational.toString(UnreducedRational.make_frac(9,6)) • Internally Whole has type 'a -> 'a * int • PairRational.toString(UnreducedRational.make_frac(9,6)) externally int -> rational • specialize 'a to int Crucial for type system and module properLes: • abstract int * int to rational • Type-checker just figures it out • Different modules have different internal invariants! • ... and different type definiLons: • Whole cannot have types 'a -> int * int • UnreducedRational.rational looks like Rational.rational, but or 'a -> rational (must specialize all 'a uses) clients and the type-checker do not know that • PairRational.rational is int*int not a datatype! SML Modules and ADTS 21 SML Modules and ADTS 22 Double Ccks mean a Is an equality Set ADT (set.sml) type (can compare elts with =) Side Note: Equality Types Double-9ck types like range over so-called equality types, which are types over signature SET = Common idiom: if module provides ''a which the polymorphic equality operator = is defined. sig one externally visible type, name it t. type ''a t Then outside references are Set.t. Sadly, the semanCcs of IEEE 754 floaCng point arithmeCc standard prevents the real val empty : ''a t type from being an equality type. It includes Nan (not-a-number) values that represent val singleton : ''a -> ''a t the results of certain operaCons, such as subtracCng posiCve infinity from itself. According to the IEEE standard, tesCng two Nan values for equality must return false, val isEmpty : ''a t -> bool but that would break the reflexivity property that is required for an equality type (i.e., val size : ''a t -> int for any value v in an equality type, v = v must be true).
Recommended publications
  • A Nominal Theory of Objects with Dependent Types
    A Nominal Theory of Objects with Dependent Types Martin Odersky, Vincent Cremet, Christine R¨ockl, Matthias Zenger Ecole´ Polytechnique F´ed´eralede Lausanne INR Ecublens 1015 Lausanne, Switzerland Technical Report IC/2002/070 Abstract Simula 67 [DMN70], whereas virtual or abstract types are present in BETA [MMPN93], as well as more recently in We design and study νObj, a calculus and dependent type gbeta [Ern99], Rune [Tor02] and Scala [Ode02]. An es- system for objects and classes which can have types as mem- sential ingredient of these systems are objects with type bers. Type members can be aliases, abstract types, or new members. There is currently much work that explores types. The type system can model the essential concepts the uses of this concept in object-oriented programming of Java’s inner classes as well as virtual types and family [SB98, TT99, Ern01, Ost02]. But its type theoretic foun- polymorphism found in BETA or gbeta. It can also model dations are just beginning to be investigated. most concepts of SML-style module systems, including shar- As is the case for modules, dependent types are a promis- ing constraints and higher-order functors, but excluding ap- ing candidate for a foundation of objects with type mem- plicative functors. The type system can thus be used as a bers. Dependent products can be used to represent functors basis for unifying concepts that so far existed in parallel in in SML module systems as well as classes in object sys- advanced object systems and in module systems. The paper tems with virtual types [IP02].
    [Show full text]
  • The Power of Interoperability: Why Objects Are Inevitable
    The Power of Interoperability: Why Objects Are Inevitable Jonathan Aldrich Carnegie Mellon University Pittsburgh, PA, USA [email protected] Abstract 1. Introduction Three years ago in this venue, Cook argued that in Object-oriented programming has been highly suc- their essence, objects are what Reynolds called proce- cessful in practice, and has arguably become the dom- dural data structures. His observation raises a natural inant programming paradigm for writing applications question: if procedural data structures are the essence software in industry. This success can be documented of objects, has this contributed to the empirical success in many ways. For example, of the top ten program- of objects, and if so, how? ming languages at the LangPop.com index, six are pri- This essay attempts to answer that question. After marily object-oriented, and an additional two (PHP reviewing Cook’s definition, I propose the term ser- and Perl) have object-oriented features.1 The equiva- vice abstractions to capture the essential nature of ob- lent numbers for the top ten languages in the TIOBE in- jects. This terminology emphasizes, following Kay, that dex are six and three.2 SourceForge’s most popular lan- objects are not primarily about representing and ma- guages are Java and C++;3 GitHub’s are JavaScript and nipulating data, but are more about providing ser- Ruby.4 Furthermore, objects’ influence is not limited vices in support of higher-level goals. Using examples to object-oriented languages; Cook [8] argues that Mi- taken from object-oriented frameworks, I illustrate the crosoft’s Component Object Model (COM), which has unique design leverage that service abstractions pro- a C language interface, is “one of the most pure object- vide: the ability to define abstractions that can be ex- oriented programming models yet defined.” Academ- tended, and whose extensions are interoperable in a ically, object-oriented programming is a primary focus first-class way.
    [Show full text]
  • Abstract Class Name Declaration
    Abstract Class Name Declaration Augustin often sallies sometime when gramophonic Regan denominating granularly and tessellates her zetas. Hanson pleasure her mujiks indifferently, she refining it deafeningly. Crumbiest Jo retrogresses some suspicion after chalcographical Georgia besprinkling downright. Abstract methods and other class that exist in abstract class name declaration, we should be the application using its variables Images are still loading. Java constructor declarations are not members. Not all fields need individual field accessors and mutators. Only elements that are listed as class members contribute to date type definition of a class. When you subclass an abstract class, improve service, etc. Be careful while extending above abstract class, with to little hitch. Abstract classes still in virtual tables, an abstract method is a method definition without braces and followed by a semicolon. Error while getting part list from Facebook! What makes this especially absurd is data most HTML classes are used purely to help us apply presentation with CSS. The separation of interface and implementation enables better software design, it all also supply useful to define constraint mechanisms to be used in expressions, an abstract class may contain implementation details for its members. Understanding which class will be bid for handling a message can illuminate complex when dealing with white than one superclass. How to compute the area if the dust is have known? If you nice a named widget pool, each subclass needs to know equity own table name, that any node can be considered a barn of work queue of linked elements. In only of a Java constructor data members are initialized.
    [Show full text]
  • Abstract Class Function Declaration Typescript
    Abstract Class Function Declaration Typescript Daniel remains well-established after Vale quote anemographically or singe any fortitude. Nigel never fightings Quintusany salpiglossis gone almost skitters floatingly, uncommendably, though Kristian is Nathanael rip-off his stout stotter and hunches. lived enough? Warped and sycophantish Also typescript abstract keyword within a method declaration declares an abstract class without specifying its classes. The typescript has only operate on structural typing appears. Methods in the classes are always defined. Working with JET Elements JET Elements are exported as Typescript interfaces. Example of implementing interface by abstract class the structure provided between their interface typescript abstract interface abstract. This allows you love, for all, implement the Singleton pattern where mercury one copy of an object anywhere be created at finish time. Interfaces can define a type variable declaration declares one value of other similar syntax. In ts provides names for every method declaration in typescript and whatnot in java and congratulations for this? Making thereby a typed language you need so expect until it makes more limitations on the code you write that help turkey avoid any bugs or errors at runtime. This project with class that handle your function abstract class we see, we are a method with classes! What country it together for a Linux distribution to house stable and how much dilute it matter other casual users? It simply visit that at compilation the typescript compiler will get separate type declarations into either single definition. Factory method declaration declares one and functionality has nobody means a common, start appearing now! Although we are obsolete instead of an instance of what you pass properties and be used to know that can access modifier they are abstract type? For function declarations with your post, declaration declares one you! Check out to declaration declares an abstract functionality errors at this function declarations can freely accessible module and there will.
    [Show full text]
  • Static Type Inference for Parametric Classes
    University of Pennsylvania ScholarlyCommons Technical Reports (CIS) Department of Computer & Information Science September 1989 Static Type Inference for Parametric Classes Atsushi Ohori University of Pennsylvania Peter Buneman University of Pennsylvania Follow this and additional works at: https://repository.upenn.edu/cis_reports Recommended Citation Atsushi Ohori and Peter Buneman, "Static Type Inference for Parametric Classes", . September 1989. University of Pennsylvania Department of Computer and Information Science Technical Report No. MS-CIS-89-59. This paper is posted at ScholarlyCommons. https://repository.upenn.edu/cis_reports/851 For more information, please contact [email protected]. Static Type Inference for Parametric Classes Abstract Central features of object-oriented programming are method inheritance and data abstraction attained through hierarchical organization of classes. Recent studies show that method inheritance can be nicely supported by ML style type inference when extended to labeled records. This is based on the fact that a function that selects a field ƒ of a record can be given a polymorphic type that enables it to be applied to any record which contains a field ƒ. Several type systems also provide data abstraction through abstract type declarations. However, these two features have not yet been properly integrated in a statically checked polymorphic type system. This paper proposes a static type system that achieves this integration in an ML-like polymorphic language by adding a class construct that allows the programmer to build a hierarchy of classes connected by multiple inheritance declarations. Moreover, classes can be parameterized by types allowing "generic" definitions. The type correctness of class declarations is st atically checked by the type system.
    [Show full text]
  • Syntactic Type Abstraction
    Syntactic Type Abstraction DAN GROSSMAN, GREG MORRISETT, and STEVE ZDANCEWIC Cornell University Software developers often structure programs in such a way that different pieces of code constitute distinct principals. Types help define the protocol by which these principals interact. In particular, abstract types allow a principal to make strong assumptions about how well-typed clients use the facilities that it provides. We show how the notions of principals and type abstraction can be formalized within a language. Different principals can know the implementation of different abstract types. We use additional syntax to track the flow of values with abstract types during the evaluation of a program and demonstrate how this framework supports syntactic proofs (in the style of subject reduction) for type-abstraction properties. Such properties have traditionally required semantic arguments; using syntax avoids the need to build a model for the language. We present various typed lambda calculi with principals, including versions that have mutable state and recursive types. Categories and Subject Descriptors: D.2.11 [Software Engineering]: Software Architectures— Information Hiding; Languages; D.3.1 [Programming Languages]: Formal Definitions and Theory—Syntax; Semantics; D.3.3 [Programming Languages]: Language Constructs and Fea- tures—Abstract data types; F.3.2 [Logics and Meanings of Programs]: Semantics of Program- ming Languages—Operational Semantics; F.3.3 [Logics and Meanings of Programs]: Studies of Program Constructs—Type Structure General Terms: Languages, Security, Theory, Verification Additional Key Words and Phrases: Operational semantics, parametricity, proof techniques, syn- tactic proofs, type abstraction 1. INTRODUCTION Programmers often use a notion of principal when designing the structure of a program.
    [Show full text]
  • Typescript Handbook 2
    1. TypeScript Handbook 2. Table of Contents 3. The TypeScript Handbook 4. Basic Types 5. Interfaces 6. Functions 7. Literal Types 8. Unions and Intersection Types 9. Classes 10. Enums 11. Generics This copy of the TypeScript handbook was generated on Friday, June 26, 2020 against commit 10ecd4 with TypeScript 3.9. The TypeScript Handbook About this Handbook Over 20 years after its introduction to the programming community, JavaScript is now one of the most widespread cross-platform languages ever created. Starting as a small scripting language for adding trivial interactivity to webpages, JavaScript has grown to be a language of choice for both frontend and backend applications of every size. While the size, scope, and complexity of programs written in JavaScript has grown exponentially, the ability of the JavaScript language to express the relationships between different units of code has not. Combined with JavaScript's rather peculiar runtime semantics, this mismatch between language and program complexity has made JavaScript development a difficult task to manage at scale. The most common kinds of errors that programmers write can be described as type errors: a certain kind of value was used where a different kind of value was expected. This could be due to simple typos, a failure to understand the API surface of a library, incorrect assumptions about runtime behavior, or other errors. The goal of TypeScript is to be a static typechecker for JavaScript programs - in other words, a tool that runs before your code runs (static) and ensure that the types of the program are correct (typechecked). If you are coming to TypeScript without a JavaScript background, with the intention of TypeScript being your first language, we recommend you first start reading the documentation on JavaScript at the Mozilla Web Docs.
    [Show full text]
  • Abstract Types
    Chapter 7 Abstract Types This chapter concludes the presentation of Miranda’s type system by introducing the abstract type mechanism, which allows the definition of a new type, together with the type expressions of a set of “interface” or “primitive” operations which permit access to a data item of the type. The definitions of these primitives are hidden, providing an abstract view of both code and data; this leads to a better appreciation of a program’s overall meaning and structure. The use of type expressions as a design tool and documentary aid has already been encouraged in previous chapters. The abstype construct (also known as an “abstract data type” or “ADT”1) defines the type expressions for a set of interface functions without specifying the function definitions; the benefits include the sep- aration of specifications from implementation decisions and the ability to provide programmers with the same view of different code implementations. In summary, Miranda’s abstype mechanism provides the following two new programming ben- efits: 1. Encapsulation. 2. Abstraction. Encapsulation There are considerable benefits if each programmer or programming team can be confident that their coding efforts are not going to interfere inadvertently with other programmers and that other programmers are not going to inadvertently affect their implementation details. This can be achieved by packaging a new type together with the functions which may manipulate values of that type. Furthermore if all the code required to manipulate the new type is collected in 1However, there is a subtle difference between Miranda’s abstype mechanism and traditional ADTs—see Section 7.1.2.
    [Show full text]
  • OMG Object Constraint Language (OCL)
    Date : January 2012 OMG Object Constraint Language (OCL) Version 2.3.1 without change bars OMG Document Number: formal/2012-01-01 Standard document URL: http://www.omg.org/spec/OCL/2.3.1 Associated Normative Machine-Readable Files: http://www.omg.org/spec/OCL/20090501/OCL.cmof http://www.omg.org/spec/OCL/20090502/EssentialOCL.emof * original file: ptc/2009-05-03 (has not changed since OCL 2.1) Copyright © 2003 Adaptive Copyright © 2003 Boldsoft Copyright © 2003 France Telecom Copyright © 2003 IBM Corporation Copyright © 2003 IONA Technologies Copyright © 2011 Object Management Group USE OF SPECIFICATION - TERMS, CONDITIONS & NOTICES The material in this document details an Object Management Group specification in accordance with the terms, conditions and notices set forth below. This document does not represent a commitment to implement any portion of this specification in any company's products. The information contained in this document is subject to change without notice. LICENSES The companies listed above have granted to the Object Management Group, Inc. (OMG) a nonexclusive, royalty-free, paid up, worldwide license to copy and distribute this document and to modify this document and distribute copies of the modified version. Each of the copyright holders listed above has agreed that no person shall be deemed to have infringed the copyright in the included material of any such copyright holder by reason of having used the specification set forth herein or having conformed any computer software to the specification. Subject to all
    [Show full text]
  • Gradual Security Typing with References
    2013 IEEE 26th Computer Security Foundations Symposium Gradual Security Typing with References Luminous Fennell, Peter Thiemann Dept. of Computing Science University of Freiburg Freiburg, Germany Email: {fennell, thiemann}@informatik.uni-freiburg.de Abstract—Type systems for information-flow control (IFC) The typing community studies a similar interplay between are often inflexible and too conservative. On the other hand, static and dynamic checking. Gradual typing [25], [26] is dynamic run-time monitoring of information flow is flexible and an approach where explicit cast operations mediate between permissive but it is difficult to guarantee robust behavior of a program. Gradual typing for IFC enables the programmer to coexisting statically and dynamically typed program frag- choose between permissive dynamic checking and a predictable, ments. The type of a cast operation reflects the outcome of conservative static type system, where needed. the run-time test performed by the cast: The return type of We propose ML-GS, a monomorphic ML core language with the cast is the compile-time manifestation of the positive test; references and higher-order functions that implements gradual a negative outcome of the test causes a run-time exception. typing for IFC. This language contains security casts, which enable the programmer to transition back and forth between Disney and Flanagan propose an integration of security static and dynamic checking. types with dynamic monitoring via gradual typing [11]. Such In particular, ML-GS enables non-trivial casts on reference an integration enables the stepwise introduction of checked types so that a reference can be safely used everywhere in a security policies into a software system.
    [Show full text]
  • EDAF50 – C++ Programming
    EDAF50 – C++ Programming 8. Classes and polymorphism. Sven Gestegård Robertz Computer Science, LTH 2020 Outline 1 Polymorphism and inheritance Concrete and abstract types Virtual functions Class templates and inheritance Constructors and destructors Accessibility Inheritance without polymorphism 2 Usage 3 Pitfalls 4 Multiple inheritance 8. Classes and polymorphism. 2/1 Polymorphism and dynamic binding Polymorphism Overloading Static binding Generic programming (templates) Static binding Virtual functions Dynamic binding Static binding: The meaning of a construct is decided at compile-time Dynamic binding: The meaning of a construct is decided at run-time Polymorphism and inheritance 8. Classes and polymorphism. 3/47 Concrete and abstract types A concrete type behaves “just like built-in-types”: I The representation is part of the definition 1 I Can be placed on the stack, and in other objects I can be directly refererred to I Can be copied I User code must be recompiled if the type is changed An Abstract type decouples the interface from the representation: I isolates the user from implementation details I The representation of objects (incl. the size!) is not known I Can only be accessed through pointers or references I Cannot be instantiated (only concrete subclasses) I Code using the abstract type does not need to be recompiled if the concrete subclasses are changed 1can be private, but is known Polymorphism and inheritance : Concrete and abstract types 8. Classes and polymorphism. 4/47 Concrete and abstract types A concrete type: Vector class Vector { public : Vector (int l = 0) : elem {new int[l]},sz{l} {} ~ Vector () { delete [] elem ;} int size () const { return sz;} int& operator []( int i) { return elem [i];} private : int * elem ; int sz; }; Generalize: extract interface class Container public : virtual int size () const ; virtual int& operator []( int o); }; Polymorphism and inheritance : Concrete and abstract types 8.
    [Show full text]
  • Abstract Types
    Chapter 15 Abstract Types The human heart has hidden treasures, In secret kept, in silence sealed. | Evening Solace, Charlotte Bronte 15.1 Data Abstraction A cornerstone of modern programming methodology is the principle of data abstraction, which states that programmers should be able to use data struc- tures without understanding the details of how they are implemented. Data abstraction is based on establishing a contract, also known as an application programming interface (API), or just interface, that speci¯es the abstract behavior of all operations that manipulate a data structure without describing the representation of the data structure or the algorithms used in the operations. The contract serves as an abstraction barrier that separates the concerns of the two parties that participate in a data abstraction. On one side of the barrier is the implementer, who is responsible for implementing the operations so that they satisfy the contract. On the other side of the barrier is the client, who is blissfully unaware of the hidden implementation details and uses the operations based purely on their advertised speci¯cations in the contract. This arrangement gives the implementer the flexibility to change the implementation at any time as long as the contract is still satis¯ed. Such changes should not require the client to modify any code.1 This separation of concerns is especially 1However, the client may need to recompile existing code in order to use a modi¯ed imple- mentation. 599 Draft November 23, 2004 600 CHAPTER 15. ABSTRACT TYPES useful when large programs are being developed by multiple programmers, many of whom may never communicate except via contracts.
    [Show full text]