Organizing Programs and Data Lecture 5 Hartmut Kaiser

Slides:



Advertisements
Similar presentations
Chapter 6 Writing a Program
Advertisements

Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
 Monday, 9/30/02, Slide #1 CS106 Introduction to CS1 Monday, 9/30/02  QUESTIONS (on HW02, etc.)??  Today: Libraries, program design  More on Functions!
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
Computer Science 1620 Programming & Problem Solving.
CS 201 Functions Debzani Deb.
Chapter 1 Principles of Programming and Software Engineering.
Programming Fundamentals (750113) Ch1. Problem Solving
OBJECT ORIENTED PROGRAMMING IN C++ LECTURE
1 CSC241: Object Oriented Programming Lecture No 07.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
DCT 1123 PROBLEM SOLVING & ALGORITHMS INTRODUCTION TO PROGRAMMING.
JS Arrays, Functions, Events Week 5 INFM 603. Agenda Arrays Functions Event-Driven Programming.
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
5.1 and 5.4 through 5.6 Various Things. Terminology Identifiers: a name representing a variable, class name, method name, etc. Operand: a named memory.
Organizing Programs and Data 2 Lecture 7 Hartmut Kaiser
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Chapter 9 Defining New Types. Objectives Explore the use of member functions when creating a struct. Introduce some of the concepts behind object-oriented.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
CSC 221: Computer Programming I Fall 2001  top-down design  approach to problem solving, program design  focus on tasks, subtasks, …  reference parameters.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Chapter 6 Writing a Program John Keyser’s Modification of Slides by Bjarne Stroustrup
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
CSE 219 Computer Science III Program Design Principles.
Case Study - Fractions Timothy Budd Oregon State University.
Defining New Types Lecture 21 Hartmut Kaiser
SE: CHAPTER 7 Writing The Program
CS 320 Assignment 1 Rewriting the MISC Osystem class to support loading machine language programs at addresses other than 0 1.
Controlling Function Behavior Sequence, Selection and Repetition.
Introduction CS 3358 Data Structures. What is Computer Science? Computer Science is the study of algorithms, including their  Formal and mathematical.
File I/O ifstreams and ofstreams Sections 11.1 &
C++ Functions. Objectives 1. Be able to implement C++ functions 2. Be able to share data among functions 2.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.
CPS120: Introduction to Computer Science Functions.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Working with Batches of Data Lecture 4 Hartmut Kaiser
Looping and Counting Lecture 3 Hartmut Kaiser
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 6 Writing a Program Hartmut Kaiser
The Software Development Process
1 CSCD 326 Data Structures I Software Design. 2 The Software Life Cycle 1. Specification 2. Design 3. Risk Analysis 4. Verification 5. Coding 6. Testing.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
1 CS161 Introduction to Computer Science Topic #9.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Writing Generic Functions Lecture 20 Hartmut Kaiser
Chapter 3 Working with Batches of Data. Objectives Understand vector class and how it can be used to collect, store and manipulate data. Become familiar.
Using Sequential Containers Lecture 8 Hartmut Kaiser
1 The Software Development Process ► Systems analysis ► Systems design ► Implementation ► Testing ► Documentation ► Evaluation ► Maintenance.
Session 7 Introduction to Inheritance. Accumulator Example a simple calculator app classes needed: –AdderApp - contains main –AddingFrame - GUI –CloseableFrame.
Manipulator example #include int main (void) { double x = ; streamsize prec = cout.precision(); cout
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 4: Introduction to C: Control Flow.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Programming Fundamentals Enumerations and Functions.
Chapter 4 Organizing Programs and Data. Objectives Understand the use of functions in dividing a program into smaller tasks. Discover how parameters can.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
Chapter 6 Writing a Program Bjarne Stroustrup
Loop Design What goes into coding a loop. Considerations for Loop Design ● There are basically two kinds of loops: ● Those that form some accumulated.
 Problem Analysis  Coding  Debugging  Testing.
Motivation for Generic Programming in C++
Functions Inputs Output
OOP vs Structured Programming
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
Programming Fundamentals (750113) Ch1. Problem Solving
Defining New Types Lecture 22 Hartmut Kaiser
Presentation transcript:

Organizing Programs and Data Lecture 5 Hartmut Kaiser

Abstract We will discuss functions as the main means of organizing computation. We rework the student grades example to be more modularized. 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 2

Programming Principle of the Day DRY - Don’t repeat yourself (DIE – Duplication is Evil)  The probably single most fundamental tenet in programming is to avoid repetition.  Many programming constructs exist solely for that purpose (e.g. loops, functions, classes, and more).  As soon as you start repeating yourself - create a new abstraction. Every piece of knowledge must have a single, unambiguous, authoritative representation within a system (program) Tightly related to the Open/Closed Principle and the Liskov Substitution Principle 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 3

Programming Principle of the Day I wish I had been taught more about the importance of variable and method naming in school. About writing code that speaks to the reader. Code that is clear and concise. Code that solves the problem in an efficient way but also communicates what it does and why from the perspective of the user. I wish I had been taught more about how to write components that could be changed without actually changing that specific code at all. I wish I had been taught more about polymorphism and composition. About how to structure applications not with a focus on reuse but on change. About why abstractions matter. I’ve written and seen code that is super DRY but that doesn’t contain a single abstraction and that group things in huge inheritance hierarchies. Code that is about as flexible and reusable as a sunken ship.  2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 4

Building a program Analysis  Refine our understanding of the problem  Think of the final use of our program Design  Create an overall structure for the program Implementation  Write code  Debug  Test Go through these stages repeatedly 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 5

Writing a program: Strategy What is the problem to be solved?  Is the problem statement clear?  Is the problem manageable, given the time, skills, and tools available? Try breaking it into manageable parts  Do we know of any tools, libraries, etc. that might help?  Yes, even this early: iostreams, vector, etc. Build a small, limited version solving a key part of the problem  To bring out problems in our understanding, ideas, or tools  Possibly change the details of the problem statement to make it manageable If that doesn’t work  Throw away the first version and make another limited version  Keep doing that until we find a version that we’re happy with Build a full scale solution  Ideally by using part of our initial version 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 6

Writing a Program Even experienced programmers make mistakes  Lots of mistakes; it’s a necessary part of learning Designing a good program is genuinely difficult It’s often faster to let the compiler detect gross mistakes than to try to get every detail right the first time  Concentrate on the important design choices Building a simple, incomplete version allows us to experiment and get feedback  Good programs are “grown” 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 7

Organizing Programs and Data We have been using standard data structures and algorithms, where each:  Solves a particular problem  Is independent from the others  Has a name Our program (computing student grades) has only the first of these qualities  For larger programs the goal is to achieve all three  Code gets unmanageable 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 8

Organizing Programs and Data Two facilities to break program into smaller parts  Functions  Data structures Today we will look at organizing computations: i.e. functions  Functions are a way to encapsulate a piece of work  Reuse: avoid redoing explicit computation  Naming: allow to think in more abstract terms  Encapsulation: hide implementation details 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 9

Organizing Computations For example, compute overall grade from pre-computed homework, midterm and final grades // compute a student's overall grade from midterm and final exam // grades and homework grade double grade(double midterm, double final, double homework) { return 0.2 * midterm * final * homework; } Function consists of  Return type: double  Name: grade  (Optional) list of arguments: double midterm, final, homework  Function body: {... } 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 10

Alternative Function Syntax C++11 allow to write functions as (requires g++ 4.4, vs2010): auto grade(double midterm, double final, double homework) -> double {... }  In this case no real value, but we will see sensible use cases later  Exception: lambda functions, have no name, they use [] instead (requires g++ 4.4, vs2010): std::foreach( words.begin(), words.end(), [](std::string s) { std::cout << s << "\n"; } ); 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 11

Organizing Computations Functions have to be called (invoked) to be useful The output statement we had earlier: cout << name << ", your final grade is: " << setprecision(3) << 0.2 * midterm * final * sum / count << setprecision(prec) << endl; Becomes now: cout << name << ", your final grade is: " << setprecision(3) << grade(midterm, final, sum / count) << setprecision(prec) << endl; 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 12

Calling Functions Must match: name, supplied argument count, argument (type) sequence Each argument initializes a newly created instance of the corresponding parameter The parameters behave like ordinary local variables inside the function  Call by value: the parameters are initialized from a copy of the argument 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 13

Calling Functions: Control Flow 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 14 int square(int x) { return x * x; } int main() { i = 0; while (i < 100) { square(i); ++i; } i<100 i==100

Finding Medians Encapsulate finding a median // compute the median of a vector // note: calling this function copies the whole vector double median(vector vec) { auto size = vec.size(); if (size == 0) throw domain_error("vector is empty, median undefined"); sort(vec.begin(), vec.end()); auto mid = size / 2; return size % 2 == 0 ? (vec[mid] + vec[mid-1]) / 2 : vec[mid]; } 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 15

Reimplementing Grading Policy Grading policy: // Compute a student's overall grade from midterm and // final exam grades and all homework grades. // This function does not copy the vector argument // (as median does so for us). double grade(double midterm, double final, vector const& hw) { if (hw.size() == 0) throw domain_error("student has done no homework"); return grade(midterm, final, median(hw)); } 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 16

Reimplementing Grading Policy References: vector const& hw;  Const reference to a vector of double  Defines a new name for an object (here argument) vector homework; vector & hw = homework; // 'hw' is a synonym for 'homework‘  Anything we do with hw is equivalent to doing the same thing to homework (and v.v.)  Adding the const creates a read-only synonym 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 17

Reimplementing Grading Policy References  Reference to a reference is still a reference to the original object vector & hw1 = hw; vector const& chw = hw1; Constness is preserved: vector & hw1 = chw; // error! Reference as parameter asks to get access to the original object (the argument)  No copying! 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 18

Reimplementing Grading Policy Function named grade()  Same name as existing function: overloading  No ambiguity as their parameters have different types Error checking  Checked same error as in median() function  Better error message 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 19

Reading Homework Grades Reading an arbitrary number of doubles into a vector // read homework grades from an input stream into a // vector istream& read_hw(istream& in, vector & hw) { // to be filled... return in; } Returns 2 things:  Whether input operation was successful  The data itself 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 20

Reading Homework Grades Non-const references tell the intend to change the functions argument: vector homework; read_hw(cin, homework); The function changes the data and the state of cin Returns another reference, the same object which was passed: // now this: if (read_hw(cin, homework)) { /*... */ } // is equivalent to: read_hw(cin, homework); if (cin) { /*... */ } 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 21

Reading Homework Grades First attempt: istream& read_hw(istream& in, vector & hw) { double x; while (in >> x) hw.push_back(x); return in; } Not quite right? Why?  What is if hw already holds elements?  What if cin is in an error state? 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 22

Reading Homework Grades What about this solution: // read homework grades from an input stream // into a vector istream& read_hw(istream& in, vector & hw) { if (in) { hw.clear(); // get rid of previous contents // read homework grades double x; while (in >> x) hw.push_back(x); // clear the stream so that input will work for // the next student in.clear(); } return in; } 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 23

Reading Homework Grades istream::clear() vs. vector<>::clear()  Different semantics!  istream::clear() resets error state  vector<>::clear() deletes all entries 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 24

Calling Conventions Fundamentally different treatment of vector :  median()  vector : copies all data  grade()  vector const& : no copy, read-only access  read_hw()  vector & : no copy, read-write access 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 25

Calling Conventions Call by value  Default behavior  Copies the data passed as an argument  Proper thing to do for  Small data types (int, double, etc.)  If a copy is required anyways  Any modification to the parameters will not be reflected for the arguments 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 26

Calling Conventions Call by const reference  Parameter needs explicit annotation (const&)  Does not copy the data itself, but creates a read-only reference to the original data  Proper thing to do for  Larger data types (efficiency)  Function does not change the value of parameters 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 27

Calling Conventions Call by (non-const) reference  Parameter needs explicit annotation (&)  Does not copy the data itself, but creates a read-write reference to the original data  Proper thing to do for  Any data types (not only for efficiency)  Function does change the value of parameters  Way to ‘return’ several things from a functions  Any modification to the parameters will be reflected for the arguments  Arguments need to be ‘lvalues’, so this will not work: // function returning the vector of homework grades vector get_homework() {...} // this does not work, as return values are not 'lvalues' read_hw(cin, get_homework()); 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data 28