The Custom Configuration Section Code Smell

I was recently involved in a project that involved some design-time configuration.  That design-time configuration was based on custom config sections.

I didn’t really pay too much attention to it at the time because I don’t write my own custom config sections.  As I worked on the project and do what I usually do by refactoring and evolving the system to use various patterns and principles, I came to realize why I don’t use my own custom config sections.

That realization came as I began refactoring code for dependency inversion.  As I progressed getting the majority object creation code to get performed and managed by the container, I slowly started deleting the code that used these custom config sections.  I also started deleting the configuration sections from the app.config files.  It’s then I realized why I don’t use custom configuration section: I simply can’t use them them.

Custom config sections can be used for anything you need them for.  For the most part, they’re about configuration settings for infrastructure-like objects.  Effectively the constructor arguments for a particular class or a façade for a group of related classes.  They’re a way abstracting away the constructor parameters away from your code so that you don’t need to recompile simply to change configuration-like information.  In an of itself, that’s a good thing.  And, if, for whatever misguided reason you can’t use an IoC container, custom configuration sections are a good thing.

Let’s look and an example of a custom config section.  Let’s say that have a class that I use to connect to an external device via TCP.  To connect to that device I need an host name (or IP address) and a port number.  To communicate with the device (beyond "hello") I need a user name and password.  I also need some various other things like timeout values, retry values, etc.  For example:

public class Device : IDevice {
public string HostName { get; private set; }
public uint Port { get; private set; }
public string UserName { get; private set; }
public string Password { get; private set; }
public uint SocketTimeout { get; private set; }
public uint RetryCount { get; private set; }

public Device(string hostName, uint port, string userName, string password, uint socketTimeout, uint retryCount) {
HostName = hostName;
Port = port;
UserName = userName;
Password = password;
SocketTimeout = socketTimeout;
RetryCount = retryCount;
}
//...
}


I may want a app.config like this:



<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="device" type="DeviceConfigSection, Application"/>
</configSections>
<device hostName="192.168.0.111" port="8080" username="admin" password="p@55w0rd"/>
</configuration>


In order to do that I need a config section class like this:



public class DeviceConfigSection : ConfigurationSection {
[ConfigurationProperty("hostName", IsRequired=true)]
public string HostName { getset; }
[ConfigurationProperty("port", IsRequired=true)]
public uint Port { getset; }
[ConfigurationProperty("username", DefaultValue="guest", IsRequired = false)]
public string UserName { getset; }
[ConfigurationProperty("password", IsRequired=false)]
public string Password { getset; }
[ConfigurationProperty("socketTimeout", DefaultValue = 1000u, IsRequired = false)]
public uint SocketTimeout { getset; }
[ConfigurationProperty("retryCount", DefaultValue = 3u, IsRequired = false)]
public uint RetryCount { getset; }
}


I’d then use it like this:



	class Program {
static void Main() {
var config = System.Configuration.ConfigurationManager.GetSection("device") as DeviceConfigSection;
IDevice device = new Device(config.HostName, config.Port, config.UserName,
                         config.Password, config.SocketTimeout, config.RetryCount);


			var x = new DeviceConsumer(device);


			//...
}
}


Fairly straightforward; but quite a bit of code to separate construction parameters to design-time values.  Plus, my code is still tightly coupled to how a Device object is created and tightly coupled to that device being the Device implementation.  Let’s look at how I might do the same thing in an IoC container like Unity 2.0.



I’d start with a configuration file like this:



<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<unity>
<assembly name="Producer"/>
<container>
<register type="IDevice" mapTo="Device">
<constructor>
<param name="hostName" value="192.168.0.111"/>
<param name="port" value="8080"/>
<param name="userName" value="admin"/>
<param name="password" value="p@55w0rd"/>
<param name="socketTimeout" value="1000"/>
<param name="retryCount" value="3"/>
</constructor>
</register>
</container>
</unity>
</configuration>


And to load that configuration I’d have code like this:



	class Program {
static void Main() {
var unityContainer = new UnityContainer().LoadConfiguration();
var x = unityContainer.Resolve<DeviceConsumer>();
//...
}
}


Et viola, a much simpler way of putting my parameters into the configuration file and making them a design-time concern.  Much less code.  If I want to do the same thing with another class, I just add more elements to the “unity” section, I don’t need to add more configSection elements and I don’t have to write a custom config section.  If you were paying close attention, you’ll also notice that I didn’t actually write code to create a Device object!  I simply tell Unity that I need a DeviceConsumer (which is a concrete class so I don’t necessarily need to tell it how to create it) and the container figures out the dependency and if it knows about it (which it does, because I told it Device is a type of IDevice and what parameters to use when creating one) and instantiates it automatically.  My code is now completely decoupled from how a Device object is created and completely compile-time decoupled from the Device class!



Does that mean configuration section handlers are completely useless?  Of course not; but, as you embrace getting your dependencies in the right direction, decoupling your code from the responsibility of creating these dependencies the more and more you realize that configuration section handlers aren’t the solution you need or even a solution you can use.  Of course, if you’re an IoC container; that’s a completely different story :)



I have come to decide that using a custom configuration section is a code smell.  The impetus to using them is basically decoupling creation from use; but it only does it half-way by moving just the parameters into app.config.

Unbind a Visual Studio 2010 Solution from Source Code Control

I was working with a solution that I got from someone else the other day.  When I loaded it up, Visual Studio 2010 informed me that it could not connect to a TFS server at some URL and will open the solution in offline mode (or something to that effect).  Of course, I have no access to this TFS server, so, I’m going to get this message every time I open this solution.  That’s going to get annoying pretty fast.

So, I had a quick search on the Internet about removing source code control from a Visual Studio 2010.  I found all sorts of information about editing the sln file, removing various sections of an sln file and what-not.  None of this information can from Microsoft.  While in theory doing this would likely do what I wanted, manually editing sln or project files never seems like a good idea.  I don’t know if there are side-effects from this that Visual Studio will telescope into some future version of the sln file and end up causing me problems.  e.g. Visual Studio 201x is released and I try to upgrade this sln file—what if this future version of VS fails or even worse, corrupts my file.

No, I didn’t want to get chicken blood on my keyboard.

I was somewhat surprised that my search didn’t immediately show something that wasn’t obvious ritualistic magic; so, I went looking in the File menu at the Source Control entry.

In there, when my solution was loaded, I simply selected Change Source Control.  As soon as I try to open that dialog VS told me again that it was working offline and wanted to know if I wanted to completely remove the Source Control bindings from my solution.  I simply chose yes and all the SCC bindings were removed from my solution.

Saving and reloading the SLN file had no source control offline message, and my keyboard is no dirtier than when I started.

The fact that I couldn’t readily find this with a web search made me think this information would be useful for someone else; so, I’m posting it here in the hopes it helps someone else.

Fluent Builders Part 2

In this part I’m going to go into the principles behind a fluent builder.

Fluent builders don’t simply provide a method for each argument a constructor (or other method) may take, they provide consistency when providing related arguments.

In my fluent builder example I had a WithCredentials method on the builder that take two related arguments: a username and a password.  I could have just as easily have a WithPassword and WithUserName method and used it like this:

Subscription subscription = new RabbitMQSubscriptionBuilder()
.WithUserName("pQowiht12glsh%d")
.ToHost("localhost", 8181)
.WithPassword("i21uWghe&gjs")
.SubscribeToQueue("messages");


 



We achieve the same result; but now we can have username and password disconnected with this new interface.  It’s not clear that username and password go hand-in-hand.



A fluent builder is all about readability and expressiveness.  It’s about using basic compiler tricks to maintain consistency while providing an expressive and readable interface.  The very nature of chained method calls is basically a violation of the Law of Demeter, for example—depending on your interpretation.  Builders are transient containers of data that transform data into the creation of an object.  They’re not modeling domain behaviour; they’re strictly utility.  So they don’t have to completely abide by object-oriented design principles.



There’s been a couple of comments about the property with only a getter that has side-effects.  For classes that model domain behaviour, I completely agree that getters with side-effects are an abomination.  But, we’re not modeling domain behaviour with builders; we’re simply attempting to provide the most expressive interface to build object so that it’s readable by just about anyone reading the code.  The fact that WithAcknowledgements is a property with only getter that has side-effects is moot.  It could have been implemented with a method with no parameters; but that doesn’t add any expressiveness nor add to readability at all—it just adds more typing.



We’re trying to define an interface that allows the programmer to convey intent.  WithAcknowledgements as a property or a method that takes no arguments shows much more intent than WithAcknowledgementsEnabled(bool).



In my original example, I should have also included WithoutAcknowledgements in order for the programmer to accurately convey that they understand the default values.  We’d end up being able to convey that intent nicely with code like this:



Subscription subscription = new RabbitMQSubscriptionBuilder()
.WithCredentials("pQowiht12glsh%d", "i21uWghe&gjs")
.ToHost("localhost", 8181)
.WithoutAcknowledgements
.SubscribeToQueue("messages");


I’ve also chosen to use an implicit cast operator to convert the builder to the object it builds and chosen in my example to not use an implicitly typed variable as the for the object created by the builder.  My views on implicitly typed variables are pretty well known.  Should a programmer using this interface accidentally used an implicitly typed variable; they’d quickly have a compile error; so, I don’t feel there’s much issue with this technique.  If implicitly typed variables are a preference, the programmer could write code like this:



var subscription = (Subscription)new RabbitMQSubscriptionBuilder()
.WithCredentials("pQowiht12glsh%d", "i21uWghe&gjs")
.ToHost("localhost", 8181)
.WithoutAcknowledgements
.SubscribeToQueue("messages");


Not much more ore less expressive than the original; but a little bit more typing.  Sure, there could be a method that terminates the method chain like “Build” and we could do this:



var subscription = new RabbitMQSubscriptionBuilder()
.WithCredentials("pQowiht12glsh%d", "i21uWghe&gjs")
.ToHost("localhost", 8181)
.WithoutAcknowledgements
.SubscribeToQueue("messages")
.Build();


But, it’s no more expressive that our previous version.  Plus, there’s an implied order to the call to Build: it always has to be at the end.  This seems like unnecessary ceremony.



Other Practices



Generally methods are prefixed with “With” to convey that builder is building up an object through a series of additions.  But, when another prefix would add more expressiveness or clarity, that prefix should be preferred over “With”.  The “ToHost” is a good example.  The builder is creating an object that connects to a remote host; “With” could be ambiguous.  “ToHost” conveys better that the resulting object connects to a host of given name and port.



I hope this short excursion into fluent builders and fluent interfaces has given you the motivation to add expressiveness to your code where you find long strings of meaningless parameters.  By all means you should implement your builders that are most expressive to you; but don’t let strict adherence to object-oriented principles make these utilitarian classes more complex than they need to and end up hindering your expressiveness.

Fluent Builders, Part 1

I’ve seen some conversations about fluent builders as of late, and I’d thought I’d post some information about fluent builders, the principles behind them, the problems they address, and how to implement them.

Fluent Builder is a combination of the builder pattern and a fluent API.

The builder pattern is similar to the factory pattern in that it’s intended to abstract the creation of other objects.  This is often meant to abstract the fact that many objects need to be created (ala the composite pattern).  It’s often intended to hide the fact that the creation of one object is dependant on the creation of one or more other objects.

A Fluent API or a Fluent Interface is a pattern-like design technique introduced by Eric Evans and Martin Fowler and is an interface that makes use of method chaining to promote readability of code.

The combination of a Fluent API and a the Builder pattern give us fluent builders—the ability to fluently build complex objects.  The principle of doing this is not only to gain the readability of a Fluent API but to also gain the expressiveness that we can get from the use of named methods and properties.

Let’s look at a simple example that I encountered recently in the creation of a RabbitMQ Subscription object:

var connectionFactory = new ConnectionFactory
{
HostName = "localhost",
UserName = "pQowiht12glsh%d",
Password = "i21uWghe&gjs",
Port = 8181
};
var connection = connectionFactory.CreateConnection();
var model = connection.CreateModel();
var subscription = new Subscription(model, "messages", false);
var currentMessage = subscription.Next();
// ...


A Subscription object is dependant on an IModel object, and the creation of an IModel object is dependant on the creation of a IConnection object, and the IConnection object is dependant on the creation of a ConnectionFactory.  The IConnection requires a host name, a user name, a password and a port number.  A subscription requires an IModel object, a queue name, and whether messages retrieved from the queue require an acknowledgment or not.



The creation of a connection factory is fairly easy to understand because it uses properties to configure the object and we’ve chosen to use the object initializer syntax to initialize said object type.  When we get to the creation of the Subscription object, it gets a little sketchy.  What does “messages” mean and what does “false” mean?  It’s not clear from the call to the Subscription constructor what those two parameters mean.  Someone reading this code needs to understand what arguments this particular Subscription constructor accepts to really understand this code.



Now, let’s look an example using a Fluent Builder:



Subscription subscription = new RabbitMQSubscriptionBuilder()
.WithCredentials("pQowiht12glsh%d", "i21uWghe&gjs")
.ToHost("localhost", 8181)
.SubscribeToQueue("messages");
var currentMessage = subscription.Next();


 



With this code, it’s extremely obvious what "pQowiht12glsh%d", "i21uWghe&gjs" are and that they are related to one-another.  It’s also obvious that “localhost” and 8181 are related to one-another.  It’s now clear what “messages” meant and model and false are completely abstracted away.  We’ve also got a few less lines of code.



If we look at the actual builder that is used with this example:



public class RabbitMQSubscriptionBuilder {
public string UserName { get; set; }
public string Password { get; set; }
public string HostName { get; set; }
public ushort PortNumber { get; set; }
public string ExchangeName { get; set; }
public string QueueName { get; set; }
public bool AckRequired { get; set; }

public RabbitMQSubscriptionBuilder() {
HostName = "localhost";
PortNumber = 5672;
UserName = "guest";
AckRequired = false;
}

public RabbitMQSubscriptionBuilder WithAcknowledgements {
get {
AckRequired = true;
return this;
}
}

public RabbitMQSubscriptionBuilder WithCredentials(string userName, string password) {
UserName = userName;
Password = password;

return this;
}

public RabbitMQSubscriptionBuilder ToHost(string hostName, ushort portNumber) {
HostName = hostName;
PortNumber = portNumber;

return this;
}

public RabbitMQSubscriptionBuilder PublishToExchange(string exchangeName) {
ExchangeName = exchangeName;

return this;
}

public RabbitMQSubscriptionBuilder SubscribeToQueue(string queueName) {
QueueName = queueName;

return this;
}

public static implicit operator Subscription(RabbitMQSubscriptionBuilder builder) {
var connectionFactory = new ConnectionFactory
{
HostName = builder.HostName,
UserName = builder.UserName,
Password = builder.Password,
Port = builder.PortNumber
};
var connection = connectionFactory.CreateConnection();
var model = connection.CreateModel();
return new Subscription(model, builder.QueueName, builder.AckRequired);
}
}


…and look at where we create our Subscription object, it’s now more clear what the arguments are being sent to the constructor.



If we wanted to now create a Subscription object that required acknowledgements, we’d write code like this:



Subscription subscription = new RabbitMQSubscriptionBuilder()
.WithCredentials("pQowiht12glsh%d", "i21uWghe&gjs")
.ToHost("localhost", 8181)
.WithAcknowledgements
.SubscribeToQueue("messages");


…instead of changing false to true.  Much more clear.



I, personally, think the expressiveness of the fluent builder is second to none.  But, let’s look at a couple of alternatives.



The builder pattern is very similar to the Introduce Parameter Object refactoring where you’d create another class that groups the parameters together into a single class.  The issue here is that we’re dealing with the creation of multiple objects in order to get the final Subscription object. We could create a parameter class for Subscription to give us a bit in the way of readability and come up with something like this:



var connectionFactory = new ConnectionFactory
{
HostName = "localhost",
UserName = "pQowiht12glsh%d",
Password = "i21uWghe&gjs",
Port = 8181
};
var connection = connectionFactory.CreateConnection();
var model = connection.CreateModel();
var parameters = new SubscriptionParameters
         {
             Model = model,
             QueueName = "messages",
             RequiresAcks = false
         };
var subscription = CreateSubscription(parameters);
var currentMessage = subscription.Next();


We get some expressiveness with the names of properties in SubscriptionParameters; but we’ve now added several lines of code to support SubscriptionParameters because it only introduces an abstraction for the parameters of a single method.  Not without benefit; but kind of an expensive benefit.



There’s a few readers who are probably thinking of what C# 4 an offer.  And yes, that’s where I’m going next: named parameters.  Given our original example, C# offers the following possibility:



var subscription = new Subscription(model: model, queueName: "messages", noAck: false);


This offers the same readability and expressiveness of the Introduce Parameter Object refactoring; but with much less of the overhead.  We don’t need a new class with three parameters and we don’t need a new method to accept the new parameter object.  But, it still only really addresses a single method.



If we look back at what we get from the fluent builder, it abstracts building a single scenario; a scenario that includes several objects.  This scenario better encapsulates a particular usage pattern, not a particular class.  It better encapsulates our intention to create and use the concept of a Rabbit MQ “subscription”; the fact that a connection and a model are needed truly become implementation details that they are, abstracted within the builder.