Thoughts on Software by Andrew Davey
 Tuesday, August 14, 2007
A (somewhat) new approach to application development

I am excited about Silverlight 1.1 – very excited! Whilst all the graphics and animations will be a wonder for creating great user experiences, I eagerly awaiting the chance to run managed code in the browser.

In my mind, and partially in code, I have already begun to formulate a new way to design applications. Of course, by new I really mean stealing a bunch of existing good ideas and gluing them together!

The first key idea is putting the users first – always. These auto-magic, drag-n-drop data binding tools are great for quick and dirty CRUD applications, but I am yet to see one produce an application that has great usability. We need to start by putting ourselves in the user’s position and thinking about why they are using our software in the first place. It is all about finding the simplest, cleanest, more beautiful way to enable the user to get their job done. Slapping another data grid on a page probably is the worst approach!

I am a new convert to the Model-View-Presenter way of writing client applications. Although, I think, the order of coding should be Presenter-View-Model (it does not have quite the same ring to it however). In addition, by View I mean the view implementation, not the UI design. I always sketch the view design on paper/white board first. I suppose using a tool like Microsoft Expression Blend would be OK as long as you are not precious about the XAML it creates. I am never afraid to throw out code and start afresh, so why should UI mark-up be any different? Use whatever tools you find easiest to knock up UI prototypes and shove them under the user’s nose. The key here is to know roughly what buttons, textboxes, etc, the UI will contain (we can leave all the fancy colouring in to some guy in a turtle neck). Once this is the case, we can begin the most important part of the coding: The User Interaction Logic (UIL).

The UIL is the Presenter. The UIL says stuff like when the user clicks this button, read this data from the UI, tell the underlying model to do something and then tell the view to update. Whilst for some applications this level of control may seem like overkill, I argue that having to slow down sometimes is OK. This approach means you have to think about what the user will be doing in your application.

The best way to develop this code is by being test-driven. Create unit tests that describe the behaviour of the Presenter in terms of how it interacts with View and Model object-oriented interfaces. Each user story then becomes testable.

Key tools I plan to use here are:

Rhino Mocks – to create mock objects of Views and Models

Boo + my Rhino Mocks DSL – to make the unit tests easy to read and write

SharpDevelop – because Boo is not readily usable in Visual Studio yet

Visual Studio 2008 – to write the implementation of the Presenter in C#

As awesome as the language Boo is, I just cannot stand SharpDevelop for more than simple projects like the unit tests. Refactoring, intellisense and code-completion are just way to well done in Visual Studio to ignore it. I have enough memory and screen space to run VS and SD side-by-side.

As the Presenter is written, the interfaces for the View and Model are being fleshed out. The refactoring tool adding the methods automatically to the interfaces usually does this.

The choice now is whether to develop the Model or the View next. The View is a very dumb object that simply maps data to and from the UI and raises events when the user does stuff (clicks, key presses, etc). Since Silverlight does not have data binding yet, this may lead to somewhat tedious code. Bear in mind also that the Presenter is meant to be doing tasks such as converting strings into numbers and back. However, I reckon a tool can generate most of the standard mapping code.

The declarative nature of XAML means it should be easy to add attributes to button elements that describe the event they should raise when clicked. A tool could scan this data and write the code for me.

If data binding was ever added to Silverlight, I would consider creating pure “data” objects that the Presenter tells the View to bind too. No logic would be contained within the data objects.

The Model is where things become more interesting from a software architecture point of view. Silverlight runs in the client’s web browser. So the Presenter is running client-side, as is the Model on which is depends. The Model is maintaining state about the client application. For example, which check boxes are checked, which customer is selected? However, the Model also will need to communicate with a database running back on the server to read and write data.

To solve this problem, I plan to use my tier splitting C# macro. I will write the Model class as one coherent class. By coherent I mean all the data is there and all the logic regarding the data is there. I do not believe manually splitting the class and messing about with proxies and web services makes any business sense. I am not developing some kind of SOA application that is to be called by numerous different clients. I am trying to get my Model to save its valuable data on the database that is only accessible from the web server from whence it came. This is a reasonable tight coupling between the client and server versions of the Model. The coupling is so tight; I argue that I do not even want to see it!

In the case where the data does come from a remote web service, we still have to return to the application’s home server since Silverlight disallows cross-domain calls. It makes sense to put any database calls/remote web services calls into the Model. The Model knows what data it needs, so why bother moving that knowledge outside of the class only to marshal all the data back in again.

With LINQ being available we do not even have to pollute the Model with database specific SQL.

The tier splitting macro will handle generating all the WCF services and proxies. I just have to decorate the Model’s remote methods with [RunAtServer].

Thorough unit testing of the Model is required. It should be possible to create a mock D-LINQ implementation. I can then make assertions about how the Model interacts with the data layer.

In summary, I want to have a Silverlight UI that is but a marionette to a Presenter running client-side. This presenter has complete unit testing to describe the different user interactions. The Presenter uses a Model object to store all data. This Model exists on both the client and server side. However, the split implementation is effectively invisible to the developer.

The application of adequate tooling (both 3rd party and custom made) will make this an excellent way to approach writing applications. As Silverlight 1.1 becomes more complete, I will continue to expand this topic.

The result should be a happier developer and, more importantly, a happier user.


Tuesday, August 14, 2007 1:02:43 PM (GMT Standard Time, UTC+00:00)  #    Comments [0]   |  |  |  |  |  |  |  | 

 Friday, July 06, 2007
Code for the Rhino Mock DSL

I have attached the Boo code containing the Rhino Mocks DSL I'm currently working on. This is very much a work in progress release, just to get it out there. Please have a play and tell me what you think. Happy Mocking!

Dsl.boo (3.4 KB)

To use the DSL, add the following in your code to import the static methods into scope.

import Rhino.Mocks.Dsl


Friday, July 06, 2007 12:19:48 PM (GMT Standard Time, UTC+00:00)  #    Comments [2]   |  |  |  |  | 

 Wednesday, July 04, 2007
Better Syntax for Mocking

I thought some more about the syntax of my Rhino Mock DSL. It can feel unnatural putting all the mock expectation code before the call to the object being tested. I came up with this working prototype instead:

[Test]
def Get_data_objects_for_nonexistent_company_throws():
    with_mocks:
        database = mocks.CreateMock[of IDatabase]()
        userProvider = StubUserProvider("andrew", "bad corp")
        userProvider.MakeCurrent()

        execute:
            uds = UserDataService(database, userProvider)
            expect_throw FaultException[of GetDataObjectsFault]:
                uds.GetDataObjects()
            assert thrown_exception.Detail.Type.Equals(GetDataObjectsFaultType.InvalidCompany)

        assuming:
            database.GetUserID("andrew", "bad corp")
            returned 1
        assuming:
            database.GetCompanyID("bad corp")
            returned 0 # returning 0 from database implies nonexistent company.

The with_mocks method sets up the mock repository and a Store object. The execute and assumption methods then put their blocks into the Store. At the end of with_mocks I iterate through assumptions calling each to set up the Rhino Mock expectations. Following that is: mocks.ReplayAll(), call to the "execute" block, then mocks.VerifyAll().

The other clever bit in there is the expect_throw method. This runs the block inside a try...except and fails if no exception (or wrong exception type) is thrown. It puts the exception object into field that is readable using thrown_exception. This means we can then test assertions about the exception contents. I had to cheat a bit and declare thrown_exception as "duck" in Boo i.e. it is late bound. This is so we can access members on the actual object despite not really knowing about it at compile time.

I like the readability now. The outline is:

  • Initialize mocks and data objects
  • Call the object being tested
  • Assert about the result
  • State the assumptions about how dependencies are used

The key bit, I feel, is that the call to the object being tested is not buried down at the bottom of the method.

How does everyone else feel about this modified approach?


Wednesday, July 04, 2007 10:41:55 AM (GMT Standard Time, UTC+00:00)  #    Comments [0]   |  |  |  |  | 

 Monday, July 02, 2007
Rhino Mocks DSL in Boo

I recently learnt that Boo now supports a DSL-friendly syntax. A while back I created (and almost finished!) a set of syntactic macros in Boo to make using Rhino Mocks much more natural. Creating macros can be hard work though and gets pretty hacky in places.

The new DSL-friendly syntax in Boo means I can achieve 80% of the same easy-reading code, but using only methods and blocks!

In about 10 minutes I whipped up this:

namespace ConsoleDemo

import System
import Rhino.Mocks
import Rhino.Mocks.BooDsl.MockDsl

interface IModel:
    def CalculateScore(input as int) as int
interface IView:
    def DisplayScore(score as int)
interface IPresenter:
    def Init()

class Presenter(IPresenter):
    _model as IModel
    _view as IView
    def constructor(model as IModel, view as IView):
        _model = model
        _view = view
    def Init():
        score = _model.CalculateScore(0)
        _view.DisplayScore(score)

def Test_presenter_init():
    with_mocks:
        // Create mocks of the dependencies
        model = Mocks.CreateMock of IModel()
        view = Mocks.CreateMock of IView()
        // Create the object we are testing
        presenter = Presenter(model, view)
        // Record what we expect the presenter to
        // do with its dependencies.
        record:
            expect:
                model.CalculateScore(0)
                // Set the return value for the
                // previous mock call.
                mock_return 42
            expect:
                view.DisplayScore(42)
        // Now tell the presenter to do its stuff,
        // so we can verify it behaves correctly.
        verify:
            presenter.Init()
print "testing..."
Test_presenter_init()
print "all good!"
print "Press any key to continue . . . "
Console.ReadKey(true)

The import of "Rhino.Mocks.BooDsl.MockDsl" brings some new methods into scope. with_mocks initializes a MockRepository. "Mocks" is actually a property referencing that repository, so we can call CreateMock, etc, on it. The record and verify methods make use of the Mocks.Record() and Mocks.Playback() methods. I prefer using "verify" to "playback". The "expect" method runs the code in its block, usually that invokes some mock method. It then calls "LastCall.Repeat.Once()" to set up the expectation. The "mock_return" method calls "LastCall.Return(value)" to set up the return value for the last mock call.

This is all a bit messy for now I know. I have just being throwing code down into this prototype to get a feel for what is possible. I reckon this could be really useful for people using Rhino Mocks.

If you like what you've seen or have any ideas let me know.

The DSL methods are as follows:
I am aware of more than one glaring danger in the code(!) but it does show what can be done.

namespace Rhino.Mocks.BooDsl

import System
import Rhino.Mocks

callable Block()

static class MockDsl:

    private static _instance as MockDslImpl
    static def with_mocks(b as Block):
        _instance = MockDslImpl()
        b()
        _instance = null
    static def record(b as Block):
        assert _instance != null
        _instance.Record(b)
    static def verify(b as Block):
        assert _instance != null
        _instance.Verify(b)
    static def expect(b as Block):
        assert _instance != null
        _instance.Expect(b)
    static def mock_return(value as object):
        assert _instance != null
        _instance.MockReturn(value)
    static Mocks as MockRepository:
        get:
            assert _instance != null
            return _instance.Mocks

    private class MockDslImpl:
        mocks as MockRepository
        def constructor():
            mocks = MockRepository()
        public Mocks as MockRepository:
            get:
                return mocks
        public def Record(b as Block):
            using mocks.Record():
                b()
        public def Verify(b as Block):
            using mocks.Playback():
                b()
        public def Expect(b as Block):
            b()
            LastCall.Repeat.Once()
        public def MockReturn(value as object):
            LastCall.Return(value)


Monday, July 02, 2007 11:03:52 PM (GMT Standard Time, UTC+00:00)  #    Comments [0]   |  |  |  |  |