5. Subroutines

Total Page:16

File Type:pdf, Size:1020Kb

5. Subroutines IA010: Principles of Programming Languages 5. Subroutines Jan Obdržálek obdrzalek@fi.muni.cz Faculty of Informatics, Masaryk University, Brno IA010 5. Subroutines 1 Subroutines Subprograms, functions, procedures, . • principal mechanism for control abstraction • details of subroutine’s computation are replaced by a statement that calls the subroutine • increases readability: emphasizes logical structure, while hiding the low-level details • facilitate code reuse, saving • memory • coding time • subroutines vs OOP methods: • differ in the way they are called • methods are associated with classes and objects IA010 5. Subroutines 2 Outline Fundamentals of subroutines Parameter-passing methods Overloaded and generic subroutines Functions – specifics Coroutines IA010 5. Subroutines 3 Fundamentals of subroutines IA010 5. Subroutines 4 Subroutine characteristics • each subroutine has a single entry point • the calling program unit is suspended during subroutine execution (so only one subroutine is in execution at any given time) • control returns to the caller once subroutine execution is terminated • alternatives: • coroutines • concurrent units IA010 5. Subroutines 5 Basic definitions • subroutine definition – describes the interface and actions • subroutine call – an explicit request for the subroutine to be executed • active subroutine – has been executed, but has not yet completed its execution • subroutine header – part of the definition, specifies: • the kind of the subroutine (function/procedure) • a name (if not anonymous) • a list of parameters • parameter profile – the number, order and types of formal parameters • protocol – parameter profile + return type IA010 5. Subroutines 6 Procedures and functions procedures • do not return values • in effect define new statements • as functions: can return a value using • global variables • two-way communication through parameters functions • return values • function call is, in effect, replaced by the return value • as procedures: e.g. using the void return type • modelled after mathematical function (the model is faithful if no side-effects are allowed) IA010 5. Subroutines 7 Parameters Mechanism for passing data between a subroutine and its caller. (another option: through global variables) formal parameters (parameters) • specified in the subroutine header • sometimes called dummy variables actual parameters (arguments) • specified in the subroutine call statement binding of actual parameters to formal parameters • positional parameters – by position (first to first, . ) • keyword parameters – the formal parameter name is explicitly given in a call (in any order) attack(weapon = my_weapon, force = my_force) • when combined (e.g. Ada, Fortran95+, Python) once a keyword parameter appears, all remaining parameters must be keyworded IA010 5. Subroutines 8 Default parameter values A default value is used when the actual parameter is not given. both positional and keyword parameters def compute_pay(income, exemptions = 1, tax_rate) pay = compute_pay(20000.0, tax_rate = 0.15) • once a default parameter is omitted, all remaining formal parameters must be keyworded positional parameters only • parameters with default values must be listed last float compute_pay(float income, float tax_rate, int exemptions = 1) pay = compute_pay(20000.0, 0.15); • once a default parameter is ommitted, all remaining must have default values IA010 5. Subroutines 9 Variable number of parameters • problematic (type checking?) • can be useful (e.g. printf in C) • C – the programmer must explicitly process the parameters: int printf(const char *format, ...); accessed using va_list (stdarg.h) • C# – variable number of parameters of the same type public void DisplayList(params int[] list) { foreach(int next in list) { Console.WriteLine("Next value {0}", next); } } IA010 5. Subroutines 10 Parameter-passing methods IA010 5. Subroutines 11 Parameter-passing methods Semantic models 1 in mode (receive data from the actual parameters) 2 out mode (transmit data to the actual parameters) 3 inout mode Example • A subroutine takes two arrays list1 and list2, adds list1 to list2 and returns the result as revised list2. Also it returns a new array created from both arrays. • in: list1, inout: list2, out: the new list Conceptual models • copy the value • transmit the access path (usually using a pointer or a reference) Implementation models coming next ... IA010 5. Subroutines 12 Pass-by-Value • for in mode parameters • the value of the actual parametr initializes the corresponding formal parameter • usually implemented using copying (write-protection required if implemented using the access path) • advantages • fast for scalar values • disadvantages: • space needs to be allocated for the formal parameter • time and space needed to copy large objects (e.g. arrays) IA010 5. Subroutines 13 Pass-by-Result • for out mode parameters • no value is passed to the subroutine • the formal parameter acts as a normal variable • after completion, its value is copied to the actual paramter • the actual paramter must be a variable • advantages and disadvantages: • as for call-by value, plus • parameter collision • binding time choice IA010 5. Subroutines 14 Pass-by-Result problems Parameter collision void Fixer(out int x, out int y) { //C# x = 17; y = 35; } ... f.Fixer(out a, out a); Binding time choice (call vs return) void DoIt(out int x, int index){ //C# x = 17; index = 42; } ... sub = 21; f.DoIt(out list[sub], out sub); IA010 5. Subroutines 15 Pass-by-Value-Result • for inout mode parameters • combination of the previous two • sometimes called pass-by-copy • disadvantages follow the from pass-by-value and pass-by result (time and space requirements) IA010 5. Subroutines 16 Pass-by-Reference • for inout mode parameters • the access path (usually an address) is transmited • the actual parameter is effectively shared with the subroutine • advantages: • very efficient (time and space) • disadvantages: • slower access (indirect addressing) • risk of unintentionally changing actual parammeters (if used for one-way communication) • can create aliases (see next slide) IA010 5. Subroutines 17 Pass-by-Reference and aliases • Collision between actual parameters: void foo(int &bar, int &baz) ... foo(ouch, ouch) • Collision between array elements: (for i=j) foo(list[i], list[j]) • Collision between arrays and its elements: bar(list, list[i]) • Collision between formal parameters and non-local variables: int *global; //C void main() { ... sub(global); ... } void sub(int *param) { IA010 5. Subroutines 18 ... } Pass-by-Name • for inout mode parameters • very different from the previous models • actual parameters are textually substituted for the formal parameters • the referencing environment must also be passed to the subroutine • inefficient, hard to implement • complicated, decreases readability and reliability • Algol60, also available (but not default) in Scala • nowadays not used (exception: macros) IA010 5. Subroutines 19 Jensen’s device Exploits pass-by-name and side-effects. real procedure Sum(k, l, u, ak) value l, u; integer k, l, u; real ak; commentk and ak are passed by name; begin real s; s := 0; fork:=l step1 untilu do s := s + ak; Sum := s end; Pu • the code above computes k=l ak • is general: • summation over an array: Sum(i, 1, 100, V[i]) • double summation: Sum(i,l,m, Sum(j,l,n,A[i,j])) • summing squares: Sum(i,1,100,i*i) IA010 5. Subroutines 20 Parameter passing in common PLs • C • pass-by-value • pass-by-reference achieved using pointers • if formal parameters are pointers to constants, the actual parameters are write-protected • C++ • also contains a reference type (implicitly dereferenced) (pass-by-reference semantics) • write-protected if declared const void fun(const int &p1, int p2, int &p3) { ... } • Java • pass-by-value for all parameters • in effect pass-by-reference (objects are accessed only through references) • object reference passed as a parameter cannot be changed in the subroutine (but the referenced object can) • scalars cannot be passed by reference IA010 5. Subroutines 21 Parameter passing in common PLs • Ada, Fortran 95 • each parameter can be specified to be in, out, or inout • C# • pass-by-value by default • pass-by-reference can be requested using ref void sumer(ref int oldSum, int newOne) { ... } ... sumer(ref sum, newValue); • out parameters: passed by reference (declared out) IA010 5. Subroutines 22 Parameter passing in Python pass-by-assignment • all data values are objects (each variable is a reference to an object) • object references are passed by value • assignment does not affect the caller def foo(x): x = x + 1 x = 42 foo(x)#x= 42 • but for mutable objects the change is visible from the outside def bar(list): list[2] = 42 list = [1,2,3] bar(list)# list= [1,2,42] IA010 5. Subroutines 23 Type checking parameters • big impact on program reliability • nowadays almost always enforced (exceptions: Perl, JavaScript, PHP) • historically not: Fortran 77, early C • in C89 it is possible to choose whether the parameters will be checked • two ways of defining functions double sin(x) double x; { ... } • not type checked double sin(double x) { ... } • type checked • C99 and C++ support only the second method IA010 5. Subroutines 24 Passing multidimensional arrays • subroutine needs to know the array dimensions for addressing (at least the number of columns) • C/C++ • separate compilation • the mapping function is( address(m[i, j]) = address(m[0,0]) + i*columns + j) • the number of columns can be given in the formal parameter:
Recommended publications
  • Writing Fast Fortran Routines for Python
    Writing fast Fortran routines for Python Table of contents Table of contents ............................................................................................................................ 1 Overview ......................................................................................................................................... 2 Installation ...................................................................................................................................... 2 Basic Fortran programming ............................................................................................................ 3 A Fortran case study ....................................................................................................................... 8 Maximizing computational efficiency in Fortran code ................................................................. 12 Multiple functions in each Fortran file ......................................................................................... 14 Compiling and debugging ............................................................................................................ 15 Preparing code for f2py ................................................................................................................ 16 Running f2py ................................................................................................................................. 17 Help with f2py ..............................................................................................................................
    [Show full text]
  • New Inheritance Models That Facilitate Source Code Reuse in Object-Oriented Programming
    NEW INHERITANCE MODELS THAT FACILITATE SOURCE CODE REUSE IN OBJECT- ORIENTED PROGRAMMING By HISHAM M. AL-HADDAD Bachelor of Science Yarmouk University lrbid, Jordan 1986 Master of Science Northrop University Los Angeles, California 1988 Submitted to the Faculty of the Graduate College of the Oklahoma State University in partial fulfillment of the requirements for the degree of DOCTOR OF PHILOSOPHY July, 1992 Oklahoma Statt.' Ur1iv. Library NEW INHERITANCE MODELS THAT FACILITATE SOURCE CODE REUSE IN OBJECT- ORIENTED PROGRAMMING C/ wU::r-~ B I A~c;p .... _.-~ Dean of the Graduate CoUege ii PREFACE Code reusability is a primary objective in the development of software systems. The object-oriented programming methodology is one of the areas that facilitate the development of software systems by allowing and promoting code reuse and modular designs. Object-oriented programming languages (OOPLs) provide different facilities to attain efficient reuse and reliable extension of existing software components. Inheritance is an important language feature that is conducive to reusability and extensibility. Various OOPLs provide different inheritance models based on different interpretations of the inheritance notion. Therefore, OOPLs have different characteristics derived from their respective inheritance models. This dissertation is concerned with solutions for three major problems that limit the utilization of inheritance for code reusability. The range of object-oriented applications and thus the usage of object-oriented programming in general is also discussed. The three major problems are: 1) the relationship between inheritance and other related issues such as encapsulation, access techniques, visibility of inheritance, and subtyping; 2) the hierarchical structure imposed by inheritance among classes; and 3) the accessibility of previous versions of the modified methods defmed in classes located at higher levels of the inheritance structure than the parent classes.
    [Show full text]
  • Scope in Fortran 90
    Scope in Fortran 90 The scope of objects (variables, named constants, subprograms) within a program is the portion of the program in which the object is visible (can be use and, if it is a variable, modified). It is important to understand the scope of objects not only so that we know where to define an object we wish to use, but also what portion of a program unit is effected when, for example, a variable is changed, and, what errors might occur when using identifiers declared in other program sections. Objects declared in a program unit (a main program section, module, or external subprogram) are visible throughout that program unit, including any internal subprograms it hosts. Such objects are said to be global. Objects are not visible between program units. This is illustrated in Figure 1. Figure 1: The figure shows three program units. Main program unit Main is a host to the internal function F1. The module program unit Mod is a host to internal function F2. The external subroutine Sub hosts internal function F3. Objects declared inside a program unit are global; they are visible anywhere in the program unit including in any internal subprograms that it hosts. Objects in one program unit are not visible in another program unit, for example variable X and function F3 are not visible to the module program unit Mod. Objects in the module Mod can be imported to the main program section via the USE statement, see later in this section. Data declared in an internal subprogram is only visible to that subprogram; i.e.
    [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]
  • Code Reuse and Refactoring: Going Agile on Complex Products
    Code Reuse and Refactoring: Going Agile on Complex Products Using enterprise Software Version Management to coordinate complex products, seamlessly support Git developers, and solve refactoring problems. Table of Contents Component-Based Development __________________________________________________ 1 CBD Product Model ______________________________________________________________ 1 The Repository Model ____________________________________________________________ 2 Managing CBD in Git _____________________________________________________________ 2 Setting Up the CBD Model _____________________________________________________ 2 Incorporating Non-Software Components ____________________________________ 3 Updating Component Baselines ________________________________________________ 3 Submitting Patches to Components _____________________________________________ 4 Developer View _______________________________________________________________ 4 Refactoring: In Practice ________________________________________________________ 4 Refactoring: Developer Impact _________________________________________________ 4 Managing CBD in Perforce Software Version Management and Perforce Git Fusion ______ 5 Setting Up the CBD Model _____________________________________________________ 5 Incorporating Non-Software Components ____________________________________ 5 Updating Component Baselines ________________________________________________ 5 Submitting Patches to Components _____________________________________________ 5 Developer View _______________________________________________________________
    [Show full text]
  • A Model of Inheritance for Declarative Visual Programming Languages
    An Abstract Of The Dissertation Of Rebecca Djang for the degree of Doctor of Philosophy in Computer Science presented on December 17, 1998. Title: Similarity Inheritance: A Model of Inheritance for Declarative Visual Programming Languages. Abstract approved: Margaret M. Burnett Declarative visual programming languages (VPLs), including spreadsheets, make up a large portion of both research and commercial VPLs. Spreadsheets in particular enjoy a wide audience, including end users. Unfortunately, spreadsheets and most other declarative VPLs still suffer from some of the problems that have been solved in other languages, such as ad-hoc (cut-and-paste) reuse of code which has been remedied in object-oriented languages, for example, through the code-reuse mechanism of inheritance. We believe spreadsheets and other declarative VPLs can benefit from the addition of an inheritance-like mechanism for fine-grained code reuse. This dissertation first examines the opportunities for supporting reuse inherent in declarative VPLs, and then introduces similarity inheritance and describes a prototype of this model in the research spreadsheet language Forms/3. Similarity inheritance is very flexible, allowing multiple granularities of code sharing and even mutual inheritance; it includes explicit representations of inherited code and all sharing relationships, and it subsumes the current spreadsheet mechanisms for formula propagation, providing a gradual migration from simple formula reuse to more sophisticated uses of inheritance among objects. Since the inheritance model separates inheritance from types, we investigate what notion of types is appropriate to support reuse of functions on different types (operation polymorphism). Because it is important to us that immediate feedback, which is characteristic of many VPLs, be preserved, including feedback with respect to type errors, we introduce a model of types suitable for static type inference in the presence of operation polymorphism with similarity inheritance.
    [Show full text]
  • Beginning SOLID Principles and Design Patterns for ASP.NET Developers — Bipin Joshi Beginning SOLID Principles and Design Patterns for ASP.NET Developers
    THE EXPERT’S VOICE® IN .NET DEVELOPMENT Beginning SOLID Principles and Design Patterns for ASP.NET Developers — Bipin Joshi Beginning SOLID Principles and Design Patterns for ASP.NET Developers Bipin Joshi Beginning SOLID Principles and Design Patterns for ASP.NET Developers Bipin Joshi 301 Pitruchhaya Thane, India ISBN-13 (pbk): 978-1-4842-1847-1 ISBN-13 (electronic): 978-1-4842-1848-8 DOI 10.1007/978-1-4842-1848-8 Library of Congress Control Number: 2016937316 Copyright © 2016 by Bipin Joshi This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher's location, in its current version, and permission for use must always be obtained from Springer. Permissions for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution under the respective Copyright Law. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
    [Show full text]
  • Subroutines – Get Efficient
    Subroutines – get efficient So far: The code we have looked at so far has been sequential: Subroutines – getting efficient with Perl do this; do that; now do something; finish; Problem Bela Tiwari You need something to be done over and over, perhaps slightly [email protected] differently depending on the context Solution Environmental Genomics Thematic Programme Put the code in a subroutine and call the subroutine whenever needed. Data Centre http://envgen.nox.ac.uk Syntax: There are a number of correct ways you can define and use Subroutines – get efficient subroutines. One is: A subroutine is a named block of code that can be executed as many times #!/usr/bin/perl as you wish. some code here; some more here; An artificial example: lalala(); #declare and call the subroutine Instead of: a bit more code here; print “Hello everyone!”; exit(); #explicitly exit the program ############ You could use: sub lalala { #define the subroutine sub hello_sub { print "Hello everyone!\n“; } #subroutine definition code to define what lalala does; #code defining the functionality of lalala more defining lalala; &hello_sub; #call the subroutine return(); #end of subroutine – return to the program } Syntax: Outline review of previous slide: Subroutines – get efficient Syntax: #!/usr/bin/perl Permutations on the theme: lalala(); #call the subroutine Defining the whole subroutine within the script when it is first needed: sub hello_sub {print “Hello everyone\n”;} ########### sub lalala { #define the subroutine The use of an ampersand to call the subroutine: &hello_sub; return(); #end of subroutine – return to the program } Note: There are subtle differences in the syntax allowed and required by Perl depending on how you declare/define/call your subroutines.
    [Show full text]
  • Software Reusability: Approaches and Challenges
    International Journal of Research and Innovation in Applied Science (IJRIAS) |Volume VI, Issue V, May 2021|ISSN 2454-6194 Software Reusability: Approaches and Challenges Moko Anasuodei1, Ojekudo, Nathaniel Akpofure2 1Department of Computer Science and Informatics, Faculty of Science, Federal University Otuoke, Nigeria 2Department of Computer Science, Faculty of Natural and Applied Sciences, Ignatius Ajuru University of Education, Nigeria Abstract: Software reuse is used to aid the software phases. Software engineering has been more centered on development process which in recent times can improve the original development which gives an optimal software at a resulting quality and productivity of software development, by faster and less costly price, a design process based on assisting software engineers throughout various software systemic reusable is now recognized. engineering phases to enhance the quality of software, provide quick turnaround time for software development using few Software reuse reduces efforts and cost, because software people, tools, and methods, which creates a good software development costs can be extremely high, but they are quality by enhancing integration of the software system to shared, such that the cost of reuse can be extremely low. provide a competitive advantage. This paper examines the One major advantage of software reuse suggested by concept of software reuse, the approaches to be considered for keswani et al (2014) explains that there is a significant need software reuse, which is broadly shared into three categories: component-based software reuse, domain engineering and for the number of bugs to be reduced during software software product lines, architecture-based software reuse and development process, such that instead of developing an challenges that affect the software reuse development process.
    [Show full text]
  • COBOL-Skills, Where Art Thou?
    DEGREE PROJECT IN COMPUTER ENGINEERING 180 CREDITS, BASIC LEVEL STOCKHOLM, SWEDEN 2016 COBOL-skills, Where art Thou? An assessment of future COBOL needs at Handelsbanken Samy Khatib KTH ROYAL INSTITUTE OF TECHNOLOGY i INFORMATION AND COMMUNICATION TECHNOLOGY Abstract The impending mass retirement of baby-boomer COBOL developers, has companies that wish to maintain their COBOL systems fearing a skill shortage. Due to the dominance of COBOL within the financial sector, COBOL will be continually developed over at least the coming decade. This thesis consists of two parts. The first part consists of a literature study of COBOL; both as a programming language and the skills required as a COBOL developer. Interviews were conducted with key Handelsbanken staff, regarding the current state of COBOL and the future of COBOL in Handelsbanken. The second part consists of a quantitative forecast of future COBOL workforce state in Handelsbanken. The forecast uses data that was gathered by sending out a questionnaire to all COBOL staff. The continued lack of COBOL developers entering the labor market may create a skill-shortage. It is crucial to gather the knowledge of the skilled developers before they retire, as changes in old COBOL systems may have gone undocumented, making it very hard for new developers to understand how the systems work without guidance. To mitigate the skill shortage and enable modernization, an extraction of the business knowledge from the systems should be done. Doing this before the current COBOL workforce retires will ease the understanding of the extracted data. The forecasts of Handelsbanken’s COBOL workforce are based on developer experience and hiring, averaged over the last five years.
    [Show full text]
  • Subroutines and Control Abstraction
    Subroutines and Control Abstraction CSE 307 – Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Subroutines Why use subroutines? Give a name to a task. We no longer care how the task is done. The subroutine call is an expression Subroutines take arguments (in the formal parameters) Values are placed into variables (actual parameters/arguments), and A value is (usually) returned 2 (c) Paul Fodor (CS Stony Brook) and Elsevier Review Of Memory Layout Allocation strategies: Static Code Globals Explicit constants (including strings, sets, other aggregates) Small scalars may be stored in the instructions themselves Stack parameters local variables temporaries bookkeeping information Heap 3 dynamic allocation(c) Paul Fodor (CS Stony Brook) and Elsevier Review Of Stack Layout 4 (c) Paul Fodor (CS Stony Brook) and Elsevier Review Of Stack Layout Contents of a stack frame: bookkeeping return Program Counter saved registers line number static link arguments and returns local variables temporaries 5 (c) Paul Fodor (CS Stony Brook) and Elsevier Calling Sequences Maintenance of stack is responsibility of calling sequence and subroutines prolog and epilog Tasks that must be accomplished on the way into a subroutine include passing parameters, saving the return address, changing the program counter, changing the stack pointer to allocate space, saving registers (including the frame pointer) that contain important values and that may be overwritten by the callee, changing the frame pointer to refer to the new frame, and executing initialization code for any objects in the new frame that require it. Tasks that must be accomplished on the way out include passing return parameters or function values, executing finalization code for any local objects that require it, deallocating the stack frame (restoring the stack pointer), restoring other saved registers (including the frame pointer), and restoring the program counter.
    [Show full text]
  • Using Recursive Java Generics to Support Code Reuse in the CS2 Course
    Using Recursive Java Generics to Support Code Reuse in the CS2 Course J. Andrew Holey and Lynn R. Ziegler Department of Computer Science Saint John’s University and the College of Saint Benedict Collegeville, Minnesota 56321 [email protected] and [email protected] Abstract Showing students examples of code reuse in early Java programming courses is highly desirable, but one significant class of examples, linked data structures, is difficult to reuse and leads to frequent casting. We show a technique for using recursive generic parameters that significantly simplifies the inheritance of linked data structures, and we discuss the use of this technique in the CS2 course. 1 Introduction Java is well-established as the most frequently-used language in the first two programming courses at colleges and universities (CS1 and CS2). While there is serious and well-founded debate about whether other languages may be more appropriate for an introductory programming sequence at the college level, many computer science faculty members have become comfortable with using Java in these courses and are able to teach programming and problem-solving very effectively using this language. One of the advantages of using object-oriented languages like Java for teaching introductory programming is their support for the construction of abstract data types (ADTs). This support was enhanced in Java 5.0 with the introduction of generics. Libraries like the Java Collection Framework have reduced the emphasis on construction of ADTs in many CS2 courses, but most textbooks and instructors still choose to spend considerable time on the implementation of ADTs. It is now possible to guide students to produce simple and elegant implementations of the standards ADTs, including stacks, queues, various types of lists and trees, maps and even graphs.
    [Show full text]