Clarity vs. code reuse/generality
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Fri Jul 3 10:33:12 EDT 2009
On Fri, 03 Jul 2009 14:05:08 +0000, kj wrote:
> ... I find that the processing of
> abstracting out common logic often results in code that is harder to
> read ...
Yes. There is often a conflict between increasing abstraction and ease of
understanding.
[...]
> 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
You're using assert for data sanitation. That is a very bad habit for you
to be teaching novices. Your code will fail to behave as expected
whenever the caller runs Python with the -O switch.
[...]
> My question is: is the business with sense and cmp too "clever"?
For production code? Maybe -- you would need to profile the code, and
compare it to a less general, more simple-minded function, and see which
performs better. If there is an excessive performance penalty, that's a
good sign that perhaps you're being too clever, too general, or too
abstract -- or all three.
Too clever for novices? That depends on how inexperienced they are -- are
they new to Python or new to programming in general? Are they children or
adults? Do they have a PhD degree or are they still at primary school? It
depends on their experience and their intelligence -- dare I say it, some
people will *never* get programming, let alone code-reuse. It also
depends on how you lead up to it -- are you dropping them straight into
the abstract code, or giving them two pieces of nearly the same code and
showing them how to pull out the common functionality?
--
Steven
More information about the Python-list
mailing list