Tag Archives: Patterns

Presenting ValueType<T>

Here is a base class for some code that i have written once too many in my life: (In case you’re an early adaptor (.Net 4.0) you may want to use System.Tuple<T1> as base class)

public class ValueType<t> : IComparable, IComparable<valueType<t>>, IEquatable<valueType<t>>
 where T : IComparable<t>
{
 protected T Value { get; private set; }public ValueType(T value)
 {
  Value = value;
 }

 public override int GetHashCode()
 {
  return Value.GetHashCode();
 }

 public override string ToString()
 {
  return Value.ToString();
 }

 public override bool Equals(object obj)
 {
  return Equals(obj as ValueType<t>);
 }

 public bool Equals(ValueType<t> other)
 {
  return Compare(this, other) == 0;
 }

 public int CompareTo(object obj)
 {
  return CompareTo(this, obj as ValueType<t>);
 }

 public int CompareTo(ValueType<t> other)
 {
  return Compare(this, other);
 }

 static int Compare(ValueType<t> instance1, ValueType<t> instance2)
 {
  if (ReferenceEquals(instance1, instance2)) return 0;
  if (ReferenceEquals(instance1, null)) return -1;
  if (ReferenceEquals(instance2, null)) return 1;

  if (ReferenceEquals(instance1.Value, instance2.Value)) return 0;
  if (ReferenceEquals(instance1.Value, null)) return -1;
  if (ReferenceEquals(instance2.Value, null)) return 1;

  return instance1.Value.CompareTo(instance2.Value);
 }

 public static bool operator ==(ValueType<t> instance1, ValueType<t> instance2)
 {
  return Compare(instance1, instance2) == 0;
 }

 public static bool operator !=(ValueType<t> instance1, ValueType<t> instance2)
 {
  return !(instance1 == instance2);
 }

 public static bool operator <(ValueType<t> instance1, ValueType<t> instance2)
 {
   return Compare(instance1, instance2) < 0;
 }

 public static bool operator >(ValueType<t> instance1, ValueType<t> instance2)
 {
   return Compare(instance1, instance2) > 0;
 }
}

Do we need an EventAggregator when we have an IOC container?

An Event Aggregator is an example of a Publish/Subscribe channel. A while ago i started wondering if we still need an Event Aggregator in our compisite applications if we have an IOC container that takes cares of dependency wiring. An IOC container can easily inject the Event/MessageHandler(s) in the Event/MessagePublisher(s)… I’m still not sure about the answer (Yes/No).

Creating series of elements

Lately i have done quite a bit of charting. Very often the X-axis is populated with a series of numbers or dates. This can be as simple as: (My very little DSL in Jeremy D. Miller Style)

[Test] public void ShouldBeAbleToGetSeriesOfNumbers()
{
 // Arrange
 var series = 3.To(5);

 // Act
 var elements = series.Elements;

 // Assert
 var expected = new[] { 3, 4, 5 };
 CollectionAssert.AreEqual(expected, elements);
}

[Test] public void ShouldBeAbleToGetSeriesOfDays()
{
 // Arrange
 var now = DateTime.Now.Date;
 var twoDaysLater = now.AddDays(2);
 var series = now.To(twoDaysLater);

 // Act
 var elements = series.Elements;

 // Assert
 var expectedDays = new[] { now, now.AddDays(1), now.AddDays(2) };
 CollectionAssert.AreEqual(expectedDays, elements);
}

And here is the code that makes these tests pass:

public static class Series
{
 public static Series<int> To(this int from, int to)
 {
  return Create(from, to);
 }

 public static Series<dateTime> To(this DateTime from, DateTime to)
 {
  return Create(from, to);
 }

 public static Series<dateTime> Create(DateTime from, DateTime to)
 {
  return new Series<dateTime>(from.Date, to.Date, d => d.AddDays(1));
 }

 public static Series<dateTime> Create(DateTime from, int numberOfDays)
 {
  return Create(from.Date, from.Date.AddDays(numberOfDays));
 }

 public static Series<int> Create(int from, int to)
 {
  return new Series<int>(from, to, n => n + 1);
 }

 public static Series<int> Create(int from, int to, int stepSize)
 {
  return new Series<int>(from, to, n => n + stepSize);
 }
}


public class Series<t> : IEnumerable<t> where T : IComparable
{
 public T From { get; private set; }
 public T To { get; private set; }
 public Func<t, T> Step { get; private set; }

 public Series(T from, T to, Func<t, T> step)
 {
  From = from;
  To = to;
  Step = step;
 }

 public IEnumerable<t> Elements
 {
  get
  {
   var current = From;
   while (current.CompareTo(To) <= 0)
   {
    yield return current;
    current = Step(current);
   }
  }
 }

 public IEnumerator<t> GetEnumerator()
 {
  return Elements.GetEnumerator();
 }

 IEnumerator IEnumerable.GetEnumerator()
 {
  return GetEnumerator();
 }
}

In case you really have to Append one array to another

Here is another problem i’ve seen people solve once too many: Append one array to another. STOP. Revisit the problem. Can’t you simply use List<T> and move on to solving actual business problems? In case you really can’t get rid of the arrays read the following:

Given()
{
 source = new[] { SourceElement };
 destination = new[] { DestinationElement };
}


When()
{
 source.AppendTo(ref destination);
}


ThenTheDestinationShouldStillHaveTheDestinationElement()
{
 Assert.AreEqual(DestinationElement, destination[0]);
}


ThenTheDestinationShouldHaveBeenExtendedWithTheSourceElement()
{
 Assert.AreEqual(SourceElement, destination[1]);
}

And here is the code which satisfies the requirements:

public static class Extensions
{
 public static void AppendTo<t>(this T[] sourceArray, ref T[] destinationArray)
 {
  var sourceLength = sourceArray.Length;
  var destinationLength = destinationArray.Length;
  var extendedLength = destinationLength + sourceLength;
  Array.Resize(ref destinationArray, extendedLength);
  Array.Copy(sourceArray, 0, destinationArray, destinationLength, sourceLength);
 }
}

Perhaps it’s time to start (or does it exist already, cause i can’t find it) an open-source project with extension methods.

About databinding and composite views

A couple of days ago i had a databound ItemsControl (collection of Model.Cell) which instantiated sub views (with their own viewmodel).

 <grid.Resources>
  <dataTemplate x:Key="CellTemplate">
   <views:CellView />
  </dataTemplate>
 </grid.Resources>
 <itemsControl
   ItemTemplate="{StaticResource CellTemplate}"
   ItemsSource="{Binding Cells}" />
</grid>

Because each CellViewModel needs to know which cell they manage i used the following dirty hack:

public CellView()
{
 Loaded += CellView_Loaded;
}

void CellView_Loaded(object sender, RoutedEventArgs e)
{
 DataContext = new CellViewModel(DataContext);
}

Later on that day i realised there was a much cleaner solution: Let the BoardViewModel expose a collection of ViewModels.CellViewModel instead of Model.Cell. What a relief that i don’t have to use the Loaded event hack :)

Exploring M-V-VM

A couple of years ago a collegue recommended Data Binding with Windows Forms 2.0: Programming Smart Client Data Applications with .NET and i noticed that my code started to gravitate towards an Model-View-ViewModel architecture. Due to shortcomings and painful experiences i gave up on databinding and began to use Passieve View instead.

Passive View doesn’t work (well) with smart views so i decided to give M-V-VM another because i really wanted to leverage WPF’s rich support for databinding.

The key difference between M-V-VM and Passive View is, imho, the fact that the ViewModel is unaware of the View unlike Passive View where the Presenter knows about the (simple) View.

When we test a Presenter i notice that we end up writing interaction based tests (assertions on a mocked view) and when we test a ViewModel we end up writing state-based tests instead.

Extension methods to improve readability

A common reason to take advantage of extension methods is to enhance readability (think fluent interfaces). My team uses the specification pattern regularly and in case a requirement says something like “if the player has reached level 10 a message should be displayed” they would implement it as:

if (new HasReachedLevel(10).IsSatisfiedBy(player))
{
 view.DisplayMessage("Congratulations! You have reached level 10.");
}

Pretty good but did you notice that they changed the order of player and level in their (code) story? With the aid of an extension method we can express this requirement as:

if (player.Satisfies(new HasReachedLevel(10)))
{
 view.DisplayMessage("Congratulations! You have reached level 10.");
}

Here is the extension method that allows you to express the requirement in this way:

public static bool Satisfies<t>(this T candidate, ISpecification<t> specification)
{
 return specification.IsSatisfiedBy(candidate);
}

Experimenting with ControlStateMachine and Fluent interfaces

A long time ago i read Build your own CAB series and recently i noticed that there is a wiki: Presentation Patterns Wiki! and it inspired me to experiment with state machines. Here are a couple of examples:

controlStateMachine = new ControlStateMachine<states>(this);

controlStateMachine.AfterEachStateChange()
 .Do(MakeRelevantButtonsVisible);

controlStateMachine.WhenStateChangesTo(States.RetrievingSubscriptionPeriod)
 .TheOnlyVisibleControlsAre(flowLayoutPanel1, datePicker1);

controlStateMachine.WhenStateChangesTo(States.RetrievingCustomerInformation)
 .MakeVisible(customerInput1)
 .Do(() => customerInput1.Dock = DockStyle.Fill);

controlStateMachine.WhenStateChangesTo(States.Ready)
 .MakeInvisible(customerInput1);

And here is another example:

wizardStateMachine = new WizardStateMachine<states>(controlStateMachine);

wizardStateMachine.InState(States.RetrievingSubscriptionPeriod)
 .OnCommand(WizardCommands.Next)
  .TransitionTo(States.RetrievingCustomerInformation);

wizardStateMachine.InState(States.RetrievingCustomerInformation)
 .OnCommand(WizardCommands.Back)
  .TransitionTo(States.RetrievingSubscriptionPeriod)
 .OnCommand(WizardCommands.Finish)
  .TransitionTo(States.Ready);

wizardStateMachine.InState(States.Ready)
 .OnCommand(WizardCommands.New)
  .Do(() => MessageBox.Show("Currently not supported"));

Stay tuned for future posts where i describe the problem space that have lead to this API.

Strict mocks lead to overspecification

Here is an example that demonstrates how strick mocks lead to overspecification. Imagine that we are creating a simple screen in a Passive View architecture. The first feature that we implement is displaying the message “edit” when the user clicks the edit button:

[Fact] public void ShouldDisplayEditClickMessage()
{
 // Establish context
 MockRepository mockRepository = new MockRepository();
 IView view = mockRepository.StrictMock<iview>();
 Expect.Call(delegate { view.EditClick += null; }).IgnoreArguments();
 mockRepository.Replay(view);

 // Create sut
 Presenter sut = new Presenter(view);

 // Setup expectations
 mockRepository.BackToRecord(view, BackToRecordOptions.Expectations);
 Expect.Call(delegate { view.DisplayClickMessage("edit"); });
 mockRepository.ReplayAll();

 // Exercise
 RhinoMocksExtensions
  .GetEventRaiser(view, delegate(IView v) { v.EditClick += null; })
  .Raise(view, EventArgs.Empty);

 // Verify
 mockRepository.VerifyAll();
}


screenshot of test runner with all tests passing

And now we add the feature that displays the message “save” whenever the user clicks on the save button:

[Fact] public void ShouldDisplaySaveClickMessage()
{
 // Establish context
 MockRepository mockRepository = new MockRepository();
 IView view = mockRepository.StrictMock<iview>();
 Expect.Call(delegate { view.EditClick += null; }).IgnoreArguments();
 Expect.Call(delegate { view.SaveClick += null; }).IgnoreArguments();
 mockRepository.Replay(view);

 // Create sut
 Presenter sut = new Presenter(view);

 // Setup expectations
 mockRepository.BackToRecord(view, BackToRecordOptions.Expectations);
 Expect.Call(delegate { view.DisplayClickMessage("save"); });
 mockRepository.ReplayAll();

 // Exercise
 RhinoMocksExtensions
  .GetEventRaiser(view, delegate(IView v) { v.SaveClick += null; })
  .Raise(view, EventArgs.Empty);

  // Verify
  mockRepository.VerifyAll();
 }
}


screenshot of test runner with a failing test.

Although we implemented the feature correctly, and left the code of the first feature untouched, we notice that our ShouldDisplayEditClickMessage test fails because it is not expecting a subscription to the SaveClick event. Imho, this way of testing is a testing anti-pattern.

Refactoring EffectivityManager

A while ago i presented the EffectivityManager. Having used this class for a while i have decided to rename it to Temporal<T>. The implementation of IList<T> is not required anymore because a user is typically only interested in a specific effectivity, not the evolution of the effectivities.

/// <summary>
/// Represents an element that changes over time.
/// It consists out of effectivities of that element that are effective in different periods.
/// </summary>
public interface ITemporal<t>
{
 /// <summary>
 /// Modifies the element from the given date.
 /// </summary>
 /// <param name="element"></param>
 /// <param name="from"></param>
 /// <returns></returns>
 void Modify(T element, DateTime from);

 /// <summary>
 /// Gets the effectivity that is valid on the given date.
 /// </summary>
 /// <param name="validityDate">The validity date.</param>
 /// <returns></returns>
 IEffectivity<t> GetSnapshot(DateTime validityDate);

 /// <summary>
 /// Tries to get the effectivity that is valid on the given date.
 /// </summary>
 /// <param name="validityDate"></param>
 /// <param name="effectivity"></param>
 /// <returns></returns>
 bool TryGetSnapshot(DateTime validityDate, out IEffectivity<t> effectivity);
}

In the implementation i have added a constructor that accepts a DiscreteValuesGenerator<DateTime> which makes it possible to create Periods with a resolution of a day instead of seconds.