Procedural Abstraction

Similar documents
Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

Lecture 5 Abstract Data Types

Documentation (and midterm review)

PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO Course: 10550A; Duration: 5 Days; Instructor-led

Programming in Visual Basic with Microsoft Visual Studio 2010

CSE 143: Computer Programming II Winter 2019 HW6: AnagramSolver (due Thursday, Feb 28, :30pm)

CSE 143: Computer Programming II Summer 2017 HW5: Anagrams (due Thursday, August 3, :30pm)

Thread Programming. Comp-303 : Programming Techniques Lecture 11. Alexandre Denault Computer Science McGill University Winter 2004

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

CS 142 Style Guide Grading and Details

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Outline. Object Oriented Programming. Course goals. Staff. Course resources. Assignments. Course organization Introduction Java overview Autumn 2003

CSE 143: Computer Programming II Summer 2015 HW6: 20 Questions (due Thursday, August 13, :30pm)

CS558 Programming Languages

CSE143X: Computer Programming I & II Programming Assignment #9 due: Monday, 11/27/17, 11:00 pm

Programming Languages and Techniques (CIS120)

CSE 143: Computer Programming II Spring 2015 HW7: 20 Questions (due Thursday, May 28, :30pm)

CS1004: Intro to CS in Java, Spring 2005

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

Early programming languages ca. 1960

Iteration Abstraction

CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM

Testing and Debugging

H212 Introduction to Software Systems Honors

Grade Weights. Language Design and Overview of COOL. CS143 Lecture 2. Programming Language Economics 101. Lecture Outline

CITS5501 Software Testing and Quality Assurance Formal methods

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Comp Intermediate Programming EXAM #2 March 30, 2005 Rice University - Instructors: Cox & Nguyen

COMP-202: Foundations of Programming. Lecture 26: Review; Wrap-Up Jackie Cheung, Winter 2016

Classes, interfaces, & documentation. Review of basic building blocks

Comparing procedure specifications

Initial Coding Guidelines

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Fortgeschrittene objektorientierte Programmierung (Advanced Object-Oriented Programming)

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

D Programming Language

Lecture 10: building large projects, beginning C++, C++ and structs

Subclassing for ADTs Implementation

Assertions. Assertions - Example

CMPSCI 187 / Spring 2015 Implementing Sets Using Linked Lists

CS 101 Fall 2005 Midterm 2 Name: ID:

CS 231 Data Structures and Algorithms, Fall 2016

COP 3330 Final Exam Review

Lesson 3: Accepting User Input and Using Different Methods for Output

University of Utah School of Computing

6.005 Elements of Software Construction Fall 2008

Chapter 6 Introduction to Defining Classes

A Java Execution Simulator

CE221 Programming in C++ Part 1 Introduction

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Summer Session 2004 Prelim I July 12, CUID: NetID:


CSE331 Winter 2014, Midterm Examination February 12, 2014

Object Oriented Programming

Comp Intermediate Programming EXAM #1 February 16, 2004 Rice University - Instructors: Cox & Nguyen

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions

Programming Languages and Techniques (CIS120)

Absolute C++ Walter Savitch

Goal of lecture. Object-oriented Programming. Context of discussion. Message of lecture

Programming Languages and Techniques (CIS120)

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

CSCI 355 LAB #2 Spring 2004

Part 1: Group Brainstorm (NO computers during this time) Part 2: Submit Individual Brainstorm (You can now use a computer)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Administration. Objects and Arrays. Objects. Agenda. What is an Object? What is a Class?

The Dynamic Typing Interlude

PREPARING FOR PRELIM 1

Exceptions and Design

References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 10/14/2004 1

3 ADT Implementation in Java

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Programming II (CS300)

6.001 Notes: Section 8.1

Lecture 5 Representation Invariants

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

EINDHOVEN UNIVERSITY OF TECHNOLOGY

END TERM EXAMINATION

List ADT. Announcements. The List interface. Implementing the List ADT

CS2110 Assignment 3 Inheritance and Trees, Summer 2008

Welcome to CS 135 (Winter 2018)

Midterms Save the Dates!

About this exam review

C++ for Java Programmers

Programming. Syntax and Semantics

VALLIAMMAI ENGINEERING COLLEGE

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

COE318 Lecture Notes Week 4 (Sept 26, 2011)

CMPSCI 187 / Spring 2015 Postfix Expression Evaluator

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently.

CS121/IS223. Object Reference Variables. Dr Olly Gotel

CS558 Programming Languages

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

Transcription:

Procedural Abstraction Comp-303 : Programming Techniques Lecture 5 Alexandre Denault Computer Science McGill University Winter 2004 February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 1

Announcements... The classroom for Thursday s tutorial has still not been determined. Pizza and Beverages will be held next Thursday at 17:30, first floor Trottier. Assignment 1 will be handed out... now! February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 2

Last lecture... What is UML and why learn it? References and Tools for UML Class diagrams Elements of a class Relations ( Hierarchy, Contains, Uses ) Cardinality Notes Putting it all together State diagrams Sequence diagrams Requirements & Specifications February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 3

Procedural abstraction Abstracting a single action using parameterization and specification. Parameterization abstracts from the identity of the data being used, allowing the procedure to be used in more situations. relevant: presence, number, types of parameters irrelevant: identity of parameters Specification abstracts from the realization of the action, allowing multiple implementations. relevant: what is done irrelevant: how it is done February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 4

Benefits Benefits of abstraction by specification Locality The implementation of an abstraction can be read or written without needing to examine the implementations of any other abstractions. The abstraction can be used without examining its implementation. Modifiability An abstraction can be re-implemented without requiring changes to any abstractions that use it. February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 5

Specifications Specifications should be precise. Specifications can be written in a formal language or in an informal language. Formal specification languages have a precise meaning and can be checked automatically or even used to generate code (Comp 304). Informal specifications are easier to read or write but harder to give precise meaning. We will use informal English in comments to define specifications. February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 6

Specifications of procedural abstractions A function header is formal form of specification : name order and type of parameters return type visibility We can improve on this by adding some informal specification : REQUIRES specifies use constraints MODIFIES lists modified inputs/side-effects EFFECTS describes behavior for inputs complying to requirements, outputs and modifications February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 7

An example: SquareRoot public float squareroot (float x) { // REQUIRES: x should be positive // MODIFIES: nothing // EFFECTS: returns an approximation of square root of x } February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 8

Another example: Arrays public class Arrays { // OVERVIEW: stand-alone procedures for manipulating arrays of integers public static int search (int [ ] a, int x) // EFFECTS: if x is in a, returns the index where x is stored // otherwise returns -1 public static int searchsorted (int [ ] a, int x) // REQUIRES: a is sorted in ascending order // EFFECTS: if x is in a, returns the index where x is stored // otherwise returns -1 } public static void sort (int [ ] a) // MODIFIES: a // EFFECTS: Rearranges the elements of a in ascending order // e.g. if a = {3,1,6,1}, a_post={1,1,3,6} February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 9

Additional explanation: Arrays MODIFIES is omitted if no modifications happen. In other words, the properties of parameter objects or global objects are unchanged. If modifications does occur, the state before the procedure is invoked should be related to the state after the procedure returns (the change should be explained). REQUIRES is omitted if the procedure if nothing is expected of the total. In other words, the procedure functions correctly with any input. EFFECTS should always be specified. A function should always do something. Examples can be used to clarify specifications. February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 10

New Objects In general, with Java, we tend to favor creating new objects over modifying old ones. Since Java is Garbage Collected, old unused objects are eventually automatically disposed. This allows us to turn some mutable objects into immutable objects. The following is an example of favoring object creation over modifying old ones: public static int [ ] boundarray (int [ ], int n) // EFFECTS: Returns a new array containing the // elements of a in the order they appear in a except // that any elements of a > n are replaced by n February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 11

Implicit Inputs Sometime, the parameters of a function are not found in the function header. These parameters are called implicit inputs. When using implicit inputs, they should be properly documented in the specification. Here is an example of a function using implicit inputs. public static void copyline() // REQUIRES: System.in contains a line of text // MODIFIES: System.in and System.out // EFFECTS: Reads a line of text from System.in, advances cursor // in System.in to end of line, writes the line on System.out February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 12

Implementing procedures Specifications are written first. Procedure bodies are added later. Implementations should modify only those inputs specified in MODIFIES clause. Implementations should produce results according to EFFECTS clause if REQUIRES clause holds. February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 13

SearchSorted public static int searchsorted (int [ ] a, int x) { // REQUIRES: a is sorted in ascending order // EFFECTS: if x is in a, returns the index where x is stored // otherwise returns -1 // uses linear search... } If a is unsorted, we will get the wrong. If a is null, we return -1 (or we could throw an exception) Includes comment on algorithm used. February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 14

Designing Procedural Abstractions Procedures are introduced to shorten the calling code, clarify structure, and reduce code duplication. Sometimes, a piece of code in a procedure can be further subdivided into another function. These subfunctions have a well-defined purpose and allows to separate details of the subfunction from the main function. However, we must be careful. Further decomposition could be counter-productive. Rule of thumb #1: if you have trouble naming the subprocedure, then it probably shouldn t be separated. Rule of thumb #2: if you see almost identical code repeated twice, then it is probably useful to define a procedure. February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 15

Properties of procedures Minimally constraining: a specification should constrain details of the procedure only to the extent necessary. Only details that matter to the user are constrained to leave the implementor the greatest freedom for efficient implementations. Undetermined: a procedure is considered undetermined if the acceptable output is a set (as opposed to a unique output). Deterministic Implementation: these procedures will produce exactly the same output when give the same input. Undetermined procedures can be non-deterministic, but it usually takes extra program effort. February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 16

Properties of procedures Generality: a specification is more general if it can handle a larger class of inputs. For example: working with any size of array instead of fixed size Simplicity: procedures should have a well-defined purpose, easy to explain, independent of context of use. If it is hard to name the procedure there may be a problem. February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 17

Partial vs. total procedures A procedure is total if its behavior is specified for all legal inputs. Otherwise it is partial. Partial procedures are always specified with a REQUIRES clause. They are less safe than total procedures, and should only be used: when the context of use is limited (private helper procedures). when they enable a substantial benefit such as better performance. Library procedures intended for general use should always be total. February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 18

Summary A procedure is a mapping from inputs to outputs, with possible modification of inputs. Its specification describes its behavior, providing a contract between users and implementors. The specification does not change when the implementation changes. This provides locality and modifiability. Specifications should be minimal and can be undetermined / non-deterministic. Desirable properties include simplicity and generality. Implementations should be total when possible, and may be partial when the context of use is limited and controlled, such as for private helper procedures. February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 19

Assignment 1 In this assignment, you must implement the BigInt data abstraction. You may not use floating point numbers or any of the Big* number classes provided by Java. BigInt can store integer numbers from -2^120 to 2^120 no loss of precision. These numbers must be stored in 4 integers (part1, part2, part3, part4). a) fill in the bodies of the methods of class BigInt b) add methods "boolean smallerthan(bigint other)" and "boolean largerthan(bigint other)" with specifications and test code. Bonus: add a "BigInt divide(bigint other)" method with specifications and test code. Make sure you respect specifications. This means that a method without REQUIRES specifications should accept all inputs (Total implementation), and that a method with REQUIRES specs should preserve those specs. February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 20

BigInt class public class BigInt { // OVERVIEW: this class implements BigInt numbers // BigInt numbers consist of a large number store in 4 intergers. You are // free to choose how the number will be store. The only condition is that // all four integers (and no other) must be used to store the numerial part // of the number. // // (Can t start adding float, integers or arrays to store number.) // // A BigInt is printed with an apostrophy every three characters. // for example 123 456 789 123 465 000 // If the number is larger than 2^120 or smaller than -(2^120), the BigInt // number is "Not a Number" (NaN). Any operation involving a NaN has a NaN // as a result. For predicates (methods returning a boolean), NaN is // considered to be larger than any other number. BigInt numbers are // immutable. February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 21

Methods to implement // -- constructors -- public BigInt (int n) { // -- inherited from Object -- public String tostring () { public boolean equals (Object o) { // -- predicates -- public boolean ispositive () { public boolean isnegative () { // -- arithmetic -- public BigInt add (BigInt other) { public BigInt subtract (BigInt other) { public BigInt multiply (BigInt other) { public BigInt negation () { public BigInt absolutevalue () { public BigInt square () { public BigInt cube () { public BigInt power (int degree) { February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 22

Testing BigInt a = new BigInt(123456789); BigInt b = new BigInt(2); BigInt c = new BigInt(-444444444); BigInt d = new BigInt(999999999); BigInt f = new BigInt(0); System.out.println(a); System.out.println(b); System.out.println(a.add(b)); System.out.println(a.subtract(b)); System.out.println(a.multiply(b)); System.out.println(a.square()); System.out.println(a.cube()); System.out.println(a.cube().add(a.cube())); System.out.println(a.subtract(c)); System.out.println(c.power(125)); System.out.println(c.absoluteValue().negation()); System.out.println(c.power(125).multiply(f)); System.out.println(a.equals(a)); February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 23

Policies on Cooperation You are free to discuss this assignment with your friends. You may NOT share code with your friends. If you do work with someone, mention it in your header. I cannot give a failing grade to students I find cheating...... I can report him to the Dean of Science. February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 24

Hints Think before you code. How am I going to store the numbers? What base? Obvious trick to make the assignment simpler. Create many more test cases. Start early. It s a lot trickier than it looks. The assignment is due Tuesday, February 3th at 11:55 pm February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 25

Tool of the day: JCreator JCreator is a powerful IDE for Java. It provides the user with a wide range of functionality: Project management Project templates Code-completion Debugger interface Editor with syntax highlighting and so on... It s Free! You can find more information at http://www.jcreator.com/ February 16, 2004 Lecture 5 Comp 303 : Programming Techniques Page 26