Clarity vs. code reuse/generality

David Niergarth jdnier at gmail.com
Mon Jul 6 14:52:26 EDT 2009


I remember in college taking an intro programming class (C++) where
the professor started us off writing a program to factor polynomials;
he probably also incorporated binary search into an assignment. But
people don't generally use Python to implement binary search or factor
polynomials so maybe you should start with a problem more germane to
typical novice users (and less algorithm-y). Wouldn't starting them
off with string processing or simple calculations be a practical way
to get comfortable with the language?

--David

On Jul 3, 9:05 am, kj <no.em... at please.post> wrote:
> I'm will be teaching a programming class to novices, and I've run
> into a clear conflict between two of the principles I'd like to
> teach: code clarity vs. code reuse.  I'd love your opinion about
> it.
>
> The context is the concept of a binary search.  In one of their
> homeworks, my students will have two occasions to use a binary
> search.  This seemed like a perfect opportunity to illustrate the
> idea of abstracting commonalities of code into a re-usable function.
> So I thought that I'd code a helper function, called _binary_search,
> that took five parameters: a lower limit, an upper limit, a
> one-parameter function, a target value, and a tolerance (epsilon).
> It returns the value of the parameter for which the value of the
> passed function is within the tolerance of the target value.
>
> This seemed straightforward enough, until I realized that, to be
> useful to my students in their homework, this _binary_search function
> had to handle the case in which the passed function was monotonically
> decreasing in the specified interval...
>
> The implementation is still very simple, but maybe not very clear,
> particularly to programming novices (docstring omitted):
>
> def _binary_search(lo, hi, func, target, epsilon):
>     assert lo < hi
>     assert epsilon > 0
>     sense = cmp(func(hi), func(lo))
>     if sense == 0:
>         return None
>     target_plus = sense * target + epsilon
>     target_minus = sense * target - epsilon
>     while True:
>         param = (lo + hi) * 0.5
>         value = sense * func(param)
>         if value > target_plus:
>             hi = param
>         elif value < target_minus:
>             lo = param
>         else:
>             return param
>
>         if lo == hi:
>             return None
>
> My question is: is the business with sense and cmp too "clever"?
>
> Here's the rub: the code above is more general (hence more reusable)
> by virtue of this trick with the sense parameter, but it is also
> a bit harder to understand.
>
> This not an unusual situation.  I find that the processing of
> abstracting out common logic often results in code that is harder
> to read, at least for the uninitiated...
>
> I'd love to know your opinions on this.
>
> TIA!
>
> kj




More information about the Python-list mailing list