Saturday, 12 January 2008

Readonly properties and testability

Sometimes an execution step requires that a property value is calculated. This value is used then in the subsequent step. When you want to test the second step in isolation, you usually mock the property. If you use "traditional" mock frameworks, or manually constructed stubs, the property should be virtual, and your object should be injected into the process somehow. This makes your design extendable, since whenever somebody wants a different behaviour, she can override the implementation of this property, and inject the custom object into the process.

Recently I discovered that the most flexible solution would be to create a special object that just transfers the data between the steps. You don't have to inject anything, if you want some custom data for the second step, you just create your data object manually. Without the dependency injection and inheritance requirements, the steps become completely isolated. You need some sort of controller to drive the flow, and your users can easily implement another controller with any of the steps replaced with different objects and different behaviour.

However, sometimes you, like me, are attached to the old fashioned idea of keeping behaviour with data. You need your class to expose the property and calculate its value:

Public Overridable ReadOnly Property SomeProperty() As SomeClass

Get

Dim result As New SomeClass

'Set some properties

Return result

End Get

End Property


The obvious solution is to calculate the property if you haven't set it yet, but still make it settable:

Private _someProperty As SomeClass

Public Property SomeProperty() As SomeClass

Get

If _someProperty Is Nothing Then _someProperty = CalculateValue()

Return _someProperty

End Get

Set(ByVal value As SomeClass)

_someProperty = value

End Set

End Property


Protected Overridable Function CalculateValue() As SomeClass

Dim result As New SomeClass

' Set some properties

Return result

End Function


A similar pattern can be applied to value objects. The trick is to make the associated private variable nullable:

Private _someProperty As Nullable(Of Boolean)

Public Overridable Property SomeProperty() As Boolean

Get

If Not _someProperty.HasValue Then _someProperty = CalculateValue()

Return _someProperty

End Get

Set(ByVal value As Boolean)

_someProperty = value

End Set

End Property


Protected Overridable Function CalculateValue() As Boolean

'Do stuff

End Function


Finally, let's try a similar thing with enumerables. Typically, we expose an enumerable as a readonly property, and fill the values at the initialization stage. Here we do a similar trick, but on a certain condition. We add a boolean property AutoCalculateValues and calculate them only if it is set to true, which is the default behaviour:

Private _autoCalculateValues As Boolean = True

Public Property AutoCalculateValues() As Boolean

Get

Return _autoCalculateValues

End Get

Set(ByVal value As Boolean)

_autoCalculateValues = value

End Set

End Property

Private _someProperty As IList(Of SomeClass)

Public Overridable ReadOnly Property SomeProperty() As IEnumerable(Of SomeClass)

Get

If _someProperty Is Nothing Then

_someProperty = New List(Of SomeClass)

End If

Return _someProperty

End Get

End Property

Protected Overridable Sub CalculateValues(ByVal list As IList(Of SomeClass))

list.Add(New SomeClass)

'...

End Sub


This time, the property is not settable, but the idea that it is initialized by default but the initialization can be switched off.

So, what are the advantages? In terms of testability, we can set the desired values directly, instead of using mocks, which simplifies our life a bit, and our tests become even more clear. But the main point is about reuse. Testability with mocks implies that one can modify the behaviour of our class by inheritance. A user of our framework can create a descendant of our class, overriding the property, and inject it into the workflow, just as we do in our tests. Making the property settable, on the other hand, makes it possible to extend the behaviour by composition: a user can, for example, add another class that sets the property in response to some external conditions. Another, more important, possibility, is to set the property manually. For example, on a Web page, the block elements are usually go under each other, but sometimes you want to position your div manually. You don't override the div class, you just tell it, "don't calculate your position, I'll do it myself". Note that the old inheritance possibility is still there -- you can override the CalculateValue() method if you want.

So, the system definitely becomes more open. This will definitely make the users of your component happier, but also opens more possibilities for misuse. For example, I could set the value that would put the system into an invalid state. However, the same result can be "achieved" by inheritance, only with more efforts. So, apart from validation, the best solution is writing docs properly. And remember that what seems like misusing to you might be a perfect way of using for others.

I'm using these ideas for some time with Inka, and I discovered that my design has improved. Each time I'm tempted to mock a parameterless method, I'm trying to convert it into a property, and then make it settable. I discovered that I have less dependencies and better decoupling, less pulls and more pushes, less methods that cover all possible situations, more small classes specifically designed for each situation.

Inka Layout, take three

The next release if Inka is being delayed, again and again. I decided to rewrite the layout engine. I already wrote about that ( see here, for example).

In short, first I tried Need Driven development: implement it step by step, mocking out the next step before implementing the current. This became a disaster: too much upfront design for me. Without seeing the whole picture, I was never sure that it works, much less that it works the way it should.

My second attempt was much better. At least it began better. I implemented a quick and dirty solution first, then added a few more integration tests and made my solution a bit more complex, then began to refactor. The refactoring stage took forever though. I still haven't finished it in the last release, so I was too shy to publish the code. With only integration tests in place, I wasn't seeing the correct direction of refactoring, so I was doing it blindly, and it took ages to figure out why this particular test broke when I did this simple refactoring.

Now it's the third attempt, and I've already abandoned version 3a. But I don't want to talk about it yet, until I see the results. I should say that the trunk version is the same as used in the last release, since I decided to put the new experimental version in a separate branch.

Wednesday, 12 December 2007

TDDing a HelloWorld application

I'm going to write a very simple WinForms application using TDD, and I'm going to refactor it using TDD as well.

As I'm just learning good OOP design, I often don't have any idea as to how to refactor my (already working) code, and how to properly implement separation of concerns. I also don't know how much I have to cover with tests: I tried too little and was lost in refactoring, I tried too much and couldn't change my design without breaking a lot of tests, so I didn't know if everything was still working or not. So, I'm going to apply my new idea of Test Driven Refactoring and hope that it would bring me somewhere.

Here's the story. We have a form with a textbox and a button. I enter "Martin" in the text box, press a button, and a message box saying "Hello Martin" should appear.

Should I apply MVP or MVC here? Probably, but I won't. Folks say, let the tests drive your design, so I'm letting them. But first, I want to make it work as quickly as I can, so I write a simple test using NUnitForms (see below), and I quickly get the following code:


Private Sub HelloButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HelloButton.Click

MessageBox.Show("Hello " & Me.NameTextBox.Text, "Hello")

End Sub


I quickly see that my form is doing too much. It's been created for the purpose of showing the UI elements and reacting to the user input. However, in this code it decides how to greet the user. It decides how to construct the message, and that the messagebox should be shown.


How do I refactor this code? First, let's see the test:


<Test()> Sub PressingTheButtonShowsAMessage()

Dim form = CreateForm()

form.Show()

Dim boxTester As New TextBoxTester("NameTextBox", form)

boxTester.Enter("Martin")

Dim buttonTester As New ButtonTester("HelloButton", form)

ExpectModal("Hello", AddressOf HelloHandler)

buttonTester.Click()

End Sub



Public Sub HelloHandler()

Dim messageBoxTester = New MessageBoxTester("Hello")

Assert.AreEqual("Hello Martin", messageBoxTester.Text, "Invalid message text")

messageBoxTester.ClickOk()

End Sub


Function CreateForm() As Windows.Forms.Form

Return New TestDrivenRefactoring.Form1

End Function


I see that the test's setup phase is too big. In fact, the whole Test Driven Refactoring (TDR for short) process is built around the idea that too much test setup is a code smell. Specifically, we should refactor so that our unit test's setup takes just as much information as required. For example, in this case, all we need to test the message box is the text of the message. So, we should refactor our code into two components: the first, A, passes some object, X, to the second, B, and the second displays a message box. The information is somehow "packed" into X, and our test should be able to create X directly and pass it to B to test it independently of A.

What is X? It should be created using a single string, and it should provide the same string to B. It could be just a string, but another TDR principle states that such intermediate objects should be flexible, so it's best to make it a custom object. Why not an interface? Could be as well an interface, but we have a simple data transfer object here, with no behaviour, so a custom class should be fine. Let's call it PersonData, and let's rename B to MessageBoxService.

Here's our test for the new class:


<Test()> Sub CallingTheShowMessageMethodShowsAMessage()

ExpectModal("Hello", AddressOf HelloHandler)

Dim messenger As New MessageBoxService

Dim message As New Message With {.Text = "Hello Martin"}

messenger.ShowMessage(message)

End Sub


We see that the setup portion contains just enough: the first line is an expectation which is sort of an assert, creating the two objects doesn't count, and the only nontrivial thing is setting the Text property of the Message object. Now we clearly have a messaging component that encapsulates showing a message box and has no other concerns.

But what about the rest of the application? We can refactor our it straightforwardly:

Private Sub HelloButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HelloButton.Click

Dim messenger As New MessageBoxService

Dim message As New Message With {.Text = "Hello " & Me.NameTextBox.Text}

messenger.ShowMessage(Message)

End Sub


Our first, functional test still passes. But now we are unable to test the behaviour independently of the MessageBoxService object. It is more or less fine that we have a hardcoded Message class -- it's just a simple class with no behaviour. But hardcoding the MessageBoxService class is a real problem: at some point we'll want to switch all our message boxes to the new Vista-style dialogs, or provide a custom form, whatever. We'll have to search-replace thru all of our code to change that.

But at this very moment the problem is that we can't test the remaining piece. So, we have to inject a dependency. Now, we don't want hold a reference to the MessageBoxService inside our form class, since we are not sure we'll need it after the refactoring is finished. So, we use a ServiceLocator pattern.

First we introduce the IMessageService interface:

Public Interface IMessageService

Sub ShowMessage(ByVal message As Message)

End Interface


Next, we do something that is considered one of the worst practices: we introduce a global variable:

Module Globals

Public Services As System.ComponentModel.Design.ServiceContainer

End Module


Now we can obtain a reference to our MessageBoxService as simple as

Dim messenger = Services.GetService(GetType(IMessageService))

But of course we should set it to a concrete service somewhere in the setup code, which has nothing to do with our form:

Services.AddService(GetType(IMessageService), New MessageBoxService)

Similarly, in our test we set it to a mock service, and expect a call to its ShowMessage method.

(to be continued)