Thursday, August 11, 2005

View Observer

Separation of presentation and domain can often be complex, especially concerning testing. Martin Fowler is developing a new book that provides patterns giving guidance on this topic. At my previous project we did something similar but not yet documented.

How It Works
Conceptually the view observer is quite easy. The view contains setters for any state that is dynamic and raises events in response to user actions. The views implement interfaces allowing for easy stubbing when testing observers. The observers observe the view and respond to events by changing any appropriate state and reloading the entire view.

When To Use It
View Observer is similar to both Model View Presenter (MVP) and Presentation Model (PM). Similar to MVP, the observer takes a view via constructor injection. When using MVP the most common approach to handling user interaction is to have the view call methods on the presenter. Unfortunately, the view then becomes tightly coupled to the presenter. Another option would be to add methods to the view that allow you to add delegates to the events of the view. The downside is that this introduces more logic in the view. View Observer handles user interaction issues by raising events in the view and handling them in the observers. This decreases coupling and reduces the logic in the view.

Unlike MVP but similar to PM, the observer maintains the state of the view. By maintaining the state in the observer the view can be fully refreshed after each state change. Obviously, this can be optomized if necessary, but coarse-grained refreshes reduce complexity and are recommended. Additionally, View Observer is easily testable via a xUnit tool instead of using view based testing.

Example (C#)
I'm going to use the common example Martin is using in the new book to demonstrate View Observer. The view is a simple Win Form with setters for the dynamic state and event handlers that raise new events. The View implements IAlbumView to allow easy testing using stubs or mocks.

public class AlbumForm : Form, IAlbumView
{
private ListBox albumListBox;
private Label artistLabel;
private Label titleLabel;
private TextBox artistTextBox;
private TextBox titleTextBox;
private CheckBox classicalCheckBox;
private Label composerLabel;
private TextBox composerTextBox;
private Button applyButton;
private Button cancelButton;
public event UserAction ApplyButtonClick;
public event UserAction CancelButtonClick;
public event UserAction ClassicalCheckBoxCheck;
public event TextChangedUserAction ArtistTextChanged;
public event TextChangedUserAction TitleTextChanged;
public event TextChangedUserAction ComposerTextChanged;
public event IndexChangedUserAction AlbumListBoxSelectedIndexChanged;

[Windows Form Designer generated code, dispose, & default constructor removed]

private void applyButton_Click(object sender, EventArgs e)
{
if (ApplyButtonClick!=null) { ApplyButtonClick(); }
}

private void cancelButton_Click(object sender, EventArgs e)
{
if (CancelButtonClick!=null) { CancelButtonClick(); }
}

private void albumListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (AlbumListBoxSelectedIndexChanged!=null) { AlbumListBoxSelectedIndexChanged(albumListBox.SelectedIndex); }
}

private void classicalCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (ClassicalCheckBoxCheck!=null) { ClassicalCheckBoxCheck(); }
}

private void artistTextBox_TextChanged(object sender, EventArgs e)
{
if (ArtistTextChanged!=null) { ArtistTextChanged(artistTextBox.Text); }
}

private void titleTextBox_TextChanged(object sender, EventArgs e)
{
if (TitleTextChanged!=null) { TitleTextChanged(titleTextBox.Text); }
}

private void composerTextBox_TextChanged(object sender, EventArgs e)
{
if (ComposerTextChanged!=null) { ComposerTextChanged(composerTextBox.Text); }
}

public string[] AlbumListBoxItems
{
set { albumListBox.DataSource = value; }
}

public string ArtistTextBoxText
{
set { artistTextBox.Text = value; }
}

public string TitleTextBoxText
{
set { titleTextBox.Text = value; }
}

public bool ClassicalCheckBoxChecked
{
set { classicalCheckBox.Checked = value; }
}

public string ComposerTextBoxText
{
set { composerTextBox.Text = value; }
}

public int AlbumListBoxSelectedIndex
{
set { albumListBox.SelectedIndex = value; }
}

public bool ComposerTextBoxEnabled
{
set { composerTextBox.Enabled = value; }
}
}

The Observer is responsible for syncronizing the Model with the observer. The model for this example is an album.

public class Album : IAlbum
{
private string title;
private bool isClassical;
private string artist;
private string composer;

public string Title
{
get { return title; }
set { title = value; }
}

public bool IsClassical
{
get { return isClassical; }
set { isClassical = value; }
}

public string Artist
{
get { return artist; }
set { artist = value; }
}

public string Composer
{
get { return composer; }
set { composer = value; }
}
}

The Observer contains fields that maintain the state of the View's controls. It accepts the View and the Model via constructor injection. In the constructor the Observer stores the reference to both the View and the Model and subscribes to the events published by the View.

public class AlbumObserver
{
private readonly IAlbumView view;
private readonly IAlbum[] albums;
private bool isListening = true;
private string artistTextBoxText;
private string titleTextBoxText;
private bool classicalCheckBoxChecked;
private string composerTextBoxText;
private int albumListBoxSelectedIndex;

public AlbumObserver(IAlbumView view, IAlbum[] albums)
{
this.view = view;
this.albums = albums;
view.AlbumListBoxSelectedIndexChanged+=new IndexChangedUserAction(SelectedIndexChanged);
view.CancelButtonClick+=new UserAction(ReloadFromModel);
view.ClassicalCheckBoxCheck+=new UserAction(ClassicCheckChanged);
view.ApplyButtonClick+=new UserAction(SaveToModel);
view.ArtistTextChanged+=new TextChangedUserAction(ArtistTextChanged);
view.ComposerTextChanged+=new TextChangedUserAction(ComposerTextChanged);
view.TitleTextChanged+=new TextChangedUserAction(TitleTextChanged);
ReloadFromModel();
}

...
}

The Observer is responsible for reloading the View after every state change and when the Observer is constructed. Changes to the model also cause the View to be reloaded. The isListening guard clause is needed to ensure that an infinite loop does not occur when reloading the View.

public class AlbumObserver
{
private void reloadView()
{
if (!isListening)
{
return;
}
isListening = false;
view.ArtistTextBoxText = artistTextBoxText;
view.ClassicalCheckBoxChecked = classicalCheckBoxChecked;
view.ComposerTextBoxText = classicalCheckBoxChecked?composerTextBoxText:string.Empty;
view.TitleTextBoxText = titleTextBoxText;
view.AlbumListBoxItems = createAlbumStringArray();
view.AlbumListBoxSelectedIndex = albumListBoxSelectedIndex;
view.ComposerTextBoxEnabled = classicalCheckBoxChecked;
isListening = true;
}

public void ReloadFromModel()
{
IAlbum selectedAlbum = albums[albumListBoxSelectedIndex];
artistTextBoxText = selectedAlbum.Artist;
classicalCheckBoxChecked = selectedAlbum.IsClassical;
composerTextBoxText = selectedAlbum.Composer;
titleTextBoxText = selectedAlbum.Title;
reloadView();
}

private string[] createAlbumStringArray()
{
string[] result = new string[albums.Length];
for (int i=0;i<result.Length;i++)
{
result[i] = albums[i].Title;
}
return result;
}

...
}

Saving to the model is quite straight forward.

public class AlbumObserver
{
public void SaveToModel()
{
IAlbum selectedAlbum = albums[albumListBoxSelectedIndex];
selectedAlbum.Artist = artistTextBoxText;
selectedAlbum.IsClassical = classicalCheckBoxChecked;
selectedAlbum.Composer = classicalCheckBoxChecked?composerTextBoxText:string.Empty;
selectedAlbum.Title = titleTextBoxText;
ReloadFromModel();
}

...
}

Lastly, the events raised from the View change the appropriate state and cause the View to be refreshed.

public class AlbumObserver
{
public void SelectedIndexChanged(int newIndex)
{
if (isListening)
{
albumListBoxSelectedIndex = newIndex;
ReloadFromModel();
}
}

public void ClassicCheckChanged()
{
if (isListening)
{
classicalCheckBoxChecked=!classicalCheckBoxChecked;
reloadView();
}
}

public void ArtistTextChanged(string text)
{
if (isListening)
{
artistTextBoxText = text;
reloadView();
}
}

public void ComposerTextChanged(string text)
{
if (isListening)
{
composerTextBoxText = text;
reloadView();
}
}

public void TitleTextChanged(string text)
{
if (isListening)
{
titleTextBoxText = text;
reloadView();
}
}

...
}

Tuesday, August 02, 2005

SetUp and Teardown are still not good

At dinner tonight we had a wonderful discussion about testing. One topic was why SetUp and Teardown (S&T) are wrong, which I've previously blogged about. My biggest issue with S&T is that it's used to enforce DRY at the expense of readability.

Image a test that did not use S&T, it would do exactly what you wanted all in one test method (with possible helper private methods). There would be no where else to look for logic, variable declarations, or mock verifies. Wouldn't it be nice if all tests were that readable.

Unfortunately, somewhere along the way we started sacrificing readability. Also, we started blindly following rules like DRY without considering context. Sure, DRY is a great rule, but what if the duplicate code only appears within the class? What if it were only 1 line, like a variable declaration? Do you really gain anything by abstracting it to a SetUp method? Yes, you gain the ability to only make changes in one place. But, if you could make the change in one place, ensure that it changed everything correctly, and not sacrafice readability. Does this magical feature exist? Find and Replace (in this file/class only). What about more than 1 line of duplicate code? Once upon a time this was handled with private methods and the flow of a test was easy to follow. Times were simpler then, but now we do "the simplest thing that could possibly work", or do we?

Tests are procedural by naturue. Allowing developers to read tests in a procedural manner just makes sense.

Thursday, July 21, 2005

Declaration of event accessors.

In C# event accessors are used to add and remove event handlers in client code. By declaring custom accessors you can change subscription behavior.

Problem: Prevent a client object from subscribing to the same event multiple times.

Example: You have a view that contains a Navigate event which is raised when the user needs to navigate to the next page.
class View : IView
{
public event NavigationHandler Navigate;

...

public void raiseNavigate()
{
Navigate(typeof(View2));
}
}

When Navigate is raised a presenter should clear the existing view and present a new one.
class FormPresenter
{
... constructor inject a view factory ...

public void NavigateTo(Type type)
{
IView view = viewFactory.Find(type);
view.Navigate+=new NavigationHandler(NavigateTo);
changeView(view);
}
}

This code works well if a new view is returned by the viewFactory every time. However, if the same view is returned from the factory, the presenter will subscribe to the Navigate event multiple times.

Solution: Subscribe to the Navigate event only if the presenter hasn't previously. Declaring the event accessors allows us to manage a single Navigate subscription per client model in the publisher.

Thus, View becomes:
class View : IView
{
private NavigationHandler navigationHandler;

private ArrayList navigateSubscriberInstances = new ArrayList();

public event NavigationHandler Navigate
{
add
{
if (navigationHandler==null || !navigateSubscriberInstances.Contains(navigationHandler.Target))
{
navigationHandler += value;
navigateSubscriberInstances.Add(navigationHandler.Target);
}
}
remove
{
navigationHandler -= value;
navigateSubscriberInstances.Remove(navigationHandler.Target);
}
}

protected void raiseNavigate(Type type)
{
if (navigationHandler!=null)
{
navigationHandler(type);
}
}
}

Saturday, July 09, 2005

Notification without Flood

Problem: Users want instant notification without notification flooding.

Examples: Send a text message when an unhandled exception is thrown, but only 1 per day. When a new loan request form is submitted send an email, unless an email was sent in the past hour.

Solution: Store the datetime of the last sent notification and check it before sending a new notification.

This simple solution is often forgotten and replaced by a service that polls solution. I like Notification without Flood much more because you can use the existing application without requiring creation of a service.

Sunday, July 03, 2005

Focus on readability and avoid being SetUp

The SetUp method is used to initialize a test prior to running it. However, there are disadvantages to using SetUp that should be noted. Christian Taubman pointed out a few of the disadvantages in a previous entry. The focus of his entry is replacing SetUp with private methods. While I agree with this, the focus of my entry is more about readability.

Assume you are working with a class:

public class Reservation
{
public Reservation(DateTime checkInDate, int nights, int guests)
{
this.checkInDate = checkInDate;
this.nights = nights;
this.guests = guests;
}

private DateTime checkInDate;
private int nights;
private int guests;
public event ErrorEventHandler ReservationBeforeToday;
public event ErrorEventHandler InvalidNights;
public event ErrorEventHandler InvalidGuests;
public delegate void ErrorEventHandler();

public void Validate()
{
if (checkInDate<DateTime.Today) ReservationBeforeToday();
if (nights<1) InvalidNights();
if (guests<1) InvalidGuests();
}
}

There should be tests for the logic in Validate. The test could look like this:

public class ReservationTests
{
private static bool eventRaised;
private static Reservation reservation;

[SetUp]
public void SetUp()
{
eventRaised = false;
reservation = new Reservation(DateTime.AddDays(-2),0,0);
}

[Test]
public void InvalidReservationRaisesEvent()
{
reservation.ReservationBeforeToday+=delegate { eventRaised = true; };
reservation.Validate();
}

[Test]
public void InvalidNightsRaisesEvent()
{
reservation.InvalidNights+=delegate { eventRaised = true; };
reservation.Validate();
}

[Test]
public void InvalidGuestsRaisesEvent()
{
reservation.InvalidGuests+=delegate { eventRaised = true; };
reservation.Validate();
}

[TearDown]
public void TearDown()
{
Assert.IsTrue(eventRaised);
}
}

While this code does accomplish what I was looking for I don't consider it to be very readable. An alternative which is much more readable could look like:

public class ReservationTests
{
private static bool eventRaised;
private static Reservation reservation;

public void Init()
{
eventRaised = false;
reservation = new Reservation(DateTime.AddDays(-2),0,0);
}

[Test]
public void InvalidReservationRaisesEvent()
{
Init();
reservation.ReservationBeforeToday+=delegate { eventRaised = true; };
reservation.Validate();
Assert.IsTrue(eventRaised);
}

[Test]
public void InvalidNightsRaisesEvent()
{
Init();
reservation.InvalidNights+=delegate { eventRaised = true; };
reservation.Validate();
Assert.IsTrue(eventRaised);
}

[Test]
public void InvalidGuestsRaisesEvent()
{
Init();
reservation.InvalidGuests+=delegate { eventRaised = true; };
reservation.Validate();
Assert.IsTrue(eventRaised);
}
}

However, the most readable version is my favorite:

public class ReservationTests
{
[Test]
public void InvalidReservationRaisesEvent()
{
bool eventRaised = false;
Reservation reservation = createReservation();
reservation.ReservationBeforeToday+=delegate { eventRaised = true; };
reservation.Validate();
Assert.IsTrue(eventRaised);
}

[Test]
public void InvalidNightsRaisesEvent()
{
bool eventRaised = false;
Reservation reservation = createReservation();
reservation.InvalidNights+=delegate { eventRaised = true; };
reservation.Validate();
Assert.IsTrue(eventRaised);
}

[Test]
public void InvalidGuestsRaisesEvent()
{
bool eventRaised = false;
Reservation reservation = createReservation();
reservation.InvalidGuests+=delegate { eventRaised = true; };
reservation.Validate();
Assert.IsTrue(eventRaised);
}

private Reservation createReservation()
{
return new Reservation(DateTime.AddDays(-2),0,0);
}
}

The result is a test that can be read almost entirely in isolation and understood easily.