[Tutor] Follow up to 'class data'
Tue, 4 Dec 2001 17:33:28 -0000
> 1. Encapsulation - makes it easier to make a mental picture of your
> program, you can create objects and associate both actions
> and data
Absolutely correct, the foundation of OOP.
> 2. Polymorphism - I totally have no idea what does it mean in
You probably use it without realising.
Its where a group of different classes have the same
interface - ie set of methods - but implement them differently.
The HTML/XML/SGML parsers in te standard library are good
examples. You create a parser and use it. Which parser depends
on the file type. The parsers are polymorphic instances of
the general parser interface.
Another example is the AddressBook example earlier today.
AddressBook can contain entries. The Entries can either
be buildings or people but provide they have the same set
of methods the AddressBook doesn't know or care, it just
uses the basic interface. In fact we could go on to define
a Network entry too and the AddressBook need be none the wiser
it just calls the same set of methods.
See my OOP topic on my web tutor for much more with examples:
> 3. Data hiding - I guess it's useful in very large projects where many
> people are working on the code and you want to protect your data from
> the silly intern in the next cubicle?
Sort of, its also useful when you are prototyping and the
internal data starts off as a hard coded list, then gets
moved to a flat file and finally to an RDBMS. The method
calls don't change but the internals of how they work change
drastically. The other area that it helps in is where
there are data rules such as valid ranges or that you
an only set one value if you also delete another etc.
By forcing access via a method you can enforce those
rules(inside the method) and thus avoid bugs.
> 4. Inheritance - I used it a little bit but I could do without it just
> as well. It pretty much saves typing and maintainance time, right?
This is usually the means of providing polymorphism(see above)
but as I show on my web tutor the two are not necessarily linked
(except in strictly typed languages). Inheritance does provide some
code saving convenience features in its own right and in
particular allows programming by specialisation - where you
add new methods and attributes to existing ones or override
existing methods to do new things (this is subtly different
to pure polymorphism which requires identical interfaces!
Something called the Liskov(sp?) Substitution Principle)
Interestingly there are some objective data to suggest that
inheritance can actually be detrimental to maintenance since
it is much harder to ensure that a code fix in one place won't
cause damage some place else that inherits the changed code.
Also the lack of local visibility of the functions can make
code comprehension more difficult. This is one area where
python and its explicit use of self and the imported module
names actually helps a lot.