Sharing: File Reader Generator with & w/o Policy

Chris Angelico rosuav at gmail.com
Sat Mar 15 23:48:36 EDT 2014


On Sun, Mar 16, 2014 at 2:34 PM, Mark H Harris <harrismh777 at gmail.com> wrote:
> And you are right about another thing,  I just want to use this thing over
> and over.
>
> for line in getnumline(filename):
>     {whatever}
>
>    There does seem to be just one way of doing this (file reads) but there
> are actually many ways of doing this. Is a file object really better than a
> generator, are there good reasons for using the generator, are there
> absolute cases for using a file object?

I recommend you read up on the Rule of Three. Not the comedic
principle - although that's worth knowing about too - but the
refactoring rule. [1]

As a general rule, code should be put into a function when it's been
done three times the same way. It depends a bit on how similar the
versions are, of course; having two places where the exact same thing
is done might well be enough to refactor, and sometimes you need to
see four or five places doing something only broadly similar before
you can figure out what the common part is, but most of the time,
three usages is the point to give it a name.

There's a cost to refactoring. Suddenly there's a new primitive on the
board - a new piece of language. If you can't give it a good name,
that's potentially a high cost. Splitting out all sorts of things into
generators when you could use well-known primitives like enumerate
gets expensive fast - what's the difference between fName and fnName?
I certainly wouldn't be able to call that, without actually looking
them up.

Let your use-cases justify your refactoring.

ChrisA


[1] https://en.wikipedia.org/wiki/Rule_of_three_(computer_programming)



More information about the Python-list mailing list