Getting Started - Center for Computation and Technology

Getting Started - Center for Computation and Technology

Organizing Programs and Data Lecture 5 Hartmut Kaiser [email protected] http://www.cct.lsu.edu/hkaiser/spring_2015/csc1254.html We CSC 1254, Spring 2015, Organizing Programs and Data 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 Abstract 2 DRY - Dont 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 http://en.wikipedia.org/wiki/Don%27t_repeat_yourself 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data Programming Principle of the Day 3

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. Ive written and seen code that is super DRY but that doesnt contain a single abstraction and that group things in huge inheritance hierarchies. Code that is about as flexible and reusable as a sunken ship. http://joelabrahamsson.com/entry/the-dry-obsession 2/3/2015, Lecture 5 CSC 1254, Spring 2015, Organizing Programs and Data

Programming Principle of the Day 4 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 Building a program 5

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 doesnt work Throw away the first version and make another limited version Keep doing that until we find a version that were 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 Writing a program: Strategy 6

2/3/2015, Lecture 5 Writing a Program Designing a good program is genuinely difficult Its 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 CSC 1254, Spring 2015, Organizing Programs and Data Even experienced programmers make mistakes

Lots of mistakes; its a necessary part of learning 7 2/3/2015, Lecture 5 Organizing Programs and Data 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 CSC 1254, Spring 2015, Organizing Programs and Data We

8 break program into smaller parts 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 CSC 1254, Spring 2015, Organizing Programs and Data Two facilities to Functions Data structures 2/3/2015, Lecture 5 Organizing Programs and Data

9 2/3/2015, Lecture 5 Organizing Computations 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 + 0.4 * final + 0.4 * homework; } Function consists of Return type: double Name: grade (Optional) list of arguments: double midterm, final, homework Function body: { ... } CSC 1254, Spring 2015, Organizing Programs and Data For

10 2/3/2015, Lecture 5 Alternative Function Syntax 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"; } ); CSC 1254, Spring 2015, Organizing Programs and Data

C++11 allow to write functions as (requires g+ + 4.4, vs2010): 11 The have to be called (invoked) to be useful output statement we had earlier: cout << name << ", your final grade is: " << setprecision(3) << 0.2 * midterm + 0.4 * final + 0.4 * sum / count << setprecision(prec) << endl; Becomes now: cout << name << ", your final grade is: " << setprecision(3) << grade(midterm, final, sum / count) << setprecision(prec) << endl; CSC 1254, Spring 2015, Organizing Programs and Data

Functions 2/3/2015, Lecture 5 Organizing Computations 12 2/3/2015, Lecture 5 Calling Functions 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 CSC 1254, Spring 2015, Organizing Programs and Data Must 13 2/3/2015, Lecture 5 Calling Functions: Control Flow int square(int x) { i = 0; { while (i < 100) { return x * x;

square(i); ++i; i<100 } } i==10 0 } CSC 1254, Spring 2015, Organizing Programs and Data int main() 14 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]; } CSC 1254, Spring 2015, Organizing Programs and Data Encapsulate 2/3/2015, Lecture 5 Finding Medians 15 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)); } CSC 1254, Spring 2015, Organizing Programs and Data Grading 2/3/2015, Lecture 5 Reimplementing Grading Policy 16 2/3/2015, Lecture 5 Reimplementing Grading Policy 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 CSC 1254, Spring 2015, Organizing Programs and Data References: 17 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; Reference // error! 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 Reimplementing Grading Policy 18 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 Reimplementing Grading Policy 19 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 CSC 1254, Spring 2015, Organizing Programs and Data Reading 2/3/2015, Lecture 5 Reading Homework Grades 20 argument: references tell the intend to change the functions vector homework; read_hw(cin, homework); The

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

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? CSC 1254, Spring 2015, Organizing Programs and Data First 2/3/2015, Lecture 5 Reading Homework Grades 22

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; } CSC 1254, Spring 2015, Organizing Programs and Data

What 2/3/2015, Lecture 5 Reading Homework Grades 23 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 Reading Homework Grades 24 2/3/2015, Lecture 5 Calling Conventions

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 CSC 1254, Spring 2015, Organizing Programs and Data Fundamentally 25 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 Calling Conventions 26 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 Calling Conventions 27

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()); CSC 1254, Spring 2015, Organizing Programs and Data Call 2/3/2015, Lecture 5

Calling Conventions 28

Recently Viewed Presentations

  • PRESENCE Bonus: Biblical Foundatons Part 3 Secular Objections

    PRESENCE Bonus: Biblical Foundatons Part 3 Secular Objections

    How do you understand the arc of the bible story from Genesis to Revelation as the story of the Eucharist? ... About six-in-ten (63%) of the most observant Catholics — those who attend Mass at least once a week —...
  • 10 Ways to Use a Digital Camera in the Classroom

    10 Ways to Use a Digital Camera in the Classroom

    10 Ways to Use a Digital Camera in the Classroom. By: Cherie Ward ... Teachers may also allow students to zoom in on their own items and have students guess what the object is making a game of the activity.
  • Gas Cutting - Brent Payne

    Gas Cutting - Brent Payne

    Torch position, angle, motion Joints Plug Weld Use additional filler rod where joint design and strength require Positioning Tacking Shrinkage Wedge Turning on and shutting down the oxy acetylene welding outfit Cutting oxyfuel gas flame is used to heat the...
  • 3 Options in Ethics - R. Scott Smith, PhD

    3 Options in Ethics - R. Scott Smith, PhD

    (nominalism) seems to be the best fit with naturalism. Naturalism's Options in Ethics. Morality is a biological adaptation (Michael Ruse) Same-sex behavior is permissible because it is genetically determined. Right or wrong are a matter of the movement of body...
  • Energy Future @ Carleton By Richard Strong, Director

    Energy Future @ Carleton By Richard Strong, Director

    Energy Future @ Carleton By Richard Strong, Director of Facilities Minnesota Fuel Mix for Electricity Carleton Energy Use 1987-2003 Carleton Energy Use 1987-2003 Carleton Energy Use 1987-2003 Cost for Energy 1900-2002 Cost per CCF of Natural Gas Total Annual Cost...
  • Diapositiva 1 - Galicia

    Diapositiva 1 - Galicia

    O momento total tamén é cero. A barra está en equilibrio x 0,9-x 490N 588N 0 Un atleta levanta cunha man unha barra de 90 cm, con pesos ns seus extremos de 50 e 60 kg. Supoñemos que a barra...
  • Social Media Marketing - RSES

    Social Media Marketing - RSES

    Social Media Marketing - The Cost Social Media Marketing - The Reason Creative Concept-Branding "Everything We Do Is Marketing" Student Handout Follow-Up Postcards T-Shirt Handout T-Shirt Handout Display Banner Website/Landing Page Movie Theatre Promo Social Media Marketing-Q & A Contact...
  • Basic Components and Electric Circuits

    Basic Components and Electric Circuits

    Basic Nodal and Mesh Analysis * ... * We can eliminate the need for introducing a voltage variable by applying KVL to the supermesh formed by joining mesh 1 and mesh 3. Apply KVL to mesh 2: 1(i2 − i1)...