I read Sergio’s post on “Javascript, time to grok closures” today and it was very enlightening. Overall, it helped me to understand closures more than I previously had – not just in Javascript, though. I put together a quick sample on closures in C# to illustrate the same behavior that Sergio is talking about in the ‘Closures can be tricky’ section of his post. I’m happy to see C# is behaving the same way as Javascript, in the case of ‘value’ types in closures. This probably isn’t new to anyone that understands closures already. It’s new to me, though, and seems to be a fairly important concept to understand when using anonymous methods (lambda expression or otherwise) and closures. Illustrating The Closure Scope For Value Types Here is the sample code I put together, in unit test form, to illustrate the same behavior that Sergio is pointing out. [TestFixture]
public class When_referencing_a_value_type_variable_from_the_parent_scope_directly_in_a_closure : ContextSpecification
{
private readonly IList<Func<int>> theActions = new List<Func<int>>();
protected override void Context()
{
for (int i = 0; i <= 3; i++)
{
Func<int> foo = (() => { return i; });
theActions.Add(foo);
}
}
[Test]
public void Should_reference_the_original_value_in_the_parent_scope()
{
//since the value of "i" in the original scope is now 4 (having gone through all of the loop's iterations)
//every value in the execution of the "foo" anonymous function will be 4
int expectedValue = 4;
int value0 = theActions[0]();
Assert.AreEqual(expectedValue, value0);
int value1 = theActions[1]();
Assert.AreEqual(expectedValue, value1);
int value2 = theActions[2]();
Assert.AreEqual(expectedValue, value2);
int value3 = theActions[3]();
Assert.AreEqual(expectedValue, value3);
}
}
[TestFixture]
public class When_passing_a_value_type_variable_from_the_parent_scope_to_a_method_called_by_a_closure : ContextSpecification
{
private readonly IList<Func<int>> theActions = new List<Func<int>>();
private void dooFoo(int value)
{
Func<int> foo = (() => { return value; });
theActions.Add(foo);
}
protected override void Context()
{
for (int i = 0; i <= 3; i++)
{
dooFoo(i);
}
}
[Test]
public void Should_create_a_copy_of_the_variable_and_retain_the_original_value()
{
//since we called a method, passing "i" from the original context into that method,
//the copied value was sent to the "foo" anonymous function, meaning that we got all
//of the numbers - 0, 1, 2, and 3 - in the anonymous "foo" functions.
int expectedValue = 0;
int value0 = theActions[0]();
Assert.AreEqual(expectedValue, value0);
expectedValue = 1;
int value1 = theActions[1]();
Assert.AreEqual(expectedValue, value1);
expectedValue = 2;
int value2 = theActions[2]();
Assert.AreEqual(expectedValue, value2);
expectedValue = 3;
int value3 = theActions[3]();
Assert.AreEqual(expectedValue, value3);
}
}
Illustrating The Closure Scope For Reference Types
It gets a little more interesting when dealing with reference types. The same basic statements can be made for reference types, but we have to remember that we’re now dealing with what are essentially pointers, not values. So, when a reference type variable gets copied, it still points to the same object on the heap. Thus, when dealing with reference types in closures, the scope of the variable that creates the reference type suddenly becomes much more important.
To illustrate the important of variable scope when dealing with closures, I’ve created some examples that scope a small reference type (class) in a few different ways. I’ll use this class definition as the reference type in all three examples.
public class SomeClass
{
}
Closure Of A Reference In Parent Scope
[TestFixture]
public class When_creating_a_closure_for_a_reference_that_is_part_of_the_parent_scope : ContextSpecification
{
SomeClass someClass;
private readonly IList<SomeClass> theValues = new List<SomeClass>();
private readonly IList<Func<SomeClass>> theClosureValues = new List<Func<SomeClass>>();
protected override void Context()
{
for (int i = 0; i <= 3; i++)
{
someClass = new SomeClass();
theValues.Add(someClass);
Func<SomeClass> foo = (() => { return someClass; });
theClosureValues.Add(foo);
}
}
[Test]
public void Then_all_closures_should_reference_the_last_instance_of_the_variable_from_the_parent_scope()
{
SomeClass expectedValue0 = theValues[0];
SomeClass value0 = theClosureValues[0]();
Assert.AreNotSame(expectedValue0, value0);
SomeClass expectedValue1 = theValues[1];
SomeClass value1 = theClosureValues[1]();
Assert.AreNotSame(expectedValue1, value1);
SomeClass expectedValue2 = theValues[2];
SomeClass value2 = theClosureValues[2]();
Assert.AreNotSame(expectedValue2, value2);
SomeClass expectedValue3 = theValues[3];
SomeClass value3 = theClosureValues[3]();
Assert.AreSame(expectedValue3, value3);
}
}
In this example, we’ve declared the “someClass” variable outside of the for-loop. This creates a variable that is scoped outside of the loop, and in this case outside of the Context() method. As long as this variable is scoped outside of the for-loop, we will only have a single variable to create our closure on. We see that the foo() anonymous method encloses someClass, causing it to stay in scope. What we don’t see, though, is that the foo() anonymous method will not be evaluated until the observations (just before the asserts) are executed. This means that every foo() method will have a reference to the same instance of “SomeClass”, not the individual instance that was created inside of the for-loop.
Closure Of A Reference That Is Scoped Within The Loop
[TestFixture]
public class When_creating_a_closure_for_a_reference_that_is_scoped_within_the_forloop: ContextSpecification
{
private readonly IList<SomeClass> theValues = new List<SomeClass>();
private readonly IList<Func<SomeClass>> theClosureValues = new List<Func<SomeClass>>();
protected override void Context()
{
for (int i = 0; i <= 3; i++)
{
SomeClass someClass = new SomeClass();
theValues.Add(someClass);
Func<SomeClass> foo = (() => { return someClass; });
theClosureValues.Add(foo);
}
}
[Test]
public void Then_all_closures_should_have_their_own_reference_from_the_loop_iteration()
{
SomeClass expectedValue0 = theValues[0];
SomeClass value0 = theClosureValues[0]();
Assert.AreSame(expectedValue0, value0);
SomeClass expectedValue1 = theValues[1];
SomeClass value1 = theClosureValues[1]();
Assert.AreSame(expectedValue1, value1);
SomeClass expectedValue2 = theValues[2];
SomeClass value2 = theClosureValues[2]();
Assert.AreSame(expectedValue2, value2);
SomeClass expectedValue3 = theValues[3];
SomeClass value3 = theClosureValues[3]();
Assert.AreSame(expectedValue3, value3);
}
}
In this example, we’ve declared the “someClass” variable inside of the for-loop, and is thus, in the local scope of the for-loop. Since the foo() anonymous method is creating a closure on a variable that is scoped to the for-loop, we can be assured that each foo() method will point to the “SomeClass” instance that was created in the for-loop. Our closure’s scope is now limited to the for-loop.
Closure Of A Reference Pointer Copy
[TestFixture]
public class When_creating_a_closure_for_a_copy_of_a_reference_pointer : ContextSpecification
{
SomeClass someClass;
private readonly IList<SomeClass> theValues = new List<SomeClass>();
private readonly IList<Func<SomeClass>> theClosureValues = new List<Func<SomeClass>>();
private void dooFoo(SomeClass value)
{
Func<SomeClass> foo = (() => { return value; });
theClosureValues.Add(foo);
}
protected override void Context()
{
for (int i = 0; i <= 3; i++)
{
someClass = new SomeClass();
theValues.Add(someClass);
dooFoo(someClass);
}
}
[Test]
public void Then_all_closures_should_have_their_own_reference_to_the_copied_reference_pointer()
{
SomeClass expectedValue0 = theValues[0];
SomeClass value0 = theClosureValues[0]();
Assert.AreSame(expectedValue0, value0);
SomeClass expectedValue1 = theValues[1];
SomeClass value1 = theClosureValues[1]();
Assert.AreSame(expectedValue1, value1);
SomeClass expectedValue2 = theValues[2];
SomeClass value2 = theClosureValues[2]();
Assert.AreSame(expectedValue2, value2);
SomeClass expectedValue3 = theValues[3];
SomeClass value3 = theClosureValues[3]();
Assert.AreSame(expectedValue3, value3);
}
}
In this last example, we can see that the “someClass” variable is again scoped outside of the Context() method. However, notice that we are now calling a “dooFoo()” method inside of the loop, instead of creating the closure locally. The effectively means that we are not creating a closure of “someClass” anymore. When someClass is passed into the dooFoo method, a copy of the reference is made – that is, we have a new variable with a new scope; this new variable just happens to be pointing to the same object as someClass, on the heap. Since we are now creating a closure around the “value” parameter of dooFoo, the scope of the closure has changed and acts the same as the closure of a reference in that is scoped with the loop. Each foo() anonymous method, with it’s closure, will now have it’s own instance of “value” to reference – the reference that was created in the scope of the for-loop, and then copied into the “value” parameter.
In “Closing” (pun intended )
It’s important to keep the scope of the variables in our closures in mind. If we scope our closures incorrectly, we can have some strange bugs in our system. Understanding the scope of your closures does require us to know a little bit of computer science, though – stack vs. heap, reference vs. value type – but that’s not a bad thing.
(If you see something wrong in my explanations or think my spec/observation names should be changed, let me know. I tried to make it clear, but am not sure that I did a good job.)
_________________________________ Cross Posted From LosTechies.com
In the comments of my previous post - Descriptive State Enumeration - Maxim Tihobrazov asked me to show how to map a state pattern with NHibernate; and I am more than happy to oblige! NHibernate Mapping Options I certainly don't claim to be an expert on NHibernate, but I do use it on a daily basis and I've solved my fair share of problems - including how to map a State pattern with NHibernate. According the NHibernate inheritance documentation, there are three core ways of mapping this pattern: - Table per class hierarchy (I've always called it "record per class") - each subclass (state instance, in this case) is associated with a specific record in a table. All of the subclasses are found in the same table.
- Table per subclass (also called a "joined sub class") - each sub class has it's own table and is joined to the super class by a one to one relationship with it's primary key.
- Table per concrete class - each sub class has it's own table and is mapped by the specific class type, not by the abstraction.
My Choice - Table Per Class Hierarchy In my current set of applications, I've always used the table per class hierarchy option so that is what I will describe here. My reasons for choosing this option are simplicity in the mapping and more importantly - not having a need to store the records in their own tables. Each of my states can be very cleanly represented as a record in my state table. Setting Up Shop Let's consider the same coffee shop that I've used in both of my PTOM posts - in this case, we're dealing specifically with the Order class and it's OrderStatus state. It's necessary to note that when I am working with NHibernate and the state pattern, I actually do set up my state models a little different. First off - we need an Id for NHibernate to map to the table's primary key. Secondly, I like to keep the core information in the abstract base class and provide all the varying values via a constructor. Third, each of the inheriting classes needs to provide a default (no args) constructor. Forth, we need a way for NHibernate to know which class it should actually instantiate, when loading - a "descriminator". I like to use a simple string Name property for this. And lastly - I think (though I am likely wrong on this aspect) that the abstract base class needs to provide a default constructor. Fortunately, the constructors we need don't need to be public - they can be private. With all of that being said, here is realistic code base that I would use for my Order and OrderStatus model: public class Order { public int Id { get; set; } public OrderStatus Status { get; set; }} public abstract class OrderStatus { public static InProcess = new InProcessStatus(); public static Totaled = new TotaledStatus(); public static Tendered = new TenderedStatus(); public static Delivered = new DeliveredStatus(); public int Id { get; set; } public bool DisplayForFullfillment { get; } public string Name { get; set; } private OrderStatus() { } private OrderStatus(int id, bool display, string name) { Id = id; DisplayForFullfillment = display; Name = name; } } public class InProcessStatus: OrderStatus { private InProcessStatus(): base(1, false, "InProcess"); } public class TotaledStatus: OrderStatus { private TotaledStatus(): base(2, true, "Totaled"); } public class TenderedStatus: OrderStatus { private TenderedStatus(): base(3, true, "Tendered"); } public class DeliveredStatus: OrderStatus { private DeliveredStatus(): base(4, false, "Delivered"); }
The Fluent NHibernate Maps
I'm a huge fan of Fluent NHibernate. I've been using it since just after it was branched from the original ShadeTree code. And at one point, I had submitted so many patches that I was made a comitter on the project. So, it should be no surprise to anyone that I'm going to advocate using FluentNHibernate over the .hbm.xml mapping files. Truth be told, I don't even remember how to do the needed descriminators in hbm.xml files. There was some trick to the descriminator being the first specified items after the Id or something... it's just easier to do in FluentNHibernate, so I don't bother with hbm.xml files anymore.
The Order map is going to be as standard as any other map. You don't need to do anything special here. Just map the Id of the Order and the referenced OrderStatus. (I like to add a "CreateMap()" method that is called from the constructor, so that I can avoid the "virtual method call from a constructor" warning. But I also use the "treat warnings as errors" option for my C# projects).
public class OrderMap: ClassMap<Order> { public OrderMap() { CreateMap(); } public void CreateMap() { DefaultAccess.AsProperty(); WithTable("Orders"); Id(o => o.Id).GeneratedBy.Assigned(); } }
It's really the OrderStatus map that is special in this case. This is where we get into the details of the descriminator - telling NHibernate which specific instance to create, when loading the data from the database. In our case, we have added a "Name" field to our OrderStatus object and we will be explicitly using this property as the descriminator.
public class OrderStatusMap: ClassMap<OrderStatus> { public OrderStatusMap() { CreateMap(); } public void CreateMap() { DefaultAccess.AsProperty(); WithTable("OrderStates"); Id(s => s.Id).GeneratedBy.Assigned(); DiscriminateSubClassesOnColumn<string>("Name") .SubClass<InProcessStatus>() .IsIdentifiedBy(OrderStatus.InProcess.Name) .MapSubClassColumns(x => { }) .SubClass<TotaledStatus>() .IsIdentifiedBy(OrderStatus.Totaled.Name) .MapSubClassColumns(x => { }) .SubClass<TenderedStatus>() .IsIdentifiedBy(OrderStatus.Tendered.Name) .MapSubClassColumns(x => { }) .SubClass<DeliveredStatus>() .IsIdentifiedBy(OrderStatus.Delivered.Name) .MapSubClassColumns(x => { }) Map(s => s.Name); } }
The key to all of this is the DescriminateSubClassesOnColumn method. The generics <string> tells us what .NET Type is being used to identify the specific class instances that we are dealing with and the ("Name") parameter is the column name in the database that represents the specific instance.
Then, we have the specific class instances referenced by the ".Subclass<type>" calls. This is a fluent interface, so ".Subclass" is a method that gets called directly off the DescriminatoeSubClassesOnColumn method. The specific type we want NHibernate to know about is specified in the generics parameter: ".SubClass<InProcessStatus>". The "IsIdentifiedBy" is where we give NHibernate the knowledge of what value in the "Name" column maps to what specific class in our code. To prevent magic string syndrome from setting in, I like to use the actual enumeration pattern of my OrderStatus to specify the string name of the class.
And finally, we have to provide an ugly workaround for our maps via the "MapSubclassColumns" method. There is an implementation issue in FluentNHibernate currently, and because of this issue we are forced to call the "MapSubclassColumns" method, with an empty lambda expression. If we don't call this method, the sub class will not get registered and NHibernate will not know how to handle the data in question. (I am hoping to fix this issue at some time, and make it so we don't have to call that method. I just haven't had time recently.)
Wrapping Up The Map
The rest of the map (the one remaining "name" property being mapped, in this case) is a regular NHibernate map. You'll notice, though, that we never mapped the "DispalyForFullfillment" property. I explicitly choose to leave any and all "volatile" properties out of my state maps. By doing this, I am able to add, edit, and remove any properties or methods on the state objects that I need, without having to change the NHibernate mappings. Since the state objects I am dealing with don't change without recompiling the code anyway, I don't need the ability to define them in the database. However, if you do need or want the flexibility of defining your states in the database, you can map each individual property of the state. Just remember that you will have to modify both the code and the database, to make the changes complete.
I hope this quick look at mapping a state pattern with Fluent NHibernate will help to shed some light on the subject, for someone. I realize that I have only provided the FluentNHibernate mapping, though. I specifically chose to do this because it would be a serious chore for myself to create a code project with NHibernate set up so that I can actually verify my mapping xml is correct. However, the translation from FluentNHibernate back to standard .hbm.xml files should be fairly straightforward, with the help of the NHibernate Documentation. If anyone out there is willing to help out and send me the correct .hbm.xml mapping, I would be more than happy to add it to this post and credit you with the work.
_________________________________ Cross Posted From LostTechies.com
A coworker recently asked if we should always abstract every object into an interface in order to fulfill the Dependency Inversion Principle (DIP). The question stunned me at first, honestly. I knew in my head that this was a bad idea - abstracting into interfaces for the sake of abstraction leads down the path of needless complexity. However, I wasn't able to clearly answer his question with specific examples of when you would not want to do this, at the time. I've been thinking about this for a few days now and I think I have a good, albeit very long winded, answer. Before the question is answered, though, we need to step back and look at what DIP is all about. I've previously shown how to implement DIP and talked about why it's beneficial, so I won't be repeating that here. Rather, I want to talk about the language that describes DIP and what it really means. Robert Martin's original definition of DIP is this: A. High level modules should not depend upon low level modules. Both should depend upon abstractions. B. Abstractions should not depend upon details. Details should depend upon abstractions. The word 'abstraction' is used three times in the definition for DIP. So, in order to understand DIP, we have to first understand some of the basics of Abstraction. Some Background On Abstraction From Wikipedia (emphasis mine): "In computer science, abstraction is a mechanism and practice to reduce and factor out details so that one can focus on a few concepts at a time" I can't say it any better than this. Abstraction can very directly lead to a system that is more understandable by helping us ignore the detail and implementation specifics, allowing us to focus on something at a higher level. This reduction in cognitive load can benefit someone that is reading the code by not forcing them to know the detail immediately. Additionally, abstraction is a form of encapsulation or information hiding, which again helps us to reduce cognitive load and produce better systems. From Wikipedia's entry on Information Hiding: "In computer science, the principle of information hiding is the hiding of design decisions in a computer program that are most likely to change, thus protecting other parts of the program from change if the design decision is changed." At the heart of abstraction and information hiding, we find the ability to change the system. The ability to change is an absolute requirement in software development and produces good design that is easier to work with, modify, and put back together as needed. The inability to change is directly called "bad design" by Robert Martin, in the DIP article. Applying Abstraction And Encapsulation To DIP So how does our knowledge of abstraction and information hiding play into DIP? First and foremost, DIP never states that we should depend on explicit interfaces. Yes, in C# we have an explicit Interface as a form of abstraction. It is a separation of the implementation detail from the publicly available methods, properties, etc, of a class. Some languages, such as C++, don't have an explicit construct for interfaces, though. From Robert Martin's original DIP article, again: "In C++ however, there is no separation between interface and implementation. Rather, in C++, the separation is between the definition of the class and the definition of its member functions." A String As An Abstraction Abstraction does always mean explicit interface constructs, as evidenced in C++. Nor does it always mean an abstract base class, which we also have available in .NET. In fact, languages such as Ruby don't really need either of these constructs. The duck-type nature of Ruby allows an implementation to be replaced at any point, without any special constructs. In .NET, though, there are a number of abstraction forms that we can rely on, explicitly. We have the obvious interfaces and base classes (abstract or not) - but we also have constructs like delegates and lambda expressions, and even the simple types that are built into the base class library. Let's look at a simple string to illustrate abstraction. As I said in my SOLID presentation at ADNUG, we can invert our dependency on database connection information. Rather than putting a connection string directly into our code that calls the database, we can use the string as our dependency and our abstraction. All we need to do is follow the basic DIP principle and provide the string as a parameter to the class that calls the database. We certainly don't need (or want, for that matter) to introduce a new interface or base class at this point. Our abstraction is simple enough to use a common type found in the .NET framework. Other Forms Of Abstraction Even if we are talking about an object, who says that the interface we are depending on has to be an explicit interface construct or base class? When I write a Domain Service that uses an Entity from my Domain, I don't create an explicit interface for that Entity. Rather, I use the Entity's inherent interface - it's public methods, properties, etc. I also use delegates on a regular basis. By specifying my abstraction as a delegate, I can further decouple the depending object from the dependant code that it needs to call. I'd be willing to bet you have used delegates as abstractions as well. Have you ever created an event handler for something like a button click? There's a delegate's abstraction at work. Abstract Judgement The point is, there is not always a need to introduce an explicit interface or base class when inverting our dependencies. We still need to apply dependency inversion and provide our implementation as a constructor parameter (or setter, though I don't like setter injection). But, that dependency doesn't have to be anything more than the interface inherent to the object, or a simple type found in .NET. You do have to be careful when making the call to not use an explicit abstraction with DIP, though. You can quickly turn your system into a ball of mud if you rely on a concrete class that is not intention revealing or well encapsulated to begin with. At the same time, too many abstractions can lead to needless complexity and make it very difficult to see the big picture of a system. Too few abstractions, though, will certainly lead to a rigid, immobile design that is hard to change. All of these problems are equally vicious - and I've been bitten by all of them in recent months. It takes good judgement calls to determine when you do and do not need an explicit abstraction for a dependency. Unfortunately, good judgement comes from experience and experience comes from bad judgement. Don't be afraid to make bad decisions - make a decision, just be sure you can reverse that decision as easily as possible.
At some point, you will need to put a timer into your C# code. Hopefully you're doing Test Driven Development, or at least unit testing, to cover your need for a timer with a unit test. If you are - I'm betting you ran into some really ugly problems like tests that would not pass without having 'Thread.Sleep(1000)' calls in them. Worse yet - last week, I put a 3 second timer into a class that was being unit tested. This one mistake cause my CruiseControl build to go from 2 minutes, to timing out at 90 minutes because NUnit was keeping the app domain alive while the timer was alive, so it never closed the test run. Oops. To fix this problem, we decided we needed to eliminate the use of an actual timer and use an abstraction that could be mocked/controlled in our unit tests. Unfortunately, the .NET Framework does not have an actual abstraction for a timer. So, if you need to use a timer in your code - and at some point in time, you will - you'll want to create a very simple ITimer interface that would let you control when the timer elapses and fires its registered action. Here's the core of the abstraction that we came up with, initially. public interface ITimer { void Start(Action timerAction); }
With such a simple interface in place, we can now mock it out in our unit tests (I like Rhino Mocks) and set up an expectation on the Start method to capture the timerAction parameter, then simulate the timer elapsing by calling the timer action from our unit test. Here's an example test and 'system under test' to illustrate how we use this interface.
[Test] public void DemonstratingHowToUnitTestATimerElapsing() { Action timerElaspedAction; ITimer timer = MockRepository.GenerateMock<ITimer>(); timer.Expect(t => t.Start(null)).IgnoreArguments().Callback( delegate(Action timerAction) { timerElapsedAction = timerAction; return true; }); MySystemUnderTest sut = new MySystemUnderTest(); sut.StartMonitoringStuff(timer); //here's where we simulate the timer elapsing timerElapsedAction(); Assert.IsTrue(sut.TheTimerActionWasCalled); } public class MySystemUnderTest() { public bool TheTimerActionWasCalled { get; set; } public MySystemUnderTest() { TheTimerActionWasCalled = false; } public StartMonitoringStuff(ITimer timer) { timer.Start(() => TheTimerActionWasCalled = true); } }
There is a bit more detail to the actual ITimer interface, and the implementation, though. We ran into issues where we needed to stop the timer, prevent it from firing after we close the SUT, etc. So, all said and done, here's the full ITimer interface and MyTimer implementation that we ended up with.
public interface ITimer { void Start(Action action); void Stop(); } public class MyTimer : ITimer, IDisposable { private TimeSpan _timerInterval; private Timer _timer; private Action _timerAction; private bool IsRunning { get; set; } public MyTimer(TimeSpan timerInterval) { _timerInterval = timerInterval; } public void Dispose() { StopTimer(); } public void Start(Action action) { _timerAction = action; IsRunning = true; StartTimer(); } public void Stop() { IsRunning = false; StopTimer(); } private void StartTimer() { _timer = new Timer(o => Timer_Execute(), null, 0, Convert.ToInt32(_timerInterval.TotalMilliseconds)); } private void StopTimer() { if (_timer != null) { _timer.Change(Timeout.Infinite, Timeout.Infinite); _timer.Dispose(); _timer = null; } } private void Timer_Execute() { try { StopTimer(); _timerAction(); } finally { if (IsRunning) StartTimer(); } } }
This has worked out very well for us, so far. It lets us put a timer in place when we need one, but not worry about thread racing issues, long running tests, etc.
In the last month or two, I have been hand coding a lot of mock and stub objects and it has become a nightmare to manage. My primary reason for doing this by hand was that Rhino Mocks 3.4 and older did not fit with the BDD style unit tests that I was writing. Yes, I made it work in a few places, but it was ugly and annoying. Fortunately, Ayende has cleaned it all up with the new syntax and made it very easy to assert that individual expectations were met, with v3.5. I finally got around to trying out the new syntax today, and I immediately fell in love with it. For example: [Concern("User Administration")]public class When_accessing_the_system_as_a_non_administrator : ContextSpecification { private IMainView view; private IMainView GetView() { IMainView mockView = MockRepository.GenerateMock<IMainView>(); mockView.Expect(v => v.EnableUserManagement()).Repeat.Never(); mockView.Expect(v => v.DisableUserManagement()).Repeat.Once(); return mockView; } protected override void Context() { User administrator = new User(); administrator.IsAdministrator = false; CurrentUser.User = administrator; view = GetView(); new MainPresenter(view); } [Observation] public void Should_not_display_the_User_Management_option() { view.AssertWasNotCalled(v => v.EnableUserManagement()); } [Observation] public void Should_hide_the_user_management_option() { view.AssertWasCalled(v => v.DisableUserManagement()); } }
In the "GetView" method, I am setting up two very distinct expectations on my mock object.
- Never Call the EnableUserManagement method.
- Call the DisableUserManagement method once.
With the new Rhino Mocks syntax, I can easily verify that each one of these expectations was called via my "should" observations.
The "AssertWasNotCalled" extension method verifies that an expectation of Repeat.Never was setup and that the method was not called.
mockView.AssertWasNotCalled(v => v.EnableUserManagement());
And the "AssertWasCalled" extension method verifies that the expectation was to call the method, and that the method actually was called.
mockView.AssertWasCalled(v => v.DisableUserManagement());
I like it. The new syntax has really simplified my Context Specification testing.
Over the weekend, I spent some time refactoring some business rules in my current project, to use the ISpecification<t> framework that I previously created. One of my coworkers had asked about logical groupings - making sure that we can handle complex logic such as, "(this and this) or this". Since my project actually made use of logical groupings I wanted to share with the world and show how easy it is. In this example, I have a Date Range that is being selected – a From date and a To date. The rules are as follows for validating the range: - If a From date and a To date are provided, the From date must be equal to, or before, the To date
- Or, you can specify a From date without To date
- Or, you can specify a To date without From date
The following is the actual code that I’m using to define these business rules, via the ISpecification<t> framework. PredicateSpec<ExtractSearchCriteria> fromDateProvided = new PredicateSpec<ExtractSearchCriteria>(crit => crit.FromDate > DateTime.MinValue); PredicateSpec<ExtractSearchCriteria> toDateProvided = new PredicateSpec<ExtractSearchCriteria>(crit => crit.ToDate > DateTime.MinValue); PredicateSpec<ExtractSearchCriteria> fromDateBeforeToDate = new PredicateSpec<ExtractSearchCriteria>(crit => crit.FromDate <= crit.ToDate); ISpecification<ExtractSearchCriteria> validDateRangeSpec = ( (fromDateProvided.And(toDateProvided)) .And(fromDateBeforeToDate) ) .Or( fromDateProvided.Not(toDateProvided) ) .Or( toDateProvided.Not(fromDateProvided) );
Here, I am defining the core of the business rules – to check if the From date was provided, to check if the To date was provided, and to check if the From date is before or equal to the To date. From these core specifications, I can build the aggregate spec that handles all of the stated rules for validating the date range.
There are three logical groupings using parenthesis to represent each of the business rules that can comprise a valid date range. The first logical grouping checks to see if both a From and To date are provided, and checks if the From date is before or equal to the To date, if both are provided.
( (fromDateProvided.And(toDateProvided)) .And(fromDateBeforeToDate) )
The second group is specified with an Or, and checks to see if we provided a From date but not a To date.
.Or( fromDateProvided.Not(toDateProvided) )
And the third group also uses an Or, and checks to see if we provided a To date but not a From date.
.Or( toDateProvided.Not(fromDateProvided) )
The end result is that we have one of three possible ways for this date range to be valid – all logically grouped and relatively easy to read (compared to a bunch of if-then statements, at least). Even better – we re-used two out of three simple ISpecification<t> objects to create all of the rules for this validation check. This helps to create a validation that is not only easier to read, but easier to maintain and enhance in the future.
Inspired by my recent readings in Domain Driven Design - specifically Chapter 10, "Supple Design" - and recent posts by David Laribee and Nigel Sampson, in combination with the recent pains I've been putting myself through, trying to test query generation code in a search screen, I decided to spike out a quick example of a reusable Specification implementation. Rather than repeat what's already been said, I'm just going to get straight to the code. using System; namespace Spec_Spike { class Program { static void Main() { Foo foo1 = new Foo(); foo1.Bar = "Test"; ISpecification<Foo> equalSpec = new Specification<Foo>(foo => foo.Bar == "Test"); ISpecification<Foo> notEqualSpec = new Specification<Foo>(foo => foo.Bar != "Not Equal To This Text"); ISpecification<Foo> falseSpec = new Specification<Foo>(foo => false); ISpecification<Foo> passingSpec = equalSpec.And(notEqualSpec); ISpecification<Foo> failingSpec = passingSpec.And(falseSpec); Console.WriteLine(equalSpec.IsSatisfiedBy(foo1)); Console.WriteLine(notEqualSpec.IsSatisfiedBy(foo1)); Console.WriteLine(passingSpec.IsSatisfiedBy(foo1)); Console.WriteLine(failingSpec.IsSatisfiedBy(foo1)); } } public class Foo { public string Bar; } public interface ISpecification<t> { bool IsSatisfiedBy(t obj); ISpecification<t> And(ISpecification<t> lhs); } public class Specification<t>: ISpecification<t> { private readonly Predicate<t> _pred; public Specification(Predicate<t> pred) { _pred = pred; } protected Specification(){} public virtual bool IsSatisfiedBy(t obj) { return _pred(obj); } public ISpecification<t> And(ISpecification<t> andSpec) { return new AndSpecification<t>(this, andSpec); } } public class AndSpecification<t>: Specification<t> { private readonly ISpecification<t> _spec1; private readonly ISpecification<t> _spec; public AndSpecification(ISpecification<t> spec1, ISpecification<t> spec) { _spec1 = spec1; _spec = spec; } public override bool IsSatisfiedBy(t obj) { return (_spec.IsSatisfiedBy(obj) && _spec1.IsSatisfiedBy(obj)); } } }
Drop this code into a console app in C# 3.5 and watch the magic happen. Here's the output:
These are the results that I expected - the first 2 individual specs passed, the first combined spec passed, and the last combined spec failed.
Overall, I'm fairly excited about the possibilities here. I'm thinking that I may actually be able to properly unit test the query generating code in my search screen with this basic technique. I'm still not 100% sure on that, but I plan on trying, anyway.
For more information on the Specification pattern, I highly recommend you read the previously linked posts by David Laribee and Nigel Sampson, in addition to reading all of the Domain Driven Design Book. This is one of those books that should fundamentally change the way you think about software development.
I've been toying around with various ideas in code, and I've come to the conclusion that the following formula is true: Lambda Expressions + Func<> and Action<> = Easy Command Patterns As a very contrived, quick example: public class DoStuff { private Func<CommandResult> Step1 { get; set; } private Func<CommandResult> Step2 { get; set; } public DoStuff(Func<CommandResult> step1, Func<CommandResult> step2) { Step1 = step1; Step2 = step2; } public void DoTheStuffProcessing() { CommandResult result = step1(); if (result.Succeeded) { step2(); } } }
It's ... so ... beautiful ... 
I hate the Try Catch syntax in C# - it's bulky, ugly, and makes my code hard to read. try { // do some stuff here } catch { //handle exceptions here } finally { //clean up here }
Although very functional and well documented, to the point where it can be effectively used, I don't see the elegance that I want in my language - especially if you actually have to catch a specific exception and deal with it in the middle of your functional code.
So, I'll create the elegance that I want.
public class TryCatch { public static Exception Do(Action action) { Exception caughtException = null; try { action(); } catch(Exception ex) { caughtException = ex; } return caughtException; } }
With this very basic implementation, using lambda expressions, I can create a much more friendly syntax to use:
Exception ex = TryCatch.Do(() => { //Do Stuff Here, with assurance that an exception will be caught, if thrown. }); //send the exception off to the exception processing / handling, if needed.
From there, you could add a "fluent" interface to catch specific exceptions, have a finally block, etc - but you end up with the same ugliness that I wanted to avoid.
//Blech. This just puts us right back in ugly-ville TryCatch.Do(() => { //throw exception here }).Catch<Exception>(() => { //handle exception here });
ugh - ugly, for that matter. That didn't help us at all. And we don't need it, anyway. You are guaranteed to have the before and after TryCatch.Do execute.
//setup IDBConnection conn = GetMyConnection(); TryCatch.Do(() => { //execute conn.Open(); }); //cleanup if (conn != null) conn.Dispose();
I like it.
|