Skip to main content

Micro Fluency

I’ve been having a lot of conversations at work lately about how comments are a code smell, and if you’re not writing self-documenting code, ur doin it rong.
Then I found myself in a position I’ve been in quite a few times… The general description is this: I have a method that takes two parameters. The action the method performs is best written in English in the form “{SomethingTheObjectDoesWith} {parameter1} {On/With/For/SomeOtherPreposition} {parameter2}”. The only way to name the method is “SomethingTheObjectDoesOn/With/For(parameter1, parameter2)”. It seems like I run into this situation too often. The API for all of the concerned code doesn’t necessitate building out a huge fluent interface for readability, but it would be nice to have things read just a little better in this case.
An example is certainly in order. I have an ASP.NET server control that activates a certain index on an associated MultiView. In order to let client code know whether or not it activates an index, I have this method:
public bool ActivatesViewOn(int viewIndex, string multiViewId)
{
    // Some logic that determines if the control activates the specified view
}
Here is the method in use:
filterPanel.Visible = itemClicked.ActivatesViewOn(0, contentMultiView.ID);
This is *kinda* self-documenting, but it doesn’t really read as nicely as it could. So I did this fairly minor refactoring in the control:
public IActivateViewOn ActivatesView(int viewIndex)
{
    return new ActivateViewOn(viewIndex);
}

public interface IActivateViewOn
{
    bool On(string multiViewId);
}

private class ActivateViewOn : IActivateViewOn
{
    private readonly int viewIndex;

    public ActivateViewOn(int viewIndex)
    {
        this.viewIndex = viewIndex;
    }

    public bool On(string multiViewId)
    {
        // Some logic that determines if the control activates the specified view 
    }
}
And now the calling code looks like:
filterPanel.Visible = itemClicked.ActivatesView(0).On(contentMultiView.ID);
So here I’ve created a miniature fluent interface that is specific to this method. But at what cost? Have I added needless complexity to the control? Arguably, I’ve made the client code more readable but the control code harder to maintain. Here’s how I see it:

  • PRO: Consuming code is easier to read.
  • PRO: Adding nested types (the IActivateViewOn interface and ActivateViewOn class) is no more complicated that adding methods. Basically, I get a nice fluent syntax by breaking my uglier method into a few smaller ones.
  • PRO: The added private class isn’t exposed to the client, so that piece doesn’t complicate the external API. The added interface is only exposed as a nested class on the control, so it doesn’t pollute the controls namespace.
  • PRO: I can modify this further pretty easily to keep my client code very readable as dictated by usage. Though it would probably be overkill to have itemClicked.Activates.FirstView.On(someMultiView), the option is there and the syntax could be easily produced.
  • PRO: I could rename the nested types for even more clarity in the control’s code.
  • CON: The IActivateViewOn interface might not aid discovery as a return value as much as bool might. I’m reaching here… I personally think the fluent interface is more discoverable. But how do I know I can eventually get the data that I want?
  • CON: A developer maintaining the control will think “what the hell is this?!?”.

Comments

Sam Nissim said…
I like the fluency and definitely agree with your policy on trading comments for more readable code in general. Another possible approach would be to create a MultiViewExtender control (similar to the extender controls in the Ajax Toolkit). The extender would take the MultiView, the view index, and the target control as properties. In this approach you would have to have many extenders if you have many views. Alternatively, you could have one extender as a composite control with many child bindings.

Popular posts from this blog

Who I'm Is

I am a junior .NET developer currently working in Chicago, IL. I am starting this blog in order to enhance my knowledge of programming subject matter. Hopefully, someone else will be helped along the way. This first post will probably be edited soon...

Stubbing Static Methods with PostSharp

TypeMock uses the Profiler API to allow mocking, stubbing, etc. of classes used by code under test. It has the ability to handle sealed classes, static classes, non-virtual methods, and other troublesome-yet-oft-encountered scenarios in the world of unit testing. Other frameworks rely on proxies to intercept method calls, limiting them to be able to only fake virtual, abstract, and interface members. They also rely on dependecy injection to place the proxies as the concrete implementation of calls to the abstracted interface members. Anyone working with a legacy codebase is bound to run into static method calls (especially in the data access layer), dependencies on concrete types with non-virtual methods, and sealed class dependencies (HttpContext anyone?). The only way to unit test this without refactoring is with TypeMock. I've never used TypeMock, and I'm sure it's a great product, but it's not free. I decided to spike some code to see if I could solve the prob...

Strongly-Typed Property Constraints in Rhino Mocks

UPDATE: As I suspected, this functionality was right in front of my face – it’s called PredicateConstraint in Rhino Mocks. I also realize that I managed to completely ignore the existence of Predicate<T> in the framework, and write my own predicate delegate. Hey, I was on a roll. Rhino Mocks has a PropertyConstraint class that allows you to check the values on properties of objects passed into the method as part of the verification for that method being called. Unfortunately, the name of the property is specified as a string, which means the benefits of strong-typing that Rhino Mocks is normally so good at preserving are lost. Here’s an example (using Rhino Mocks 3.3 and .NET 2.0): [Test] public void Main_Form_Should_Show_Start_Panel_On_Load() { MockRepository mockRepository = new MockRepository(); IMainFormView mockView = mockRepository.DynamicMock<IMainFormView>(); IEventRaiser loadEventRaiser = GetEventRaiserFor(delegate { mockView.Load += null; });...