var blog = new ThoughtStream(me); RSS 2.0
 Monday, February 23, 2009

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
Monday, February 23, 2009 4:10:39 PM (Central Standard Time, UTC-06:00)  #    Comments [0]. Trackback 
Tags: .NET | C# | Lambda Expressions | Principles and Patterns

 Thursday, February 19, 2009

I have a service object with an interface explicitly defined for it. I like this because it let’s me unit test the things that need the service without having to worry about the implementation detail of the actual service.

public interface IMyService
{
  public void DoSomething();
  public void AnotherThingHere();
}

When I get to the implementation of this service and I start specifying the behavior through my specification/tests, I create a class that has a dependency on another interface – ISomeRepository. This repository is used in both methods of the actual service implementation.

For the “AnotherThingHere” method, I end up with several specification/tests because that method has some good business logic in it.

For the “DoSomething” method, though, the real implementation is only a pass-through to the repository and my specification/test ends up looking like this:

[TestFixture]
public class When_doing_something: ContextSpecification
{
 
 ISomeRepository repo;
 
 public override void Context()
 {
   repo = MockRepository.GenerateMock<ISomeRepository>();
   IMyService myService = new MyService(repo);
 
   myService.DoSomething();
 }
 
 [Test]
 public void Should_do_something()
 {
   repo.AssertWasCalled(r => r.DoSomething());
 }
 
}

I know this specification is necessary because I am using the “DoSomething” method of IMyService in other parts of the system. I think there is value in having an IMyService interface explicitly because it simplified the specification/tests for the parts of the system that need to use it, and decoupled the system to a point that made it much easier to code and change.

So my question is, do you see any real value in a specification/test name like “When doing something, should do something”? or should I be looking at this test from a different “style” or perspective?

I think this specification/test is valuable, but I also think the test name and observation name are silly since they say the same thing. Advice? Different naming suggestions? What am I missing or just not seeing? or is this ok and I’m just running on 25% brain power due to lack of sleep today?



_________________________________
Cross Posted From LosTechies.com
Thursday, February 19, 2009 7:01:19 PM (Central Standard Time, UTC-06:00)  #    Comments [0]. Trackback 
Tags: .NET | Behavior Driven Development | C# | Unit Testing

 Sunday, February 15, 2009

Update: There’s a wealth of knowledge out there that I just haven’t been aware of until now. Thanks to the many commenters of this post, other posts, and other conversations for the links and info. Here is a list of items that I’m finding to be very helpful in understanding what is only a surface level “validation” problem:

Update 3/3/2009 – additional info in the continuing conversation.

Update 3/11/2009

 

There’s a whole host of stuff out there linked from these articles and posts, as well. It’s obvious now that I have a lot to learn and think about, and I think I have a better sense of where I need to start looking. I also think that the ideas Sean Biefeld expressed about never letting an entity be in an invalid state are more reachable than I previously thought.

----------------------------------

This post started as a comment in Sean’s post on Entity Validation Ideation but quickly grew. I’m hesitant to post separately because I believe the conversation should continue along the lines of what he was originally saying. There’s just so much junk tossing around in my head, though, I didn’t think it would be appropriate to post a 50 page diatribe in a comment.

 

A while back, I asked the question “Where does required info validation belong for an entity?” There were a lot of good answers to that question and my team and I took some very interesting directions based on those answers. However, I still haven’t had the ‘validation’ question completely answered in my mind. Fortunately, I’ve got the brains of my fellow Los Techies (and coworker in this case), to keep me from giving in to the entropy that wants to keep me mediocre.

I love the theory that Sean is talking about - especially when stated as 'proactive' vs 'reactive'. I've had a hard time with this in practice, though. In the last few weeks – days, really - it seems to me that we need to have both proactive and reactive validation in our applications.

Being Proactive

The domain model that I create wants to prevent an object from being invalid, so I require a minimum set of information in my constructors, etc etc. This helps me prevent an object from ever being created in an invalid state. this is the proactive approach. I love this approach and I use it a lot.

Oh Wait, I Need Reactive

The proactive recently failed me, though. I had ‘the perfect’ domain model with the all the validation and rules composed in my entities, preventing the information from being added to the model if it was not valid. However, when I got to the user interface, I realized that I had a major design problem. The user interface is not 'all or nothing' scenario. The user is allowed (expected, really) to only provide one field of information at a time. After all, you can't type into more than one text box at a time - unless you have multiple keyboards and multi-input capable systems. So, when a user is adding information to the inputs of the form, we need to have a reactive approach. We need to provide real time validation of what the user is putting into the system, so that they can be immediately notified of any errors in what they are providing. This reactive approach is needed because the user interface is entirely reactive to the user's actions.

Proactive AND Reactive?

At the same time that we need both a proactive and a reactive solution, we want to adhere to the "Don't Repeat Yourself" principle, encapsulating the validation logic into the appropriate location(s). If we require reactive validation in the user interface, and proactive validation in the domain model, how do we avoid breaking DRY?

On the surface, proactive and reactive validation seem to be at odds with each other – at least, they do in my mind. I don't think they need to be, or should be, though. We just need to find the higher level order in which we can enable both. Unfortunately, I haven't been able to do this yet – at least not in a way that really seems to satisfy me. I'm curious to know how others approach this situation. How do we balance this triad of need: Proactive, Reactive, and DRY?

I need some fresh perspectives on this, and I think Sean is starting out with some great ideas. Now if I can just learn to throw away my own bias to how I’ve already been handling this, maybe I’ll be able to learn something.



_________________________________
Cross Posted From LosTechies.com
Sunday, February 15, 2009 3:49:55 PM (Central Standard Time, UTC-06:00)  #    Comments [0]. Trackback 
Tags: .NET | C# | Domain Driven Design | Principles and Patterns

 Thursday, February 05, 2009

I’ve written a lot of specification tests like this in the last three years, from a UI / Workflow perspective, with Model-View-Presenter as my core UI architecture:

[TestFixture]
public class When_starting_some_process()
{
 
 IMyView view;
 MyPresenter presenter;
 
 [Setup]
 public void Setup()
 {
   //...setup code and execute stuff for the test here
   view = MockRepository.GenerateMock<IMyView>();
   presenter = new MyPresenter(view);
 
   presenter.StartSomeProcess();
 } 
 
 [Test]
 public void Should_attach_the_view_to_the_presenter()
 {
   presenter.View.ShouldNotBeNull();
 }
 
 [Test]
 public void Should_show_something()
 {
   view.AssertWasCalled(v => v.ShowSomething(something));
 }
 
}

The Devil In These Details

I had one of those ‘aha!’ moments yesterday where several of my nagging suspicions and annoyances at writing specification tests like this example finally gelled into a coherent understanding. That understanding is easily stated by saying that the test, “Should_attach_the_view_to_the_presenter” is invalid and should never be written. There are a number of reasons for this.

  1. In practicing BDD, the technical jargon that is leaking into the test is irrelevant to the real value that is intended with this specification
  2. In practicing any form of TDD, the implementation detail of attaching a view to a presenter creates a brittle test – I care about the API and how the system really works, not a very technical, implementation detail like this.
  3. Exposing the “View” property of the Presenter object is a violation of encapsulation and an ‘over-intimate’ smell. My test has far too much fine detail, granular knowledge of what’s going on behind the scenes, to really be of any practical value
  4. Finally – and possibly outweighing all other reasons combined – it’s simply not necessary.

Look at the second test: “Should_show_something”. It’s actually using the view. Presumably, the “StartSomeProcess” method on the presenter is going to call a method on the view – that’s why we are asserting that the method on the view was called. If this is true, then it can be safely assumed that not having a view attached to the presenter would throw a null reference exception when trying to call that method on the view.

If not having the view attached to the presenter results in a null reference exception for the other test, then we have a valid reason for that test to fail. We certainly can’t say that the view’s method was called when the view is null. Therefore, testing to ensure that we have a view attached to the presenter is a duplication of effort. We’re only proving what we have already proved transitively, via another test.

Beauty And Meaning In Simplicity

Assuming that this is all true, we can remove that test entirely. Our specification now looks like this:

[TestFixture]
public class When_starting_some_process()
{
 
 IMyView view;
 MyPresenter presenter;
 
 [Setup]
 public void Setup()
 {
   //...setup code and execute stuff for the test here
   view = MockRepository.GenerateMock<IMyView>();
   presenter = new MyPresenter(view);
 
   presenter.StartSomeProcess();
 }
 
 [Test]
 public void Should_show_something()
 {
   view.AssertWasCalled(v => v.ShowSomething(something));
 }
 
}

It’s one less test to deal with, yet is as expressive and meaningful. In fact, I would say it is more meaningful because we have avoided all of the problems I listed. I’m reminded of a quote by Alan Cooper:

“No matter how beautiful, no matter how cool your interface, it would be better if there were less of it.”

Although I think he was specifically addressing User interfaces in this quote, it is applicable to all interfaces – programmatic, user, etc. Simplicity and subtleness is the key. I know I’m not the first person to talk about this problem, why it’s a problem, or the solution. I’m only claiming that I finally had that ‘aha!’ moment and realized why so many others have talked about this before.



_________________________________
Cross Posted From LostTechies.com
Thursday, February 05, 2009 5:16:48 PM (Central Standard Time, UTC-06:00)  #    Comments [0]. Trackback 
Tags: .NET | Analysis and Design | Behavior Driven Development | C# | Model-View-Presenter | Principles and Patterns | Unit Testing

 Tuesday, February 03, 2009

Wow! I’m actually writing code!

I thought this little snippet would be useful for anyone that is binding a custom collection of objects to a Telerik MultiColumnComboBox. If you want to get the selected item as your actual class – the custom class that you wrote and bound as a collection to the list, you can use this basic code:

private void MyComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
   GridViewDataRowInfo rowInfo = MyComboBox.SelectedItem as GridViewDataRowInfo;
   if (rowInfo != null)
   {
       MyClass myClass = rowInfo.DataBoundItem as MyClass;
       //do something with the 'myClass' variable, here.
   }
}

Hopefully this will save someone else some time in the debugger trying to figure out why ‘SelectedItem’ is not coming back as the class instance that was selected.

_________________________________
Cross Posted From LostTechies.com
Tuesday, February 03, 2009 5:28:48 PM (Central Standard Time, UTC-06:00)  #    Comments [0]. Trackback 
Tags: .NET | C# | Telerik

Navigation
About Me
View Derick Bailey's profile on LinkedIn

Send mail to the author(s) Contact Me
Archive
<September 2010>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Derick Bailey
Sign In
Statistics
Total Posts: 115
This Year: 0
This Month: 0
This Week: 0
Comments: 44
Themes
Pick a theme:
All Content © 2010, Derick Bailey
DasBlog theme 'Business' created by Christoph De Baene (delarou)