Hi Ben,
Two of the design considerations in OOP are 'who knows what about whom',
and 'who's responsible for what'. The choice between Events and Methods falls
under this.
Let's consider an object which is doing some file processing. It gets
started by another object and wants to report its progress.
One choice is for the object to raise an Event which says "I've done a
unit". This may actually call some other object or not, depending on whether
any objects have 'subscribed' to the event. (Remember there may be more than
one). Whether any other objects have subscribed to this event is up to them.
Although the Event members of the object know about these subscribed
objects, the object itself knows nothing about them. Nor, if fact, does it
care. It raises the event for anyone who <might> be interested. This keeps the
worker object self-contained and uncoupled. The .NET framework takes care of
the linking.
Another choice is for the worker object to call a method of the other
object. In this case, it must be explicitly told which object to call. And it
must know which method to call. This is known as close-coupling.
The worker object must know about the type of the object to which it will
report and be given a reference to an instance so that it can do so. Sometimes
the type will be explicit, often it will an interface, which loosens the
coupling a bit. Whichever way, though, this worker object is not independant,
and the programmer must take care of the linking. [And if there are several
objects to report to, things get more complicated.]
It might sound as if events have all the advantages. Close-coupling is not
a no-no, but it gets in the way of re-use. When you are designing classes
which will be components of a system, and especially when you can't anticipate
all the uses to which your class will be put, events are preferable.
Components designed for re-use which are closely coupled to their users are a
bit contradictory (although close-coupling to co-workers is a different game).
But there are plenty of times when you are using a class which is pretty
much going to be a one-off, or it's fairly trivial and wouldn't take much
effort to revamp. Close coupling is then valid for expediency. Passing an
object in to another so that it can call back on a method is quick and easy.
Defining events, subscribing to them, packaging up event args and raising the
events - this all adds more complexity and effort.
There's always a trade off between doing it the 'right way' and 'getting
the job done'. They are both laudable aims and the boundary is often decided
by personality factors rather than objective criteria.
Just some thoughts.
Regards,
Fergus