Monday, June 06, 2005

C# Idiom: NullObject Interface

I'm going to start to publish/collect some ideas in C# programming.
Some or them might be patterns, or more granular, like idioms.

let' say we have a class Client which uses a class Server.
The interface which is used by Client, will be IServer

class Client
{
private IServer server;
}

class Server : IServer
{
...
}

in Order to have a function Client, we need a initialization with a valid IServer.
Let's make a minimalistic, null object, implementation of this interface:
sealed class NullServer: IServer
{
... //default, empty implementation of IServer
private NullServer()
{ }

public static readonly NullServer Instance = new NullServer()
}

class Client
{
private IServer server = NullServer.Instance;
}

- Now we can use the client, without the need to create a whole instance of the Server class.
- Using the IServer interface, the Client can be better tested, using a MockObject.

- The Client can be injected with a server interface in the constructor (PicoContainer-style),
or with a Setter (Spring-style).

0 Comments:

Post a Comment

<< Home