Partial function application (in C#)

I often use delegates (e.g. Func<> or Action<>) to make code testable that would otherwise be using static methods. In this case, Trace.WriteLine:

public class TraceLogger : ILogger
{
	private readonly TraceSwitch _traceSwitch;
	private readonly string _category;
	private readonly Action<string, string> _write;

	public TraceLogger(TraceSwitch traceSwitch, string category, Action<string, string> write)
	{
		_traceSwitch = traceSwitch;
		_category = category;
		_write = write;
	}

	public void Debug(string message)
	{
		if (_traceSwitch.TraceVerbose)
			_write(message, _category);
	}

	public void Info(string message)
	{
		if (_traceSwitch.TraceInfo)
			_write(message, _category);
	}
	
	etc...
}

Every time the write action is called, the second argument is the same. So we can save ourselves some duplication by using partial function application (not currying, apparently!):

public class TraceLogger : ILogger
{
	private readonly TraceSwitch _traceSwitch;
	private readonly Action<string> _write;

	public TraceLogger(TraceSwitch traceSwitch, string category, Action<string, string> write)
	{
		_traceSwitch = traceSwitch;
		_write = m => write(m, category);
	}

	public void Debug(string message)
	{
		if (_traceSwitch.TraceVerbose)
			_write(message);
	}

	public void Info(string message)
	{
		if (_traceSwitch.TraceInfo)
			_write(message);
	}
	
	etc...
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s