[Tutor] OO re-factoring (was Pythonese/Efficiency/Generalese critique)

Kent Johnson kent37 at tds.net
Wed Jun 8 12:12:41 CEST 2005

Lee Cullens wrote:
> I was thinking of extending the learning exercise by re-factoring it  
> as an OO approach, since it would contain a minimum altered method.   
> Being new to OOP also though, I'm confusing myself with how that  
> would be best accomplished.  My thinking is that class/subclass  
> method instances would replace the recursive functions approach, but  
> have as yet not formed the coding in my mind.

Using an OOP approach won't change the algorithm from recursive to non-recursive.

To me, OOP is about code organization and abstraction. It is a way to collect code and data into chunks that can be used at a higher level of abstraction than just the raw data. OOP is not necessary for reuse - functional modules can be very useful and reusable.

There is a spectrum of re-use. Many of my programs have classes that are only instantiated once. They are not reused but they provide a useful way to organize the code and provide a useful building block for the rest of the program. I also have many classes that are reused within the program containing them, this is an important kind of reuse. And some classes I write are more broadly useful and are re-used in more than one program.

I have written an essay about when to use classes that approaches the question from a very simple, practical point of view.

Javier's File and Dir classes are strongly reminiscent of the path class in J Orendorff's path module; you might want to take a look at it. Highly recommended for file and directory manipulations.

Alan G wrote:
> 4) build one class, the lowest level one, with no dependencies on the
> others

Yes!! Try to think of your classes as reusable modules even if you don't anticipate reusing them! Don't allow dependency cycles.

> 5) test it (at the >>> prompt?)

Testing is good. Do yourself a favor and learn how to use unittest (or doctest or py.test). If you write your tests as unit tests instead of doing them by hand in the interpreter, you can re-run the tests as needed. This is invaluable when you make a change to your code and want to know if you have broken anything - you don't have to test manually, you just run the unit test.


More information about the Tutor mailing list