Unformatted text preview:

TopicsDesign HeuristicsDesign Heuristics continuedReference parametersQuadratic Equation ExampleWho supplies memory, where’s copy?ExamplesAnother ExampleYet another exampleParameter Passing: const-referenceCount # occurrences of “e”General rules for ParametersStreams for reading filesInput file stream: Note similarity to cinFind longest word in file (most letters)Maximal and Minimal ValuesRead values, find largest (smallest)What about if ints are strings?Using classes to solve problemsComplete the code belowTwo problemsStringSet and WordIteratorSee setdemo.cppClasses: From Use to ImplementationAnatomy of the Dice classThe header file dice.hThe header file is a class declarationFrom interface to use, the class DiceHeader file as InterfaceWilliam H. (Bill) Gates, (b. 1955)From Interface to ImplementationImplementation, the .cpp fileMore on method implementationUnderstanding Class ImplementationsClass Implementation HeuristicsBuilding Programs and ClassesA Computer Science Tapestry6.1TopicsDecompositionParameter passingReading and writing from filesDesigning classesReadingChapter 6AssignmentBiorhythmsCD ReaderA Computer Science Tapestry6.2Design HeuristicsMake each function or class you write as single-purpose as possibleAvoid functions that do more than one thing, such as reading numbers and calculating an average, standard deviation, maximal number, etc.,•If source of numbers changes how do we do statistics?•If we want only the average, what do we do?Classes should embody one concept, not several. The behavior/methods should be closely relatedThis heuristic is called Cohesion, we want functions and classes to be cohesive, doing one thing rather than severalEasier to re-use in multiple contextsA Computer Science Tapestry6.3Design Heuristics continuedFunctions and classes must interact to be usefulOne function calls anotherOne class uses another, e.g., as the Dice::Roll() function uses the class RandGenKeep interactions minimal so that classes and functions don’t rely too heavily on each other, we want to be able to change one class or function (to make it more efficient, for example) without changing all the code that uses itSome coupling is necessary for functions/classes to communicate, but keep coupling looseChange class/function with minimal impactA Computer Science Tapestry6.4Reference parametersIt’s useful for a function to return more than one valueFind roots of a quadraticGet first and last name of a userFunctions are limited to one return valueCombine multiple return values in object (create a class)Use reference parameters to send values back from function•Values not literally returned•Function call sends in an object that is changed Sometimes caller wants to supply the object that’s changedstring s = ToLower("HEllO") // return type?string s = "HeLLo";ToLower(s); // return type?A Computer Science Tapestry6.5Quadratic Equation Examplevoid Roots(double a, double b, double c, double& root1, double& root2);// post: root1 and root2 set to roots of// quadratic ax^2 + bx + c// values undefined if no roots exist int main(){ double a,b,c,r1,r2; cout << "enter coefficients "; cin >> a >> b >> c; Roots(a,b,c,r1,r2); cout << "roots are " << r1 << " " << r2 << endl; return 0;}A Computer Science Tapestry6.6Who supplies memory, where’s copy?void Roots(double a, double b, double c, double& root1, double& root2);// post: root1 and root2 set to roots of// quadratic ax^2 + bx + c// values undefined if no roots exist For value parameter, the argument value is copied into memory that “belongs” to parameterFor reference parameter, the argument is the memory, the parameter is an alias for argument memorydouble x, y, w, z;Roots(1.0, 5.0, 6.0, x, y);Roots(1.0, w, z, 2.0, x); // no good, why?A Computer Science Tapestry6.7ExamplesWhat’s prototype for a function that rolls two N-sided dice Y times and returns the number of double 1’s and double N’sHow many input parameters?How many values returned? (reference parameters)Return type of function?Name of function and parameters?void DoubleCount(int sides, int rollCount, int& snakeEyeCount, int& boxCarCount);// pre: sides > 0, rollCount > 0// post: returns # double 1’s (snakeEyeCount)// returns # double N’s N=sides(boxCarCount)A Computer Science Tapestry6.8Another ExampleWhat’s prototype for a function that returns the number of hours, minutes, and seconds in N seconds?Number of input parameters?Number of output parameters?void SecondsToHours(int& seconds, int& hours, int& minutes);// pre: seconds > 0// post: converts to hours/minutes/seconds, and// returns values in three parameters// Note: seconds is in/out parameterA Computer Science Tapestry6.9Yet another exampleWhat’s prototype for a function that returns the number of Saturdays and the number of Sundays in a year?How many input parameters?How many output parameters?Name of function and parameters?void SatSunCount(int year, int& saturdayCount, int& sundayCount);//post: returns # saturdays and sundays in year// via corresponding parametersA Computer Science Tapestry6.10Parameter Passing: const-referenceWhen parameters pass information into a function, but the object passed doesn’t change, it’s ok to pass a copyPass by value means pass a copyMemory belongs to parameter, argument is copiedWhen parameter is altered, information goes out from the function via a parameter, a reference parameter is usedNo copy is made when passing by referenceMemory belongs to argument, parameter is aliasSometimes we want to avoid the overhead of making the copy, but we don’t want to allow the argument to be changed (by a malicious function, for example)const-reference parameters avoid copies, but cannot be changed in the functionA Computer Science Tapestry6.11Count # occurrences of “e”Look at every character in the string, avoid copying the stringint LetterCount(const string& s, const string& letter)// post: return number of occurrences of letter in s{ int k, count = 0, len = s.length(); for(k=0; k < len; k++) { if (s.substr(k,1) == letter) { count++; } } return count;} Calls below are legal (but won’t be if just


View Full Document

Duke CPS 006 - Lecture

Download Lecture
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?