How to Think Like a Programmer

# How to Think Like a Programmer

## How to Think Like a Programmer

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
##### Presentation Transcript

1. How to Think Like a Programmer CS 21a: Introduction to Computing I First Semester, 2013-2014

2. Last Time… • Civilization advances by extending the number of operations that we can perform without thinking about them. • Alfred North Whitehead (1861-1947)

3. Outline • Motivational Activity • Thinking About Programming • Proper Writing Practice • Abstraction • Practice Problems

4. Motivational Activity

5. Try Writing Down the Following • Instructions for Shampooing Hair • Your Weekly Schedule • How to Make a Notebook

6. Shampooing Hair • Open the bottle of shampoo. • Don’t have to say how to open a bottle • “Open” is considered a primitive operation.

7. Shampooing Hair • Pour a generous amount of shampoo onto hand. • “Generous amount” isn’t really specific. • Not too important for shampooing hair • An exact amount like “10 mL” is important if this were a manufacturing process involving dangerous chemicals.

8. Shampooing Hair • The amount of shampoo needed can depend upon hair length. • We say that the amount of shampoo and the hair length are variables. • Hair length is an input parameter. • The amount of shampoo is a function of hair length.

9. Shampooing Hair • Note the difference • Amount of shampoo function: rule that states how the amount of shampoo should vary with hair length • Amount of shampoo value: the actual amount of shampoo needed given a specific instance of the problem, a specific hair length • Here it is the value that is variable, not the function

10. Shampooing Hair • Note: The next two steps will be presented in reverse order, but only for educational purposes.

11. Shampooing Hair • Rinse and repeat, if necessary. • There are actually 2 statements here. • “Repeat” refers to the entire process, and not just to the rinsing. It is important to specify what exactly is repeated. • “If necessary” makes the repetition a conditional iteration • Means the process can be invariably long, but the algorithm that describes it remains short

12. Shampooing Hair • Spread shampoo all over hair until lather forms. • “Spread shampoo all over hair” is a bounded iteration. • Another way to say it: “For every area of scalp, put some shampoo from hand.” • There is a fixed number of areas (simplistically speaking) that the shampoo has to be placed. • “Spread shampoo all over hair” is nested in a conditional iteration “until lather forms.”

13. Shampooing Hair • But the act of spreading shampoo can also be seen as a single unit, a single subroutine, and there is no nesting here. • The how-to knowledge for properly spreading shampoo over your hair can be described elsewhere.

14. What’s the point? • There are many features of our language that we take for granted. • Think explicitly about these features • When we want to convey a difficult idea very clearly • When we want a dumb computer to execute a difficult solution

15. Weekly Schedule • Level of detail is important. • You don’t just say, “Perform Monday activities.” • But you also don’t go into details of “perform bathroom rituals.”

16. Weekly Schedule • The time in which activities happen give a natural direct sequencing to the actions performed.

17. Weekly Schedule • Since MWF classes are the same, and TThclasses are the same, some might write only 2 daily schedules, and say… • If MWF, do this… • Otherwise if TTh, do this… • Two things happened here: • MWF schedule is chunked into one subroutine, TTh schedule is chunked into another. • Conditional branching

18. Here’s A Different Way of Writing The Weekly Schedule • This is my weekly schedule: • For each day in the week • If the day is Monday, Wednesday, or Friday • Do MWF activities • If the day is Tuesday or Thursday • Do TTh activities • If the day is Saturday • Do Saturday activities • If the day is Sunday • Do Sunday activities

19. Here’s A Different Way of Writing The Weekly Schedule • Here is my TTh schedule: • Wake up at 7:00 A.M. • Get ready for school from 7:00-8:00 A.M. • Travel to school from 8:00-8:30 A.M. • CS class at 8:30-10:30 A.M. • etc. • And so on for the other days…

20. Weekly Schedule • Each activity can be described in further detail if there’s a need. • In the same way that a daily schedule needs to be described in further detail • Algorithms can be described in terms of smaller algorithms. • The entire weekly schedule can be integrated into a larger (monthly/yearly/life) schedule. • Algorithms can be part of larger algorithms. • Programs can be part of larger programs.

21. Weekly Schedule • Schedules can be seen as an example of recursive algorithms. • A schedule for a timeframe can be expressed in terms of schedules for smaller timeframes. • The problem of living for a certain amount of time can be broken down into the problem of living for smaller amounts of time. • There will be a schedule (daily) called the base case that is small enough to be described directly, instead of in terms of smaller schedules.

22. Weekly Schedules • Schedules can be seen as an example of recursive algorithms. • But in a true recursion, the way that a larger problem is decomposed into a smaller problem is the same for all sizes.

23. Weekly Schedules • Now that you think of your life as a program, it kind of makes you feel like a robot, doesn’t it?

24. How to Make a Notebook • Get a bunch of plain writing papers. • Get some glue. • Get a cardboard sheet. • Arrange the papers in a neat stack. • Glue the papers together onto the cardboard sheet.

25. How to Make a Notebook • Getting and naming the objects needed (declaring and assigning variables) is part of the procedure. • Paper is an object that we assume exists, but really we know it is composed of more primitive data types. • This is a physical example, so it doesn’t really make sense to talk about data types, but the analogy should be clear. • In computer science, the primitive data types are usually numbers.

26. How to Make a Notebook • By changing the position of a piece of paper (during rearranging) or applying glue to it… • Its stateis changed by invoking a method on it or passing a message to it.

27. How to Make a Notebook • We are getting a bunch of plain writing papers. • Each piece of paper is an instance of the more abstract idea or class of plain writing papers. • By talking about a bunch or array of papers, we don’t care about the individual papers. We want to talk about and manipulate the entire group of papers as a unit. • Contrast this with the single cardboard paper.

28. How to Make a Notebook • You are acting on the entire array as a unit. • No matter how many papers there are, since the same action is done on each paper, a bounded iteration makes it possible to describe an arbitrarily long process on an arbitrarily large volume of objects using a short algorithm. • Question: Why bounded iteration? • Iteration and arrays often go hand-in-hand.

29. How to Make a Notebook • Both “plain writing paper” and “cardboard paper” are special cases of the more abstract “paper.” • “Paper” is an abstract class. • “Plain writing paper” and “cardboard paper” are subclasses of paper, they inherit several features of generic paper, but have special features of their own. • Ultimately, there is a most abstract class that contains all objects, which we’ll call Object.

30. Outline • Motivational Activity • Thinking About Programming • Proper Writing Practice • Abstraction • Practice Problems

32. Input and Output • If programming is about reasoning about an intelligent process, then programs have to interface with the conditions surrounding that process. • Input: the initial condition • Output: the final condition • An algorithm correctly describes a process when it predicts the final condition given any initial condition

33. Input and Output • If programming is all about problem solving, then programs have to interface with the real world. • Input: the current state of the world different from the desired state • Output: the desired state of the world • An algorithm solves a problem when it produces the correct output given any specific input

34. Instances • Each particular selection of inputs constitutes an instance of a problem. • Each particular execution of an algorithm/program is independent of each other.

35. Instances • The blueprint is not the house. • The instructions for building a house is not the same as each act of building a specific house. • Use is not the same as definition.

36. Data Flow • Think of data transforming from input into output in successive stages. • Control structures like branching and iteration control the flow of data

37. Sub-problems • When the problem is too complex, it may be broken down into smaller problems. • A solution can be expressed in terms of smaller solutions. • Relevant data is passed as input into the sub-problem when you call a subroutine. • The output of the subroutine is returned to the original problem for any further transformations.

38. Names and Scope • What the data is named in a sub-problem need not be the same as in the outer problem. • The namespaces of independent algorithms are separate. • The context in which a name refers to something refers to scope. • Once you exit a scope, the name no longer means the same thing.

39. Instance Versus Scope • Names take on different values in different instances, but mean the same thing. • Names mean different things in different scopes.

40. Outline • Motivational Activity • Thinking About Programming • Proper Writing Practice • Abstraction • Practice Problems

41. Proper Writing Practice

42. Write For Humans • Programs must be written for people to read, and only incidentally for machines to execute. • Not just for making computers do things, but for expressing ideas about processes • Abelson and Sussman, preface to the first edition of Structure and Interpretation of Computer Programs

43. How To Write For Humans • Write clearly. • Make the code speak for itself. • Level of detail is important. • Don’t go down to the level of 0’s and 1’s. • Don’t assume all high-level actions can be understood.

44. Too Low-Level • Raise your left leg at a 70-degree angle from the ground. • Let your bottom come into contact with the bike seat, from the left side, using a velocity of 3 inches per second. • Lower your left leg to a 20-degree angle from the ground. • …

45. Too High-Level • Sit on the bike. • Move.

46. Just Right • Carefully situate yourself on the bike seat until you are comfortable. Grasp the handlebars and put your feet on the pedals. • Use your feet to begin pedalling. • Keep pedalling to gain speed. Stop pedalling once you’re at the desired speed. • Start pedalling again if you slow down. You’ll fall if the bike stops moving. • Turn the handlebars to steer. Don’t turn too much to keep your balance. • If you feel like falling to one side, use your foot to kick yourself back to balance.

47. Write For Computers • Of course, algorithms can be applied in all aspects of life. • But many interesting problems require that solutions run on computers to be useful.

48. Computers are Stupid • The order in which instructions are given matter. • Instructions have to be dead-specific. • All high-level instructions must eventually be translated into 0’s and 1’s. • How? • High-level code is translated to low-level code by an interpreter or compiler. • Programs must be written following exact syntax.

49. Another Advantage of Compilation • Allow the same machine to run programs in different languages. • But wait, I thought we had a universal language for computer science? • Universal, in the sense of having the same basic operations at the lowest level • Universal, in the sense that any problem that can be solved in a good language can be solved in another • But ways of combining the lower-level ideas into higher-level ones can differ

50. Why So Many Programming Languages? • Different application areas and problem domains need different high-level constructs. • Some languages make it easier to express certain ideas than others. • BUT THEY’RE ALL EQUIVALENT IN EXPRESSIVE POWER. • It’s always possible to translate from one language to another. And because HTML and CSS are less expressive than the standard programming language, most people do not consider them to be programming languages.