Methods: more than DRY
Using Method Names As Documentation
Beginner programmers often think, and are often told, that the only use for a method definition is to eliminate repetition in a program’s implementation. Keeping your code DRY is important, and defining methods is a great way to do that, but that is not the only use for declaring new methods.
Another use for method declarations is documentation and readability. A good rule of thumb for declaring a method for these purposes is when you are tempted to add a comment to a chunk of code to explain what it is doing. Instead of writing a comment, you could declare a new method with a descriptive name and call it in that spot. You should do this even if you only plan on using this method once in your whole implementation. It makes your code more readable, short, declarative, and testable.
Get Charles Hughes’s stories in your inbox
Join Medium for free to get updates from this writer.
Here’s an example of two different implementations of Newton’s method for approximating the square root of a given number in JavaScript:
function sqrt_iter(guess,x) {
if (abs(square(guess) — x) < 0.001)
return guess;
else
return sqrt_iter(guess + x/guess) / 2);
}
function sqrt(x) {
return sqrt_iter(1.0,x);
}This first implementation is very terse and somewhat difficult to read. If we were to take this code and perform the technique I had suggested above, this code might look something like this:
function sqrt_iter(guess,x) {
if (good_enough(guess,x))
return guess;
else
return sqrt_iter(improve(guess,x), x);
}
function improve(guess,x) {
return average(guess,x / guess);
}
function average(x,y) {
return (x + y) / 2;
}
function good_enough(guess,x) {
return abs(square(guess) — x) < 0.001;
}
function sqrt(x) {
return sqrt_iter(1.0,x);
}This implementation is noticably longer. That aside, I think that it could be argued that this implementation is much more nicely separated out into the different concepts it uses. The sqrt_iter function, in particular, is much more readable in this implementation than the previous. I don’t have to do much thinking to look at that function definition and understand what it is doing.
The “better” implementation of sqrt above was adapted from the first chapter of SICP.






