[Tutor] creating classes while coding

Alan Gauld alan.gauld at btinternet.com
Mon Feb 21 02:59:47 CET 2011


"Bill Allen" <wallenpb at gmail.com> wrote

> However, I do wonder a bit about the practice I have seen of some
> Python programmers to implement relatively short bits of code, that 
> would be
> quite simple using functions and procedural code, with classes.

OOP is often overkill, but if its the normal way of programming
- and for many recent students its all they get taught - then using
classes is the natural approach. "When all you have is a hammer
everything looks like a nail..." However, there may be good reasons.
Classes make reuse easier, in general, than functions. So if the
task may become a building block for a future project, or even
an extended version of the current one then building a class
makes sense.

> code appears far more complicated than the job at hand really 
> demands.   I
> know there is not always a single right or wrong way of 
> accomplishing
> programming task, but why implement using classes unnecessarily?

Why do anything unnecessarily?
1) You may not know another way.
2) You may have an extended use case in mind that is
    not directly related to the task at hand
3) Somebody said it was "the right way to do it"
4) A learning exercise (do we really need so many text editors?!)
5) Obstinacy - I've started so I'll finish!

and probably more...

> When is it necessary?  When is it best practice?

When reuse is an issue, When multiple instances of the problem
need to be created (think parallel processing), When it has to fit
with a bigger project context (which is using OOP). When objects
naturally fit a complex problem domain - think GUIs.

> I'll freely admit that I do not come from an OOP programming
> background, so designing classes is not my first
> impulse when writing code.  Am I missing something?

Yes, but not as much as you might think!
But when you do start to think OOP before functions you
will probably find it less surprising! :-)

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list