
|
This is a post[^] I made to the Lounge. I wanted to give a basic overview of the concept of messaging in object oriented programming. Specifically, I wanted to show how anonymous methods help facilitate passing one message from one object to another in a decoupled way. This is similar to my "Anonymous Methods as Glue"[^] entry.
The post got a little long; I really enjoy talking about these concepts. So I thought I would repost it here:
From a theoretical point of view, invoking a method on an object can be considered sending it a message:
SomeObject obj = new SomeObject();
obj.DoSomething();
The challenge becomes implementing this in such a way as to make it extensible and flexible to change. Polymorphism helps by lowering the coupling between objects:
public interface ISomeInterface
{
void DoSomething();
}
ISomeInterface obj = new SomeObject();
obj.DoSomething();
Now we can substitute types that implement ISomeInterface and it won't break the rest of our code. Just basic polymorphism.
It would be nice to have objects communicate peer-to-peer through a more explicit messaging system:
public interface ISink
{
void Send(Message msg);
}
Then we can set up relationships between objects when they are created and allow them to send messages directly to each other via the ISink interface:
ISink obj1 = new SomeObject();
AnotherObject obj2 = new AnotherObject(obj1);
obj2.Go();
obj2 can send messages directly to obj1 and does so through the ISink interface.
The problem with this approach is that we have to straightjacket objects into the ISink interface in order to allow our messaging system to work. We can use .NET events to decouple objects even further and use anonymous methods as a means of facilitating communication. Take your typical .NET class that raises an event:
public class ClassWithEvents
{
public event EventHandler SomethingHappened;
}
Take a class with a method that returns void and takes no parameters:
public class SomeObject
{
public void DoSomething()
{
}
}
Anonymous methods glue the objects together allowing them to communicate:
ClassWithEvents obj1 = new ClassWithEvents();
SomeObject obj2 = new SomeObject();
ob1.SomethingHappened += delegate(object sender, EventArgs e)
{
ob2.DoSomething();
};
The objects are completely decoupled. The anonymous method provides a way for events raised by one object to be delegated to another object. Things can get fancier if our anonymous method adapts the event raised by one object by transforming the message into something the receiving object can understand.
From my point of view, since taking up C#, messaging has become a ubiquitous to my programming. And I think it's improved as a result.
|
|
|
|