[Tutor] When to use classes
alan.gauld at btinternet.com
Wed Apr 9 12:22:05 CEST 2014
On 09/04/14 06:58, Ni hung wrote:
> functions and no classes. I have some understanding of classes/Object
> Oriented Programming. I can write simple classes but I do not understand
> when to use classes.
If you are just learning it may be that the programs you have written
are too small to make classes useful. Classes tend to come into their
own on larger programs.
As to when to use them: if you see a lot of functions all taking the
same set of data inputs then there's a good chance you should turn that
into a class that holds the data and has the functions as methods.
Alternatively if you need to manipulate several copies of a thing then
defining thing as a class and creating multiple instances makes sense
(Think of strings in Python - how much harder it would be to work with
strings if they weren't classes. Up until Python v2 that's exactly what
we had to do.)
As projects get bigger still, it starts to become more natural to
think of the program in terms of classes because they become more
of an expression of your real-world problem domain than an expression of
programming data sets. Think about classes like employee, order,
bankaccount, building, etc (Although those with a formal math background
often find this hardest to do since they have had it
beaten into their skulls that things consist of functions and data!)
But don't sweat about it, you can go a long way without classes. And
when they are needed it usually becomes clear based on what I said in
paragraph 2 above.
Author of the Learn to Program web site
More information about the Tutor