Boy Meets 'Hello World'

Blogging the journey from College Grad to .NET Developer

  Home  |   Contact  |   Syndication    |   Login
  11 Posts | 0 Stories | 4 Comments | 0 Trackbacks

News

Archives

Post Categories

Wednesday, June 25, 2008 #

I've been working on a WPF program (which once again, as expected, justified my belief that I will never find enjoyment in programming any UI)...

Luckily, my program is just one-way... it is used for reporting, no input needed here besides just moving around. So, I implemented most of it in labels. Later I realized, however, that some of these labels have contents that a user of the program might want to copy and paste in another program. By default, you cannot highlight text on WPF labels, and I couldn't find any properties that changes this behavior.

Here is how I went about it, taking a TextBox and styling it until it looks like a label.

<Style x:Key="FauxLabel" TargetType="{x:Type TextBox}">
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="BorderBrush" Value="{x:Null}"/>
    <Setter Property="BorderThickness" Value="4"/>
    <Setter Property="IsTabStop" Value="False"/>
</Style>

You need to be careful of is if you're data binding these FauxLabel's to read-only properties. I think that TextBox's have a different default binding mode, which will cause an InvalidOperationException is you try to bind it against a read-only property...

InvalidOperationException:
A TwoWay or OneWayToSource binding cannot work on the read-only property 'StartTime' of type 'MyDataObject'.

So, my full change from label->text box is as follows...

<Label Content="{Binding StartTime}"/>
...
<TextBox Text="{Binding StartTime, Mode=OneWay}"/>

Of course, you will need to also include the style if you're not using it by default (I'm making a new style that is based off the FauxLabel style and using that as default).

There might be other nuances I've missed, but this works for me.


Monday, June 23, 2008 #

Jonathan Starr joined in the "to var or not to var" discussion that occurred recently with his post "Code Redundancy Is NOT Necessarily Bad". No, I'm not jumping into the ring with this whole var thing. Not much anyway. Ok, maybe a bit at the end, it's all Jon's fault, the text box on his comment section is too small, so I made a post instead, and that lead to me thinking harder about the subject, and things kinda' just took off from there :P

In his first post, which I've linked to, he declared:

 

Say I have a class named Example that implements two interfaces, IFoo and IBar.  When I instantiate I have several options when dong so statically.

Example example1 = new Example();
IFoo example2 = new Example();
IBar example3 = new Example();

In the second case I am ensuring that example2 implements a certain interface, and I can swap this out with an instantiation of a different object that implements IFoo.  This strategy pattern is fundamental to object oriented programming, and 'getting in the habit of writing code using var' can provide inflexible suboptimal design.  Additionally, if you are coding using TDD (Test Driven Development) you won't be able to write unit tests that remove all dependencies for your class unless you write your dependencies as interfaces.

I asked about the comment regarding how you "won't be able to write unit tests". Whether in response to myself, or the other commenter, or both, he made his second post (Code Redundancy is NOT Bad - Part 2), where he said:

If the method PartitionMerchants had been written using class declarations instead of interfaces, than any test I would write for this method would be an integration test, not a unit test...  Because the failure could be in one of the dependent classes, not in the class that is under test in my unit test!

This is why I was confused with his assertion. The difference between a unit test and an integration test is not whether you are using interfaces are not, but whether you are testing the smallest "unit" of code or the interaction of multiple "units" of code. If you couldn't mock class methods, then he would be right, since you would have no alternative other than to have the unit of code that you are testing also be interacting with another unit of code that you're not. But, we can mock class methods, and without needing to make an interface wrapper.

To do this, you would make a subclass of the class in question, which will be used as your mock (fake, double, whatever) and override the method you wish to mock with your implementation. Since frameworks like Rhino.Mocks and Moq use DynamicProxy, they too rely on subclassing the class to mock. This all means that the class you wish to mock will need to have those methods you wish to mock marked as virtual to correctly override them. In addition, you should probably allow for a protected parameterless constructor (if a public one is not available) just so that you don't have to rely on passing in dependencies to your mock object (which these frameworks include abilities to do, but honestly I can't even imagine a scenario where this would be preferred to refactoring). Since I wouldn't mind seeing all methods being marked as virtual by default anyway, I have no qualms with it.

Not that I'm disagreeing with the whole coding to an interface. Actually, I thought that I had stopped doing this myself, so I dug up my code from the last few days so I could show Jon an example of where it might be ok to just use a class and refactor to an interface when necessary, but I couldn't find one because I had been coding to interfaces the whole time without really even noticing it. I think that's a good thing :)

Ok, I said I wasn't going to join the fight, but just had a few comments to make on Jon's example. I wasn't following the whole var discussion, so my apologies if any of this has already been said.

Jon starts by creating an object three times, and shows that because he doesn't use var he can instead explicitly set the type to an interface, which he can now "swap out". Then he goes on to say that

This strategy pattern is fundamental to object oriented programming, and 'getting in the habit of writing code using var' can provide inflexible suboptimal design.

To me, what he appears to be saying was that you can do this...

   1:  public interface Notification
   2:  {
   3:      void Run();
   4:  }
   5:   
   6:  public class FirstNotification : Notification
   7:  {
   8:      public void Run()
   9:      {
  10:          Console.WriteLine("First");
  11:      }
  12:  }
  13:   
  14:  public class SecondNotification: Notification
  15:  {
  16:      public void Run()
  17:      {
  18:          Console.WriteLine("Second");
  19:      }
  20:  }
  21:   
  22:  public class Service
  23:  {
  24:      public void DoStuff()
  25:      {
  26:          Notification firstExample = new FirstNotification();
  27:          firstExample = new SecondNotification();
  28:      }
  29:  }

 

First off, let's just imagine that I'm using factories to create stuff, so that no one can gripe about the inherit untestability of the code and miss the point.

Because we used Notification instead of var on line 26, we can now "swap out" on line 27, whereas the var would create an error message. This is not the strategy pattern. The strategy pattern would be about if I were to later use the the instance in another method which took Notification as a parameter. I could pass in whatever notification strategy I wanted to, and it would run it. I'm asumming that this is more what Jon had in mind, so let's imagine this case...

   1:  public interface IOtherService
   2:  {
   3:      void Run(Notification example);
   4:  }
   5:   
   6:  public class Service
   7:  {
   8:      private readonly IOtherService otherService;
   9:   
  10:      public Service(IOtherService otherService)
  11:      {
  12:          this.otherService = otherService;
  13:      }
  14:   
  15:      public void DoStuff()
  16:      {
  17:          var firstExample = new SecondNotification();
  18:   
  19:          otherService.Run(firstExample);
  20:      }
  21:  }

 

Here, I pass it to another method. By using var, you do NOT lose any "flexibility". Ok, perhaps the DoStuff method will be returning this instance, in which case just make the return value exactly what you want to return. Want to return the interface? Go for it.

public class Service
{
    public Notification DoStuff()
    {
        var example = new SecondNotification();
        example.DoSomethingThatICouldNotDoWithTheCTorIKnowNotWhat(
            "ButMakeItPlainlyObviousThatICannotJustReturnTheVariableDirectly");

        return example;
    }
}

 

The only problem I can see is when you want to make sure that something is only used as an abstraction. If you didn't want to deal with it as a SecondNotification when it was returned from this method, you would've changed the return type. If using it as a parameter in another method, that method probably is expecting the actual class as opposed to the abstraction for a reason (probably a bad one, go change it). Thus, the only time you would be using this object in it's actual form is when the instance is still part of the method. Perhaps you want to avoid this situation...

 

public class Service
{
    public Notification DoStuff()
    {
        var example = new SecondNotification();

        example.MethodOnSecondNotificationThatIShouldNotBeRunningInThisCase();

        return example;
    }
}

 

Honestly, if you need to change that var to Notification to send the point home, fine. But otherwise, I don't see the deal regarding strategy patterns and flexibility. And once again, no, I didn't read everything in the blogosphere. I'm sure that when I get hit with something bad about it, I'll figure it out then, and make a blog post about it. For now, I'm not worried.


Friday, June 20, 2008 #

Ok, I admit, I didn't know what ThreadStatic was before today. I'm going to chalk it up to the fact that I don't deal (or, at least, hadn't dealt up until recently) with multi-threaded situations.

 

This all came when, partially by the fact that I am not liking the conclusions I drew on this post, I have started to look more at a static method. While revisiting Udi & Ayende's examples, I took a deeper look and noticed that there might be problems with how their code might work in multi-threaded situations.

As a quick recap, In both their examples, a message handler (service-layer code) would register what should be the response they should give depending on what the domain object tells them to do The actual possible events are placed in a static class that allows the service-layer the ablity to plug in what response it wants. Code below was from Udi's post...

 

  53:  public static class FailureEvents
  54:  {
  55:      public static event EventHandler GameReportedLost;
  56:      public static void RaiseGameReportedLostEvent()
  57:      {
  58:           if (GameReportedLost != null)
  59:               GameReportedLost(null, null);
  60:      }
  61:   
  62:      public static event EventHandler CartIsFull;
  63:      public static void RaiseCartIsFullEvent()
  64:      {
  65:           if (CartIsFull != null)
  66:               CartIsFull(null, null);
  67:      }
  68:   
  69:      public static event EventHandler MaxNumberOfSameGamePerCartReached;
  70:      public static void RaiseMaxNumberOfSameGamePerCartReachedEvent()
  71:      {
  72:           if (MaxNumberOfSameGamePerCartReached != null)
  73:               MaxNumberOfSameGamePerCartReached(null, null);
  74:      }
  75:  }

 

 

So, Udi is using .NET events to allow the service layer to register what should be done (Ayende's solution, while this specific part of the class is not posted in his response, used delegates instead). However, because these are static instances, it is completely possible for a handler to register itself, then have it's thread yield while another thread goes through the entire process, at which point two handlers will be registered to the event.

I created a simple app to demonstrate and found both would not work, given the code that I had seen. I sent an e-mail to Udi, who was very pleasent in his response. In the main course of his reply...

 

The solution is to combine what Ayende said with defining the list as thread
static (using the [ThreadStatic] attribute).

 

The ThreadStaticAttribute, when placed on fields, will ensure that each thread has it's own instance of the field. This will solve the problem in multi-threaded situations, since if a separate thread tries to access the field while another was working with it, it will be getting it's own version to work with. Attribute cannot be used on events, just fields, so the event solution would not work. To stick with events, as Udi explained, you would implement something as Ayende posted in the comment of Udi's post, where you make a custom implementation of the register/unregister properties that will add the event elsewhere (and of course use ThreadStatic on this new list.

For overriding, you do something like this:

List<WeakReference> gameRentalsEvents; 

event EventHandler GameRental
{
    add { gameRentalEvents.Add(value); }
    remove { gameRentalEvents.Remove(value); }
}

 

Ayende's solution in his blog post was to use delegates, and so long as you have ThreadStatic, this would work as well. As the delegates would be fields, they could use the ThreadStatic property, and in addition would probably be a lot smaller (at perhaps one line of code in the static class).

A final note on ThreadStatic, as I found by a quick google where I found a Scott Hanselman blog post, is that there are a few things to watch out for when using it. Read his post in full, but here are the tidbits...

First off, there is the fact that in a situation like in ASP.NET, or any place where you are using worker threads, a thread might be reused at a later point, which means it might still have the value leftover. So, you might find yourself in a position where you are expecting a field in a static class with ThreadStatic to be default, but really it has some leftover value. In the delegate case, this shouldn't be a problem, since you are just overwriting your fields the next time around anyway. But it could technically be considered a minor memory leak (the delegate on the static class is still alive and well, even though it will not be utilized).

 

The second is the nature of initialization for fields marked with ThreadStatic. The docs provides...

Do not specify initial values for fields marked with ThreadStaticAttribute, because such initialization occurs only once, when the class constructor executes, and therefore affects only one thread. If you do not specify an initial value, you can rely on the field being initialized to its default value if it is a value type, or to a null reference (Nothing in Visual Basic) if it is a reference type.

In other words, this class...

public class MyClass
{
        [ThreadStatic]
        public static string myString = "test";
}

 

will behave differently on different threads. If I'm reading it right, the first thread that uses it will have "test" initialized correctly, but all the rest will be null (but don't quote me on that). It's better off to just leave the field without a default initializer, and always assume that it will start with the default value.


Saturday, June 07, 2008 #

One of the common scenarios I find myself in is needing to be be able to mock an object instantiated during the lifecycle of another object. For example, a service object might need to, on receiving one message, create an entity, and on receiving another message, call some method on that entity. The easy way to do this is to make a builder as a service for the object needing construction, and mock out the builder object to return a mock. So, for that service-layer code I'm trying to test...

   1:  public class MyService
   2:  {
   3:      private readonly MyBuilder builder;
   4:      private readonly MyEntity entity;
   5:   
   6:      public MyService(MyBuilder builder)
   7:      {
   8:          this.builder = builder;
   9:      }
  10:   
  11:      public void OnSomeMessage(Message1 message)
  12:      {
  13:          entity = builder.Build();
  14:      }
  15:   
  16:      public void OnSomeOtherMessage(Message2 message)
  17:      {
  18:          entity.DoSomething();
  19:      }
  20:  }

 

Of course, this class is highly stripped down. There should be some error handling if, for example, Message2 is passed first (entity will be null in that case).

I can mock out my entity in the OnSomeOtherMessage method by passing in a mock MyBuilder object to return my mocked entity. When I need to eventually create the implementation for the MyBuilder object, it will look something like this...

   1:  public class MyBuilder
   2:  {
   3:      public MyEntity Build()
   4:      {
   5:          return new MyEntity();
   6:      }
   7:  }

 

This is fine, although you really can't test MyBuilder. However, even though I see myself as a TDD enthusiast, I don't think I need to test this MyBuilder class. Even if the constructor had args, I feel fine just leaving this as it is without tests. But now, assume that my entity is getting a bit more complex, and that there is a new rule that whenever this object is created, a message is sent out. This message should contain information that the entity holds, but the logic is too complex to do in the constructor. I've decided that an Initialize() method must be put on the MyEntity object. So, where do I call that Initialize method?

My gut reaction would be, in the builder. However, now because my builder has a bit of logic in it, I'm going to want to be able to test that builder to make sure that after it creates an entity, it calls this Initialize() method on it before returning. But, I run into that same problem of how do I mock the MyEntity object. Last time I ran into this problem, I added a builder, so let's do that...

   1:  public class MyBuilder
   2:  {
   3:      private readonly NoReallyThisIsTheBuilder builder;
   4:   
   5:      public MyBuilder(NoReallyThisIsTheBuilder builder)
   6:      {
   7:          this.builder = builder;
   8:      }
   9:          
  10:      public MyEntity Build()
  11:      {
  12:          var entity = builder.Build();
  13:          entity.Initialize();
  14:   
  15:          return entity;
  16:      }
  17:  }

 

Ok, this is just getting silly. I'm not going to really create another builder object. I felt dirty enough creating the first builder,  I'd hate to just keep making turtles all the way down.

This situation is easily solved with TypeMock

   1:  [Test]
   2:  public void TestObjectInstantiation()
   3:  {
   4:      MockManager.Init();
   5:   
   6:      var theMock = MockManager.Mock(typeof(Entity), Constructor.StaticNotMocked);
   7:   
   8:      theMock.ExpectConstructor(1);
   9:      theMock.ExpectCall("Initialize", 1);
  10:   
  11:      var builder = new Builder();
  12:      var results = builder.Build();
  13:   
  14:      Assert.That(results, Is.EqualTo(theMock.MockedInstance));
  15:   
  16:      MockManager.Verify();
  17:  }

 

But I'm not going to use a whole new framework just to support one style of test. If I used TypeMock more often, I'd probably go with this, but since I don't, I won't. Instead, I'll go with making a test-specific subclass...

   1:  public class Builder
   2:  {
   3:      protected virtual Entity BuildNewEntity()
   4:      {
   5:          return new Entity();
   6:      }
   7:   
   8:      public Entity Build()
   9:      {
  10:          var entity = BuildNewEntity();
  11:          entity.Initialize();
  12:   
  13:          return entity;
  14:      }
  15:  }
  16:      
  17:  public class TestSpecificBuilder : Builder
  18:  {
  19:      private Entity entity;
  20:              
  21:      public void SetStartingEntity(Entity startingEntity)
  22:      {
  23:          if (startingEntity == null) throw new ArgumentNullException("startingEntity");
  24:   
  25:          entity = startingEntity;
  26:      }
  27:   
  28:      protected override Entity BuildNewEntity()
  29:      {
  30:          return entity;
  31:      }
  32:  }

 

Slightly off-topic, but here's my take on TypeMock, which has been the center of controversy in the ALT.NET spectrum. Here's one situation where I find it helpful. The problem is, there isn't many other situations where I say that, and using a test-specific subclass is fine by me.That isn't to say there isn't any situations where you might use it. If you are doing a project with more lower-level code that is very close to the .NET framework in all it's sealed goodness, or perhaps working with legacy code, it would probably be more useful, but so far in my travels I haven't found many situations where it was miles beyond just using proper object relations.

In fact, the same probably goes for most mocking frameworks. I use them to mock objects, not create test seams. Most of my objects have only one or two methods on them, so writing a hand-written mock is pretty simple, and makes the tests easier to read ("EntityWasInitializedOnce" vs. "Expect.Call(entity.Initialized()).Times(1)"). I find my test seams mostly create themselves (with the above being one of the few examples where they don't). But remember, my experience with TypeMock goes as far as me downloading it this morning and creating that test I wrote above, so use your own judgement.


Friday, June 06, 2008 #

I use Resharper's unit test runner for running my unit tests while coding. I got sick of having to use my mouse to run my tests, but I couldn't figure out a good way to do it using Resharpers available key bindings. When the application is focused on the text editor window, you basically had two options for key bindings:

 

1.) Context Run. I'm not sure exactly what this did in terms of how it determined what tests to run, but it had something to do with looking at what class was open currently. This meant I could not use this to run my unit tests if I was currently in the class that I'm trying to implement. I want to be able to run my tests without having to navigate back to my tests.

2.) Run solution. I don't want to run all the tests in my solution. I'll do that later. I just want to run the tests specific to this class, the ones that I have in my unit test session.

 

The best result I've been able to find is the following:

 

1.) ReSharper.ShowUnitTestSessions. I'll set this to Shift+ALT+N. All this does will switch focus to my unit test window. It won't actually run the test. I set this as only usable in the text editor, because I also use...

2.) ReSharper.UnitTestSession_RunAll. This is also set to SHIFT+ALT+N. This will run all the tests, but it only works if you are already focused on the Unit Test window.

 

So, in the end, I hold SHIFT+ALT and press N twice. I'm sure there might be a better way, but I haven't found it yet.

EDIT (June 7, 2008):

I can't believe I just noticed this now! After running your unit tests, hit escape (I have it mapped to capslock, I do some stuff with VIM so it's second nature), that brings you back to your editor. The funny part was that the first time I didn't even realized that I did it, it just came so naturally.


Thursday, June 05, 2008 #

This is a weakness of mine that I just can't seem to shake, and I think it's starting to affect my productivity. As the single OOP developer at work, I don't have a senior developer to smack me over the head and say "get over it." Basically, I've been taught to keep my data encapsulated. At some point, the user wants it back. I don't want to give it to them.

Somewhere in the past few days, I saw on a blog someone mention the "getters are evil" camp, referring to Allen Hulob's article, <a href="Somewhere in the past few days, I heard someone group together people in the " getters are evil" camp, referring to Allen Hulob's article, . I guess I would be one of those people, not necessarily that any getter is evil, but I guess I strive harder than others to create objects which don't just show their data. Perhaps it's my ">"Why getter and setter methods are evil". I guess I would be one of those people, not necessarily that ANY getter is evil, but I think I strive harder than others to create objects which don't just show their data. I don't obviously go as far as Allen describes in his harshly critiqued article....

One ramification of full field encapsulation is in user interface (UI) construction. If you can't use accessors, you can't have a UI builder class call a getAttribute() method. Instead, classes have elements like drawYourself(...) methods.

I'll admit, I've actually thought about doing this... having the domain object have a method that allows the object to draw itself, and making, say, an HTML implementation of whatever object I pass to that method. I'm sure I played a video game instead, and I bet I got more out of it, but every once and awhile it still comes back to me.

I've found joy in developing code that is actually easier to understand and more succinct by having my object model use more void methods and less getters / query methods. But when I start thinking about the whole idea of encapsulation, the goal is to abstract away the data from anyone who uses that object. Typically, that person using the object is myself or another programmer. Generally, if you wanted to trust your data to someone, all things being equal, you would trust it to a programmer versus someone from marketing. And certainly you find greater trust in yourself than others. And yet this data that I have in my object, this data that I hide from fellow programmers so that they won't become coupled to it, this data that I hide from myself so that I can easily maintain it; I must show to my users?

Needless to say, I HATE doing user interfaces, and I don't mean the making things flashy part. I'll go through hoops to make my objects return DTO's from a BuildDTO() method, rather than expose them from getters. It's not that I think that methods are "better" than getters, it's just that now I have one member leaking my abstraction rather than all of them.

Honestly, I REALIZE that this is silliness. But still, I've often thought about how I would want it done. The user clicks on the "Modify Customer" button. Rather than getting a page representing a customer's record, they get a page that represents a form to change the customer's record. I would have an object that generates a form based on a customer record, and another object that handles the retrieved forms. These forms themselves are objects. But in the end, all these objects will need to get their data from somewhere, which means there would be somewhere an object exposing state.

And that bugs the hell out of me.


Wednesday, June 04, 2008 #

 

UPDATE (6/20/08):

If you are at all confused about some of the techniques outlined in the blog posts by Udi and Ayende I discuss below, specifically about their multithreading-capabilities, you might want to check out my future post here.

---

 

One of the first issues I have already found myself having to deal with in my game is the idea of how messages will be sent "from the entity" (since the entity is ultimately in charge of when something happens, and thus must trigger a message being sent), without needing the entity to know about how to send messages. This post describes some of the strategies I've been considering.

The example I will use is the UnitLocation entity, which stores where the unit is,  receive MoveUnit messages, and check to determine if the unit can move there (it must be a valid location on the map, and only one plot away from the unit's current location). If it can, it will do so, and send out a UnitMoved message. Otherwise, it will send out a UnitMoveFailed message, with a string for why it cannot. Keep in mind, there are other things that this entity must do, namely handle the map being initialized through a MapInitialized message and the unit being started through the UnitSpawned message, but for starters I'm just going to assume a 9x9 map with the unit in the middle, and that that unit is the only unit in the game. This all initialized when the system starts.

So, my entity could look something like this...

   1:  public class UnitLocation
   2:  {
   3:      private readonly Map map;
   4:      private MapCoordinate currentCoordinate;
   5:   
   6:      public UnitLocation()
   7:      {
   8:          map = new Map(new MapDimensions(9, 9));
   9:          currentCoordinate = new MapCoordinate(4, 4);
  10:      }
  11:   
  12:      public void MoveUnit(MapCoordinate newCoordinate)
  13:      {
  14:          CheckValidCoordinate(newCoordinate);
  15:          CheckAdjacent(newCoordinate);
  16:   
  17:          // If the above pass...
  18:          currentCoordinate = newCoordinate;
  19:          // Send UnitMoved message with newCoordinate.
  20:      }
  21:   
  22:      private void CheckValidCoordinate(MapCoordinate newCoordinate)
  23:      {
  24:          if (map.IsValidCoordinate(newCoordinate) == false)
  25:          {
  26:              // Send UnitMoveFailed message with reason "Invalid Coordinate"
  27:          }
  28:      }
  29:   
  30:      private void CheckAdjacent(MapCoordinate newCoordinate)
  31:      {
  32:          if (map.AreCoordinatesAdjacent(currentCoordinate, newCoordinate) == false)
  33:          {
  34:              // Send UnitMoveFailed message with reason "Coordinate not adjacent"
  35:          }
  36:      }
  37:  }

So, here are my criteria for choosing a strategy that allows the entity to notify the service-level code that is utilizing it (henceforth, the "Gateway" to the entity) that it should be reacting to events. I Will be be constantly referring to when the entity wants a message sent to triggering an "event" that the gateway responds to. Keep in mind, though, that this does not mean that I must use C# events.

Criteria:

1.) Strategy must be easily testable. More than just being easy to unit test, an easily testable strategy will also determine how easy it is for the Gateway to be able to do it's job. If I have to hook up and intercept a bunch of interface calls in each test, then I'll more than likely be needing to wire up a bunch of interfaces in my code.

2.) Strategy must not assume what message a method will be sending, nor how many messages it is sending. As shown above, a method will not necessarily trigger one type of event per method. While there isn't any method listed in my example that shows sending multiple messages, or no messages at all, I would still like to support those cases.

3.) Limit any changes to entity return-values & parameters. I can deal with small, inconsequential changes, but don't make every method need to use three out parameters to work.

4.) Keep strong encapsulation. I prefer not to expose my state. I will not accept strategies that require the above example to use getters for the map, current location, or any other added additional member variables.

5.) Allow Gateway to control message results. I want the Gateway to be able to easily do what needs to be done with the messages sent from the entity. In other words; the entity cannot bypass the gateway. For example, I might want to have the messages the entity sends out to be wrapped with some sort of envelope, or aggregated together in one super-message. The gateway will most likely be dealing with these concerns, so I want it to get first crack at the results of any messages that are sent out. If it decides it just wants to send it directly out, it can have the option of doing so.

 

With these criteria in mind, here are the strategies I considered, in no particular order...

 

List of Strategies:

1.) Static Send.Message

The entity creates the message, and sends it to a Send.Message method in the sky. Testing can be done assuming that whatever the Send.Message method does can be faked out. This can be slightly changes to have more than one static method, one for each message, but that just seems a ton of work.

   1:  [Test]
   2:  public void SendsSomeMessage()
   3:  {
   4:      MessageInterceptor interceptor = new MessageInterceptor();
   5:   
   6:      using (Send.RegisterIntercept(interceptor))
   7:      {
   8:          // Exercise entity
   9:          // ...
  10:   
  11:          var expectedMessage = //...
  12:          Assert.That(interceptor.Intercepted(expectedMessage));
  13:      }
  14:  }

 

Of course, this can be thrown right out. It's the simplest solution, in my opinion, but not only might the entity need to know the message data structure, it also will bypass the gateway if the gateway doesn't "hook into" the message sending system.

2.) Passing a Message-Sending object into entity through constructor/property injection, or method parameters.

Injection of anything into entities seems to give people tummy aches, but I've never been one to shoot down an idea just because I ate too many Oreos (except, perhaps, the idea of eating more Oreos). In this idea, an object implemented in the service-layer will send the message is injected once into the entity. This can be mocked more easily than using the static Send.Message.

In both the constructor and property injection, mind you, the object need not be done by an inversion of control container. It could be as simple as...

   1:  public class UnitLocationGateway: Handles<MoveUnitMessage>
   2:  {
   3:      private readonly Bus bus;
   4:      private readonly UnitLocation unitLocation;
   5:   
   6:      public UnitLocationGateway(Bus bus)
   7:      {
   8:          this.bus = bus;
   9:   
  10:          var unitLocationMessageSending = new UnitLocationMessageSending(bus);
  11:          unitLocation = new UnitLocation(unitLocationMessageSending);
  12:      }
  13:          
  14:      public void Handle(MoveUnitMessage message)
  15:      {
  16:          unitLocation.MoveUnit(new MapCoordinate(message.X, message.Y));
  17:      }
  18:  }

 

At first, the problem with this code is that, in terms of unit testing, it's not as testable as I would LIKE it to be. That is to say, I would need to have some way of determining that the UnitLocation was created with the correct service type. Assuming I implement "constructor equality" on UnitLocationMessageSendingService, I could do this by having MoveUnitGateway take a UnitLocation factory service, that I would be able to provide a mock unit location for. I don't like creating new services just to help facilitate unit testing, I will make an exception for this case, as it typically alleviates all my other pains. Besides, I would never write a unit test for this class...

   1:  public class UnitLocationBuilder
   2:  {
   3:      public void BuilderUnitLocation(UnitLocationEventHandler messageSending)
   4:      {
   5:          return new UnitLocation(messageSending);
   6:      }
   7:  }

 

All this class earns me is the need to change the parameters whenever the UnitLocation constructor parameters change. I'll take that hit for the unit testing abilities. BTW, I keep talking about passing a UnitLocationEventHanlder, which is probably an interface that consists of a method for each type of event that might happen in the entity. I would probably separate this into an interface per event, just to make it easier to deal with being able to handle different events with different objects.

So this can work, unless I want to change what type of object I'm using as my message-sender (for example, replace it with an "IgnoreEvents" object that just drops the messages on the floor, which I guess is debatable as to whether it would be of any use). Another failure is that any destruction of the UnitLocation at any time, such as saving it to some repository, and then destroying the object (the typical lifecycle I deal with in my web projects, not sure how much I'll see it writing this game), will mean that at reconstitution, I most likely won't have my message-sending objects anymore. Finally, and most importantly to me, it uglies up my constructor.

Property injection fixes some of these issues (you can "rewire" the services after a reconstitution of an entity from the repository) but isn't testable. For it to be testable, I would have to find some way of determining that I passed the correct service objects to the properties, which would require getters/other means on those properties (yuck) or equality overriding. I don't mind doing "constructor equality", because I'm assuming that the objects passed into the constructor will not be changed, making Equals (and thus, GetHashCode()) less likely to cause disappearing acts in dictionaries. However, using properties for your equals overrides, you are almost guaranteeing that they will be changed. Of course, I could make all of this easier by just allowing myself to use getters, but I guess I'm a masochist like that.

Finally, you can do all this "injection" through the method calls as argument. Most problems are solved, but now you are uglying up you method parameters. If you are like me and want your message sending objects to be separate interfaces as opposed to all lumped into one, this will ugly up your parameters even more.

3.) Make a static event or delegate for the Gateway to subscribe to.

These ideas came from posts called "How to create fully encapsulated Domain Models" and "Re: How to create fully encapsulated Domain Models", by Udi Dahan and Oren Eini, respectively. If you are interested in the concept of encapsulation of your domain from the service layer without injection, you should definitely check out the posts and comments. The idea is to create some outside system with which the gateway subscribes to and uses to receive event triggers from the entity. In Udi's strategy, you use C# events on a static class. In Oren's, you use delegates instead (still on a static class). The use of events vs. delegates or events with weak references isn't as important to me

4.) Make events/delegates on the entity for the Gateway to subscribe to.

Basically, the same thing as above, but rather than deal with a completely separate class, you place these directly onto your entity. You get all the advantages/disadvantages of above, but you don't need this separate class. Unfortunately, you also get this complexity that Udi mentioned:

The problem is that if an event is raised by a child (or grandchild object), the service layer object may not even know that that grandchild was involved and, as such, would not have subscribed to that event. The only way the service layer could work was by knowing how the Domain Model worked internally - in essence, breaking encapsulation.

Of course, you could fix this by having any event on the child also be an event on the aggregate root, where the child event invocation triggers the aggregate root invocation. For this, you would have to wire up the children's event to the entity's, which is possible, but a pain. Also, assume that you have an aggregate root with a child entity. In this case, we have three classes that know about the event and need to have members that do something about it: The gateway, the aggregate root, and the child entity. In the static class, we have the same number of classes that need to know about this event: the gateway, the child, and the static class. So far, it's the same. Now, assume that child entity has a GRANDCHILD which triggers an event. Here, four classes need to "know" about the event, the gateway, aggregate root, child, grandchild. In the static class system, you still only have three classes that know about it. I don't think that wiring up and passing these events through the entity "chain" would fall under the category of "breaking encapsulation" any more than the aggregate root returning results from a getter on the child would, but I do think that this method will result in more code, and not in a good way.

Finally, if for any reason you wanted to notify the gateway of an event during entity construction, it would be impossible, since the gateway couldn't wire itself to the delegate before the entity was created. This could easily be fixed (and would probably be a better idea than having a more complicated constructor) by using a builder for the entity, and making the builder send the event notification.

5.) Have method return an "OperationResult" object.

Although Oren used the above strategy in his post, he saw it more of how he would "approach Udi's sample", posting in his comments, "I might go with an OperationResult instead, but it is basically the same idea." Edit: Oren wasn't specific about this, this is simply what I would do.

The nice part about this strategy is that, assuming that you have stuck with Command/Query Separation, your methods that "do things" should all have void return types. All other methods and properties should not be triggering events, as they're just queries, and so you don't need to worry about how to return an OperationResult from them. Of course, you could also say that all of a sudden your commands are returning something, violating Command/Query Separation. This is something I'm willing to do, however, and I guess is really a judgement call to the same degree that strict following of CQS is in the first place.

Now, you might argue that even getters or other methods that don't run side effects could trigger events. Since these members already have return types, how could we return an OperationResult as well? What if we have an event that is produced every time that the a piece of data is retrieved? Maybe you want to keep a tally of times a report is generated (for domain-related ideas, not for performance profiling). To this, I say that this "tracking" is an outside concern. If this needed to be done, then another service could receive the PullReport message as well, and handle that logic. There is no reason for a query member to be triggering events.

Gateway code is kept simple (no need to subscribe to any events). The question is what does the OperationResult object look like? Consider the following example: Suppose I have a domain object Visibility that, on receiving a UnitMoved message, determines if any new plots are visible to the owner of the unit. The operation result object (and thus the type that the method returns) could look like this...

   1:  public class UpdatePlayerVisibilityOperationResult
   2:  {
   3:      private readonly IList<MapCoordinate> mapCoordinatesRevealed;
   4:   
   5:      public UpdatePlayerVisibilityOperationResult(IList<MapCoordinate> mapCoordinatesRevealed)
   6:      {
   7:          this.mapCoordinatesRevealed = mapCoordinatesRevealed;
   8:      }
   9:   
  10:      public IList<MapCoordinate> MapCoordinatesRevealed
  11:      {
  12:          get { return mapCoordinatesRevealed; }
  13:      }
  14:  }
 

The problem I have with this is that if the visibility operation needs to start sending out additional messages (like in the case of my MoveUnit, there are failure cases that could happen as well), I need to keep adding on new data to this object for each scenario. That's not just a violation of OCP, it's just plain annoying.

Instead, I would probably have an OperationResult object, and each different type of result (UnitMoved, UnitMoveFailed, etc.) gets it's own type(which will probably just be a struct with the data). They add each event to this result object, and return the collection to the gateway. The gateway tells the operation result object how to handle each type of event by giving it objects of it's own, one for each type of event it wants to handle. Here is how I would like the class to work...

   1:  public class UnitLocationGateway : Handles<MoveUnitMessage>
   2:  {
   3:      private readonly Bus bus;
   4:      private readonly UnitLocation unitLocation = new UnitLocation();
   5:   
   6:      public UnitLocationGateway(Bus bus)
   7:      {
   8:          this.bus = bus;
   9:      }
  10:   
  11:      public void Handle(MoveUnitMessage message)
  12:      {
  13:          var newCoordinates = message.MapCoordinates;
  14:   
  15:          var unitMovementFailed = new SendUnitMovementFailedMessage(bus);
  16:          var unitMoved = new SendUnitMovedMessage(bus);
  17:   
  18:          var results = unitLocation.MoveUnit(newCoordinates);
  19:          results.UseHandler<UnitMovementFailed>(unitMovementFailed);
  20:          results.UseHandler<UnitMoved>(unitMoved);
  21:      }
  22:  }

 

You can see lines 15 + 16 creating my event handler objects. This means my gateway will just need to mock out the OperationResult returned from the entity, and assert that I'm getting the correct handler objects passed into it during the UseHandler method calls. Finally, because I'm using a reusable OperationResult object, I can create a really sweet OperationResultMock object, which I've always found better than dealing with mock frameworks.

By the way, the generic call on UseHandler can be made implicit, but I placed them there to show how the UseHandler method is working. It will ensure that the object passed is of a type EventHandler<T>. Of course, if I found making all these handler objects too much, I could just as easily change the arguments of UseHandler to allow for an Action<T>. But, every time I implement new functionality by creating a new class, I get the feeling I'm doing something right, so creating new classes isn't that big of a deal to me. :P

Finals Thoughts:

As you can probably tell, I've really been leaning towards using the OperationResult. Interestingly, I will no doubt find that my UnitMoved event struct will look remarkably similar to my UnitMovedMessage struct, which immediately makes me question the validity of attempting this whole ruse of encapsulation in the first place. I'm sure this is the same thoughts that run through the head of some people when they wonder if they really need that service tier on their web-app, or if they can just put the repository and entities right on their MVC controller. The difference is that the domain is a mystical, magical beast, and that putting infrastructure in your infrastructure (service-layer code in your MVC controller) if ok, while putting infrastructure in your domain (even though they look REMARKABLY similar) is "bad practice". However, for now I'm going to trust the wisdom of the ancients and not dwell on this too much. After all, one of the things I've been trying to get out of my head is that the goal of OOP is NOT to reduce duplication, as was told to me time and time again in college.

Hopefully, I will be able to come back with thoughts on how the OperationResult strategy has treated me. Also, hopefully my posting of this (as opposed to typing some, thinking some, sleeping some, changing my mind, typing some, eating, changing my mind) will get me to start working, and stop over-thinking.


Tuesday, May 27, 2008 #

Ok, in the spirit of DRY, I'm going to write this blog post once, describing my main ideas for the game I've finally decided to start working on. More than just slappy fun, I've decided to implement this game in a hard-core message-passing style, taking hints from the likes of Udi Dahan and Greg Young (note I said hints, so if one of them is reading any future post of mine, beware, your concepts might be twisted to do evil deeds, bwahaha).

The game is planned to be a 4x style turn-based strategy game, similar to the Civilization series, although it may end up being closer to SMAC. A player starts the game in a world that consists of many plots aligned on a 2D grid. They have one or two units, one of which can build a new city. Every turn, a city gains resources based on it's surrounding plots, where it can build city improvements (buildings), or produce units. By balancing your military, technology, economy, foreign diplomacy and politics, you try to forge your empire to victory.

As much as the gameplay details are fun, I'm drooling over the technological aspects of the implementation. Before learning concepts like patterns, TDD, inversion of control, etc., I did some modding on the PC game Civilization 4 (Civ4). Civ4 offered a great amount of modding flexability with their c++ SDK and python scripts. The thing is, you really couldn't unit-test this thing. The CvPlot.cpp class, for instance, was a few thousand lines of code, dealing with every detail of the plot. The AI was built using the CvPlotAI.cpp, a subclass of CvPlot that would override abstract methods on CvPlot. You would have to change something, compile it, then load the entire game, which probably took all of 3 minutes on a reasonably fast computer.

In other words, once I learned unit testing, and found myself working on projects where the time to determine if things worked were nearly instantaneous (run tests, hurray green!), my desire to work on such a large project as Civ4 mods faltered.

I'm hoping to avoid the CvPlot motherload by separating out the various parts into their own services. For example, one service might have a Plot entity that just contains items relating to whether a unit can enter a plot (the owner of the plot, whether the plot is a water/land plot, etc), while another service will contain just info relating to what defensive bonuses units gain if defending on that plot. Still another service will actually determine the results of combat.

Now, this may sound like a recipe for an anemic domain model, but the reality is that each of these "services" really takes in messages, and as a result calls some method on a real entity. This entity is part of my domain model, built using quasi-DDD tactics. However, there isn't one "Plot" entity, or one "Unit" entity, but actually multiple such entities, one for each specific concern, and maybe a few for some aggregate concerns.

So, there in a nutshell is my project. It doesn't yet have a name, and I probably won't release more than the snippets I post here just for simplicity's sake. Right now, I'm working on some core classes. I'll probably start small; 9x9 grid of dots with a moveable X in the console, small. Hopefully the architecture will allow for a gui to be built without much change at all.

 

Sunday, May 11, 2008 #

Recently, after some analyzing some of the controllers I was building using ASP.NET MVC, I found that my controllers typically have the same pattern. They all have some dependencies injected into them through the constructor, each action calls a method on one of the dependencies (typically using the arguments of the  and gets a result back), and depending on the result, an ActionResult is returned.

Now, writing the tests wasn't tough. But, I dunno, I guess I'm REALLY lazy. So I started looking today at some sort of an idea for a DSL that could make testing even easier than using all the extension methods found in MVCContrib.

Eventually, I came up with a syntax that was pretty simple, and thought, "Well, I've gone this far, I wonder if I can take it one step further."

I haven't implemented it completely, but the idea is rather than build a class to act as your controller, you build actions using an action builder. The action consist of these things...

1.) A name (typically in the "/area/controller/name", not still sure about how the areas would work under ASP.NET MVC, I don't know if I still grok the whole routing thing)

2.) A lambda expression with one strongly typed arg that represents the parameters of the request.

3.) A key-value of conditions, with the key being a Type, and the value being the action result.

Here is some example code. No implementation, just throwing it out there...

 

   1:  var action = Create.Action("Customer/Orders/ViewPending",
   2:          (CustomerID id) => new ReviewPendingCustomerOrdersTasks(id))
   3:      .Results<PendingCustomerOrdersReview>(RenderView.View())
   4:      .Results<CustomerNotFoundResults>(Redirect.To("NotFound"));
 
 

In the first line, we create the action with the name. The second line has the arguments that we'll bind the parameters into (a CustomerID object), that is used in a lambda expression to say what actual task object should be invoked for this action (more on this below). The argument's type could be as simple as an int or Guid, or as complex as we want our DataBinder to be.

ReviewPendingCustomerOrdersTask is a class that would be in our service layer. Typically, you have things such as ICustomerOrders, which has methods such as GetOrder(id), GetAllOrders(), GetPendingOrders(), etc., and then a class which implements all those methods in your service layer. However, I typically enjoy having as small a number of methods as possible on a class, even if it means more classes, so I would have a GetOrderTask class, a GetAllOrders class, and a GetAllPendingOrders class (I'm also trying to stop using "Get____", and instead come up with terminology for what this task is actually used for). Typically, I would need to then put each of these various services into my IoC container, but since I'm just creating the objects directly, I don't really need the container for these services.

This, of course, assumes that the container will have the ability to use setter-injection on my service that is not included in the container, for dependencies such as the repository. Something like...

   1:  var ioc = MyGreatIoCContainerAlreadyLoadedUpWithStuff;
   2:  var task = new ReviewPendingOrdersTask(args);
   3:  ioc.ResolveOn(task);
 

The ResolveOn method should be able to see that the ReviewPendingOrdersTask object has a public setter for IRepository, and inject the IRepository into it. I'm sure some IOC containers can do this, but I don't know the methods off the top of my head (nor after a quick google search...)

Ok, so now let's take a look at what the implementation of ReviewPendingOrdersTask might actually look like....

   1:  public class ReviewPendingCustomerOrdersTasks : Task
   2:  {
   3:      private readonly CustomerID id;
   4:   
   5:      public ReviewPendingCustomerOrdersTasks(CustomerID id)
   6:      {
   7:          this.id = id;
   8:      }
   9:   
  10:      public Repository Repository { get; set; }
  11:   
  12:   
  13:      public void Run(Context context)
  14:      {
  15:          var customer = Repository.Run(Commands.Fetch<Customer>(id));
  16:   
  17:          if (customer == null)
  18:          {
  19:              context.RunResults(new CustomerNotFoundResults(id));
  20:              return;
  21:          }
  22:   
  23:          var summary = customer.BuildPendingOrdersSummary();
  24:   
  25:          context.RunResults(summary);
  26:      }
  27:  }

 

The class inherits from Task, which is simply an interface that defines void Run(Context). Context is defined here...

   1:  public interface Context
   2:  {
   3:      void RunResults<T>(T results);
   4:  }

 

As you can see, testing the task would be very simple. We would just mock out the repository, and pass a test-specific version of Context to the method, assuring that when the method finishes, context.RunResults was called with the correct argument.

To wrap this all up, an IController class implementation is created when the app starts up. It houses ALL the actions. When it gets a request, it finds the correct action, binds the arguments (in the example, to CustomerID), and calls the lambda function to create the new task. The controller, which has a dependency on IoC container, uses the container to inject the necessary dependencies (like Repository) into the task, and creates a Context with the dictionary of the result types. When the task uses RunResults, the context matches the result type to that passed into the dictionary, and thus we have the ActionResult that we passed in when creating the action.

Another thing I would probably do is change so that the action is built using an action builder, rather than a static Create.Action. Then, you can create an action builder and set a default action (like, for example, if a task runs result UnmetSecurityCriteria, you can always redirect to a page without having to set each action individually, but of course have the ability to override it for a specific action).

I really haven't changed much of my task (typically, I was returning BuildPendingOrdersSummary, but now I'm passing the results into the Context object). I now have a simple way of handling failures without resorting to throwing exceptions. Obviously, not everything is fleshed out. More advanced scenarios could implement their own action result, which might add things to the flash before a redirect, etc., but that still seems like a pain.

Thoughts?


Wednesday, April 23, 2008 #

I often have found that working with small, immutable objects can be very helpful. First off, they are extremely easy to test, typically not needing any sort of mocking involved. Second, due to their immutable state, you can easily override Equals to use to your advantage. The advantage I'll talk about today is the ability to introduce a new test seam that doesn't depend upon inversion of control to be able to test an object.

 

Suppose I'm writing an object that will represent a query. The query should return all blogs that contain certain text in their titles...

 

public class BlogWithTextInTitle : Query<Blog, BlogCollection>
{
    private string text;

    public BlogWithTextInTitle(string text)
    {
        this.text = text.ToLower();
    }

    public BlogCollection RunOn(IQueryable<Blog> queryable)
    {
        var results = from b in queryable
              where b.Title.ToLower().Contains(text)
              select b;
        return new BlogCollection(results.ToArray());
    }
}

 

Fun stuff! Now, suppose that I am going to write something in my service layer that will query all the blogs with the text "Hello World" in the title, and send a warning to their owner about how unimaginative their blog titles are.

(Stupid examples. I'm full of 'em.)

Now, you'll notice this query implements an interface, Query. My repository will have something like a "Find" or "RunQuery" method on it to run these queries (check out Ayende's post "Thinking about repositories" for more details on this). The service might look like this...

 

public class SendWarningService : ISendWarningService
{
    private Repository repository;

    public SendWarningService(Repository repository)
    {
        this.repository = repository;
    }

    public void SendWarningToThoseWithTextInTitle(string text, string warningMessage)
    {
        var query = null; // How do I create the query, while still being able to use it in a test?
            
        BlogCollection blogs = repository.FindAll(query);
        blogs.SendWarningToAll(warningMessage);
    }
}

 

I need to test that the blog collection returned has it's SendWarningToAll method called, but how can I control what FindAll returns? Typically, I would use a stub, but I would need to create that stub in the test method. How could I then pass that stub to the actual method? I could put a QueryFactory into the constructor, and then mock out the factory to have it return my stub, but I don't like that idea. Interestingly, we don't seem to have this problem with value types, do we? Let's assume that the query were a value type (which, I guess if you really wanted to, you could do by making it a struct, but I don't think I'm comfortable with that). Here's what the test would look like...

 

   1:  public void GivesWarningToBloggersReturnedFromQuery()
   2:  {
   3:      // Create test values.
   4:      var text = "Hello World";
   5:      var warningMessage = "Hello World? 'cmon, it's been done before!";
   6:   
   7:      var expectedQuery = new BlogWithTextInTitle(text); // Check it out, I'll just go ahead and create this thing...
   8:   
   9:      var repository = new FakeRepository();
  10:      var blogCollection = new FakeBlogCollection();
  11:   
  12:      // Set the repository to reutrn the fake blog collection when it recieves the query object.
  13:      repository.SetupResultFor(expectedQuery).Return(blogCollection);
  14:   
  15:      // Exercise the test.
  16:      var service = new WarningBlogsService(repository);
  17:      service.SendWarningToAllWithTitleContaining(text);
  18:   
  19:      // Check that the collection had it's message sent.
  20:      Assert.That(blogCollection.MessageWasSent(warningMessage), "Message was not sent.");
  21:  }

 

Notice that at no time am I ever passing the query object (expectedQuery) into the service. Instead, the service will be allowed to make another query object, simply using the new operator.

 

   1:  public class SendWarningService : ISendWarningService
   2:  {
   3:      private IRepository repository;
   4:   
   5:      public SendWarningService(IRepository repository)
   6:      {
   7:          this.repository = repository;
   8:      }
   9:   
  10:      public void SendWarningToThoseWithTextInTitle(string text, string warningMessage)
  11:      {
  12:          var query = new BlogWithTextInTitle(text);
  13:          
  14:          BlogCollection blogs = repository.FindAll(query);
  15:          blogs.SendWarningToAll(warningMessage);
  16:      }
  17:  }

 

See on line 12, I just go ahead and create the object. However, if I ran the test as it is, it would fail, because right now my fake repository (and any mock framework you use) will probably be doing the default testing of equality by reference. Obviously, the object created in my test is not equal to the one created in the actual method, because they do not reference the same object. However, by overriding Equals on our query, we can actually make this work...

 

public class BlogWithTextInTitle : Query<Blog, BlogCollection> {
    private string text;

    public BlogWithTextInTitle(string text)
    {
        this.text = text.ToLower();
    }

    public BlogCollection RunOn(IQueryable<Blog> queryable)
    {
        var results = from b in queryable
              where b.Title.ToLower().Contains(text)
              select b;
        return new BlogCollection(results.ToArray());
    }

    public override bool Equals(object obj)
    {
        var other = obj as BlogWithTextInTitle;
        if (ReferenceEquals(null, other)) return false;

        return text.Equals(other.text);
    }

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

This is sort of like using a whole new test seam. Typical test seams used are the constructors, properties, and method parameters, which are all used to pass mocks and stubs. The problem is that you can start filling these up quickly. By using value equality to your advantage, you can "pass" a stub into your system under test without using another parameter.

Now I've been bitten before by screwing up such a repetitive thing like overriding Equals. Furthermore, Testing that you've overridden Equals correctly could include a bunch of tests...

 

  • Not equal to null
  • Not equal to an object of a different type.
  • Not equal to an object of the same type with different parameters.
  • Equal to an object of the same type with same parameters.

 

That's four tests to test three lines of code (I don't test GetHashCode()... technically you could just return 0 and things would still work, just with a performance hit, but do read the comments below!). And, I've found that I do this a lot. For example, testing that you threw a custom assertion correctly is much easier when all you need to do is create the assertion yourself and check that this assertion equals the one just thrown.

So, eventually, I started needing to do these kind of tests enough that I created my own class for it. Basically, the test will test that a class adheres to the idea of Constructor Equality. This means that two objects will be considered equal if they were created by using the same constructor parameters.

 

   1:  public class ConstructorEqualityTest<T>
   2:  {
   3:      private readonly T same1;
   4:      private readonly T same2;
   5:      private readonly T[] different;
   6:   
   7:      public ConstructorEqualityTest(T same1, T same2, params T[] different)
   8:      {
   9:          this.same1 = same1;
  10:          this.same2 = same2;
  11:          this.different = different;
  12:      }
  13:   
  14:      public IList<string> Failures
  15:      {
  16:          get
  17:          {
  18:              IList<string> failures = new List<string>();
  19:                  
  20:              if (!PassesEqualToNullTest())
  21:              {
  22:                  failures.Add("Type should not be equal to null.");
  23:              }
  24:   
  25:              if (!PassesEqualToOtherTypeTest())
  26:              {
  27:                  failures.Add("Type should not be equal to a different type.");
  28:              }
  29:   
  30:              if (!PassesEqualToSameConstructorArgs())
  31:              {
  32:                  failures.Add("Type should be equal to another type constructed with the same arguments.");
  33:              }
  34:   
  35:              foreach (int indexMarkedAsSame in GetDifferentObjectsMarkedAsSame())
  36:              {
  37:                  failures.Add("Type should not be equal to another type constructed with different arguments (Different Argument " + indexMarkedAsSame + " was seen as same)");
  38:              }
  39:                  
  40:              return failures;
  41:          }
  42:      }
  43:   
  44:      public string FailureMessage
  45:      {
  46:          get
  47:          {
  48:              StringBuilder stringBuilder = new StringBuilder();
  49:              stringBuilder.AppendLine("The object did not pass all requirements for Constructor Equality.");
  50:   
  51:              foreach (string failureMessage in Failures)
  52:              {
  53:                  stringBuilder.AppendLine(failureMessage);
  54:              }
  55:   
  56:              return stringBuilder.ToString();
  57:          }
  58:      }
  59:   
  60:      private bool PassesEqualToSameConstructorArgs()
  61:      {
  62:          return same1.Equals(same2);
  63:      }
  64:   
  65:      private bool PassesEqualToNullTest()
  66:      {
  67:          return !same1.Equals(null);
  68:      }
  69:   
  70:      private bool PassesEqualToOtherTypeTest()
  71:      {
  72:          return !same1.Equals("A_String");
  73:      }
  74:   
  75:      private IList<int> GetDifferentObjectsMarkedAsSame()
  76:      {
  77:          IList<int> list = new List<int>();
  78:          for (int index = 0; index < different.Length; index++)
  79:          {
  80:              if (same1.Equals(different[index]))
  81:              {
  82:                  list.Add(index);
  83:              }
  84:          }
  85:   
  86:          return list;
  87:      }
  88:          
  89:      private bool PassesEqualToDifferentConstructorArgs()
  90:      {
  91:          return GetDifferentObjectsMarkedAsSame().Count == 0;
  92:      }
  93:   
  94:      public bool Passes()
  95:      {
  96:          return PassesEqualToNullTest() &&
  97:              PassesEqualToOtherTypeTest() &&
  98:              PassesEqualToDifferentConstructorArgs() &&
  99:              PassesEqualToSameConstructorArgs();
 100:      }
 101:  }

So now, if I wanted to test that my query works adheres to the concept of "Constructor Equality", I could use this test...

 

[Test]
public void AdheresToConstructorEquality()
{
    var same = new BlogWithTextInTitle("same");
    var same2 = new BlogWithTextInTitle("same");
    var different = new BlogWithTextInTitle("different");

    var test = new ConstructorEqualityTest<BlogWithTextInTitle>(same, same2, different);

    Assert.That(test.Passes(), test.FailureMessage);
}
 

First, I created two objects that should be equal. I'll also created additional different objects that will all be tested to ensure that Equals will return false. Each one should be different from the "same" objects from one parameter. If I had a class that had two parameters, I would use the following...

 

[Test]
public void AdheresToConstructorEquality()
{
    var same = new MyClassToTest(1 ,2);
    var same2 = new MyClassToTest(1, 2);
    var different1 = new MyClassToTest(-999, 2);
    var different2 = new MyClassToTest(1, -999);

    var test = new ConstructorEqualityTest<MyClassToTest>(same, same2, different1, different2);

    Assert.That(test.Passes(), test.FailureMessage);
}
 

My test will fail to begin with, with the failure message telling me that the objects created with the same arguments should be equal, but they aren't. Then I would override equals until my test passes.