Sunday, May 8, 2011

Avoiding Nulls with "Tell, Don't Ask" Style

A very interesting thought about another wonderful side effect of "Tell, Don't Ask" principle (Nat Price wrote in his blog):

"On the other hand, if the object tells a collaborator to do something with the value, it can choose, when the value does not exist, to just not tell it's collaborator anything or to tell the collaborator to do something different. There's often no need to represent the "does not exist" case as a data structure because it never gets passed around."

Sunday, May 1, 2011

Why .NET Events Suck

The .NET events are so common that almost nobody even thinks to consider practical alternatives to them. And that's a mistake. I'm going to show how much interfaces are better in OO sense.

Consider two simple implementations of a very common Listener scenario where one class is "listening" another for some useful events.

First, .NET event-based version:


And interface-based version:


The pros of the interface-based version are:

  • An instance of Worker always references to a not-null WorkListener, which is great point since the Listener is its Dependency.
  • ...and Worker claims about that as clear as possible - via its constructor. It's not possible to create a Worker without a valid instance of a class implementing WorkListener.
  • It's absolutely clear at a glance that AnotherClass plays WorkListener role. In the even-based version all we have is just a public method with a rather weird (in context of the rest class's public interface) name and semantic (Work's Done? What work? Who is call it? When?).
  • AnotherClass.WorkDone() is private which is a good thing - AnotherClass's public interface is not polluted with a method that's not a class's responsibility.
The only con I can see:
  • It's not multicasting. However, it's rarely the case when multicasting is really needed.