90 likes | 166 Views
Student Q and As from 4.4 – 4.9. Students of CS104, Fall 2013 (and me). Encapsulation. Q: What does it do and what is it supposed to accomplish?
E N D
Student Q and As from 4.4 – 4.9 Students of CS104, Fall 2013 (and me)
Encapsulation Q: What does it do and what is it supposed to accomplish? A: Encapsulation means wrapping up code into a function, which you give a nice descriptive name. Like, putting 8 commands that draw a square into a function called drawSquare().
Example What does this do?: # given two integers, u and v while v: u, v = v, u%v res = abs(u) Perhaps this is better?: res = greatest_common_divisor(u, v)
Generalization Q: Can you explain why generalization is useful? A: The idea of generalization is to take code and make it more useful by parameterizing the code. E.g., take drawSquare() and make it drawPolygon(). (You could still have drawSquare() and have it just call drawPolygon(4).)
Interface vs. implementation • Interface: a functions name and what it does for you. • Implementation: how the function works, on the inside. • E.g., for our Scribbler robots, we can call forward(1, 1) # full speed ahead for 1 sec • That’s the interface for the forward() function. • 2 parameters: first is speed, second is duration. • How this function makes the robot go forward at full speed for 1 second is the implementation. We don’t know, and we don’t care about that… The implementation is encapsulated in the function.
An interface “as clean as possible” Q: How do you know if your interface is “as clean as possible”? A: You don’t. Computer programming is an art, and sometimes you have to make judgment calls. Also, sometimes you just don’t want to mess with stuff that is working…
Refactoring • This is the process of looking back over the code, and rewriting parts to eliminate duplicate code, clean up stuff, etc. • This is part of the art of computer programming. Seeing patterns that you can take advantage of.
Comments vs. docstrings Q: What is the difference between putting a comment in a # vs. making a docstring with “””? A: If you give a function a docstring, then the help() command prints it for you. Also, pydoc tool will generate a nice html file with your docstring in it to describe what the function does. Also, it is a python convention. Get over it.
More on docstrings Q: Are docstrings ignored by the interpreter, similar to comments? A: The contents of the docstring are ignored by the interpreter. The docstring is stored so help() can display it. Q: Does a docstring have to be the first thing in a function definition? A: Yes. Otherwise, the string is just ignored by the interpreter.