[Tutor] When to use classes

Alan Gauld alan.gauld at yahoo.co.uk
Sat Aug 19 04:07:43 EDT 2017


On 19/08/17 08:52, Alan Gauld via Tutor wrote:

Following up my own post - a sure sign of failure to communicate :-(

> On 19/08/17 05:26, boB Stepp wrote:
> 
>> related methods needs to share the same values and a class would tidy
>> this up nicely without the need for any globals 

> Indeed, but its important to remember that class attributes
> are in effect just global data confined to a smaller context,
> and they share many of the same issues of global data.

> Classes don't remove the problems with globals, they just
> limit the damage.

I should have added that making the globals into instance
variables rather than class attributes improves the
situation still further since it effectively enables
multiple "threads" of execution of your function sequence.

The big issue I was alluding to is the solution whereby a
sequence of functions sharing data is translated into
a Class with class level variables and a bunch of
static/class methods. (This is often seen in bad
Java code). Shared instance data is much less likely
to be changed in bad ways although still a form of global
(within the instance).

But creating classes just to avoid globalizing data
should be a last resort solution. Classes should
serve a conceptual function too in helping to understand
the role of the functions within the overall system.
And that, coincidentally, will usually result in the
functions that share data being grouped in the
same class.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list