[Tutor] Communication between classes
Alan Gauld
alan.gauld at btinternet.com
Mon Apr 2 02:13:37 CEST 2007
"Greg Perry" <gregp at liveammo.com> wrote
> I am still in the process of learning OOP concepts and
> reasons why classes should be used instead of
> functions etc.
That's OK, many folks find the transition hard at first.
It is a new way of looking at problems.
> One thing that is not apparent to me is the best way
> for classes to communicate with each other.
Classes don't.
Its *object* oriented programming and its objects
which communicate. Objects pass messages
between each other and the parameters are other
objects. Classes are just the mechanisms for defining
and creating objects. And thats a very important distinction.
> For example, I have created an Args class that sets
> a variety of internal variables (__filename, __outputdir etc)
> by parsing the argv array from th command line.
OK, What is the responsibility of an Args object?
What kind of things would you do with/to an Args
instance? You might want to get the vatrious values
from it - treating it somewhat like a dictionary maybe?
You might want to store it so the same set of args
can be used over and over. What else do you want
the args to do? Focus on the responsibility of the object
as a whole.
> What would be the preferred mechanism for returning
> or passing along those variables to another class?
You pass an instance of the args class as an object to
another object via a message.
> Maybe by a function method that returns all of those variables?
You might have a method of the Args class that can get
the values for a given instance but you wouldn't want to
extract the values from the object and manage them elsewhere.
That would be to defeat the point of the object, which is to
encapsulate both the data and the operations on the data
in one entity, the object, which can be passed around in
its entirety.
For example when you drive your car(an object) you don't
dismantle it and then reassemble just the bits you need.
Let's see its only me so only one seat and its a warm day
so I don't need the heater... You just jump into the complete
car and drive it. Same with your args class(*). You create
an instance and use it whichever way you need. If somebody
else needs your args to do something you give them the args
(just like if somebody borrows your car you don't give them
bits of it you lend them the whole car)
(*)And same with the car, you don't lend someone the factory
blueprint (the class) and tell them to build their own car, you
lend them your specific instance of the car.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list