Archive
Working with XML Namespaces and LINQ
October 11th 2010 | Ben Yoder
Working with XML Namespaces and LINQ
While working on a project using LINQ to XML to parse a web response, I ran into an issue whereby my calls to get an entity’s Descendants or Elements were returning no results. It turned out that the specified response included a namespace. In this case you can’t use the common element name—you must get the fully qualified XName.
For example, given the following XML and LINQ Query:
string xml = @"<Employees> <Employee> <FirstName>John</FirstName> <LastName>Smith</LastName> <Id>1</Id> </Employee> </Employees>"; XElement employee = XElement.Parse(xml); var employees = from e in employee.Descendants("Employee") select new { Id = e.Element("Id").Value, FirstName = e.Element("FirstName").Value, LastName = e.Element("LastName").Value };
The query works and the employees object contains John Smith. However if the XML changes, the query returns nothing:
<h:Employees xmlns:h="http://www.w3.org">
<h:Employee>
<h:FirstName>John</h:FirstName>
<h:LastName>Smith</h:LastName>
<h:Id>1</h:Id>
</h:Employee>
</h:Employees>
After browsing through some MSDN documentation, I learned that I have to include the namespace in the query. I got the full name using XName.Get()
XName root = XName.Get("Employee", "http://www.w3.org"); XName firstName = XName.Get("FirstName", "http://www.w3.org"); XName lastName = XName.Get("LastName", "http://www.w3.org"); XName id = XName.Get("Id", "http://www.w3.org");
Replace the names in the LINQ query and it returns the correct results. Of course, there are other ways to accomplish this. You could create an XNamespace object based on the namespace string and prepend it to each element name in the query. Creating an individual XName object for each query parameter gets kind of verbose, so for more complex LINQ this is probably not the preferred way.
Code Challenge Results
Thank you to all to those that submitted code solutions. We will be running another code contest in a few weeks. Check back soon to enter our next contest. Congratulations to our contest winner: Rob Howarth
See the bottom of this page for an example solution
Others who submitted correct solutions
- Rob Howarth
- Scott Monnig
- Eric Haddan
- Thomas Eyde
- Imran Baloch
- Marc Chu
- Cesar Neves
- Jaider Ariza
- Kenneth Hall
- Teymur Mammadov
- Cam Luc
- Peter Burrell
- Anthony Clayton
- Mark Lindell
- Steve Smith
- Chris McKenzie
- Amit Parikh
- David White
- Ron Warholic
- Josh Clark
- James Baker
- Richard Deeming
- Erik Jõgi
- MORRIS CRISTOPHER
- Scott Holodak
- James Curran
- Marius Ene
- Matt Crouse
- Michel Grootjans
- Daniel Griffie
- Xiu
- Mordechai Sandhaus
- Stuart Cam
- Raj Rao
- Rafik Ramtoolah
- Ali Derman
- Eric King
Sample Solution
public class Converter
{
public string Convert(int number)
{
StringBuilder buffer = new StringBuilder();
int quotient = number;
int remainder = -1;
while (quotient != 0)
{
remainder = quotient % BaseNumber;
quotient = quotient / BaseNumber;
buffer.Insert(0, ConvertSingleBaseNumber(remainder));
}
return buffer.ToString();
}
protected virtual string ValidCharacters
{
get { return "0123456789xyz"; }
}
private string ConvertSingleBaseNumber(int remainder)
{
return ValidCharacters[remainder].ToString();
}
private int BaseNumber
{
get
{
return ValidCharacters.Length;
}
}
}
public class BinaryConverter : Converter
{
protected override string ValidCharacters
{
get
{
return "01";
}
}
}
public class OctalConverter : Converter
{
protected override string ValidCharacters
{
get
{
return "01234567";
}
}
}
public class HexConverter : Converter
{
protected override string ValidCharacters
{
get
{
return "0123456789abcdef";
}
}
}
Did you like this challenge? Maybe you found it easy? Were always looking for talented people to join our growing team. Take a look at what we do at http://www.thycoticsolutions.com/careers.html If you feel you have what it takes to work at Thycotic – submit a cover letter, resume, and solution to this problem to tddjobs@thycotic.com
Warm Turkey

July 22th 2010 | Jimmy Bosse
Warm Turkey
In a recent post, “Cold Turkey”, my colleague Kevin Jones challenged developers to “try writing code for a day, even an hour, using notepad. Not Notepad2 or notepad++. Though you can cheat and use MSBuild to compile your solution. It might just change your idea of what good code is.”
I say poppycock!
Imagine being a patient about to go into surgery when your doctor explains that he will be removing your appendix without anesthesia or a scalpel. Instead, he’ll be getting back to his roots and will be using a knife and some leeches to demonstrate what good surgery is. Utter nonsense.
Tools like IntelliSense do not write good or bad code—they are used by good or bad developers. Should I be aware of the methods of the System.IO.File class? Absolutely. Should I be able to recall each of its 56 methods on demand? Absolutely not. Can I tell you the parameter types of each of the three overloaded signatures for its Open method? Nope again. Knowing this information by rote does not make me a better developer. It’s also a waste of my time, and to our clients (if you are a consultant like many of us developers) time is money.
Tools like IntelliSense are about efficiency, and to argue that it rots the brain is to argue that we should launch the space shuttle on the minds of brilliant engineers who insist on using the abacus.
Tools help good programmers deliver good software faster. I couldn’t write a post about essential tools without discussing ReSharper. I have on more than one occasion stated that, “I will never use Visual Studio again without ReSharper, ever.” I stand by that statement. I even saw a recent tweet by someone stating that they could do more coding with one hand and ReSharper than with two hands without it.
True, if you’re a bad developer, the tools are going to make you better—at writing bad code. There’s not much I can do about that.
Cold Turkey

March 23rd | 2010
Cold Turkey
Recently I went on vacation. Being the developer that I am, this didn’t keep me away from doing a little coding. I was “forbidden” from bringing a work laptop, but I brought my personal netbook which had Office, Windows, iTunes, and a messaging client. One day I was asked to write a system tray application for someone who was moving from Windows XP to Windows 7, which was missing a feature from XP. It was easy enough to write, but I didn’t have my normal tool belt with me. All I was armed with was notepad, and the Visual Basic .NET Compiler. I’d be writing an application without my faithful tools. Cold Turkey.
The first thing I did was build a mini IDE: basically, a batch script that would compile my file and add all the assembly references. My only reference was MSDN which is rather slow in Belarus. I eventually ended up writing another program that used reflection to dump the classes of namespaces and the public members of classes.
This lead me to a blog post I read more than a year ago, “Intellisense rots the brain”. That got me thinking: Code quality should not be determined by your toolset. I thought back to my post on extension methods . My argument against extension methods was that you can’t tell the difference between an extension method and an instance method without the help of an IDE. Now the argument might be, “Kevin, you were using no tools at all. Isn’t that an unlikely case? I’ll always have my tools.” But then why strive to write good code at all? A tool shouldn’t be telling you how to write code.
So, I propose a challenge. Try writing code for a day, even an hour, using notepad. Not Notepad2 or notepad++. Though you can cheat and use MSBuild to compile your solution. It might just change your idea of what good code is.
The Danger of Single Responsibility in Programming Continued

October 16th 2009 | David Cooksey
The Dangers of Single Responsibility in Programming Continued
The Dangers of Single Responsibility, Cont.
Doug Rohrer responded to my initial post on this topic with a good refactoring of the classes involved in a manner similar to the Strategy pattern. I agree with many of his points—the hypothetical developer certainly chose the wrong responsibilities; misunderstood the Single Responsibility Principle; and generally made the code a mess. That said, I believe that SRP is most definitely dangerous, not because of what happens when it is used correctly, but because of how easy it is to get it wrong. Misapplying the SRP can result in code that makes God objects look easy to maintain.
For clarity’s sake, I’ll go one step further—it is easy to misunderstand the sentence “A class should have only one reason to change” as a literal commandment to be applied at the line or method level. This results in disaster. One common example of how the SRP is misunderstood can be seen in this thread, where the poster asks if the SRP means that each class can have only one method. Luckily the poster received a good informative answer, but that is not the case for all developers learning about the SRP.
Here is an example of code modifications I have seen motivated by a desire to apply the SRP.
BEFORE
public class Check { private readonly IDataProvider _dataProvider; public Check(IDataProvider dataProvider) { _dataProvider = dataProvider; } public bool Run() { IBusinessObject data = _dataProvider.Get(); if (data.Condition1 && data.Condition2) { string message = string.Format("Check failed, {0} {1}", data.Property1, data.Property2); throw new Exception(message); } return data.Property3 != data.Property4; } }
AFTER
public class Class { private readonly IDataProvider _dataProvider; private readonly ICheckErrorMessageProvider _checkErrorMessageProvider; public Check(IDataProvider dataProvider, ICheckErrorMessageProvider checkErrorMessageProvider) { _dataProvider = dataProvider; _checkErrorMessageProvider = checkErrorMessageProvider; } public bool Run() { IBusinessObject data = _dataProvider.Get(); if (data.Condition1 && data.Condition2) { string message = _checkErrorMessageProvider.GetErrorMessage(data); throw new Exception(message); } return data.Property3 != data.Property4; } } public class CheckErrorMessageProvider : ICheckErrorMessageProvider { public string GetErrorMessage(IBusinessObject data) { return string.Format("Check failed, {0} {1}", data.Property1, data.Property2); } }
Here, the developer asked the SRP question “Does this class have only one reason to change?” and got the answer “No, it could change because the formatted text could change, or because the logic could change”, and refactored the String.format out into its own provider. While harmless on the surface, this artificial separation of concerns does not add any value. The new class is so specific that it cannot be used anywhere else. In addition, the developer is likely to forget the CheckErrorMessageProvider name almost immediately, so if a text change is required he will most likely go to the Check class first, and then go the extra level down into the string provider in order to make the text change. In other words, the complexity of the code was increased for no benefit.
I believe that after correctness, simplicity is the most important programming principle. Simpler code is easier to understand when first read; easier to remember; easier to test; easier to refactor; and easier to add features to. Anything that adds complexity makes all of these tasks harder, especially on larger projects with many non-trivial sub-systems. Applying single responsibility at the line or method level diffuses business logic into a cloud of tiny classes that do next-to-nothing individually, and thoroughly obscure the logic they represent.
In conclusion, yes, the SRP is not dangerous when applied correctly. But then, most things are dangerous because of what happens when they are misused, and the Single Responsibility Principle is no exception. Handle with care!
David Cooksey is a Senior .NET Consultant at Thycotic Software, an agile software services and product development company based in Washington DC. Secret Server is our flagship password management software product.
The Bridge Pattern – When a single class hierarchy is not enough

September 10th 2009 | David Cooksey
The Bridge Pattern – When a single class hierarchy is not enough
The bridge pattern allows both the implementation and the abstraction of a programming scenario to vary. Let’s take a look at a specific use case in order to understand the benefit the bridge pattern provides.
Imagine we are writing a top-down scrolling action game. The player will be able to choose from a variety of vehicles and will be up against a maze full of passive and active obstacles. In order to increase replayability, the vehicles available will include tanks, helicopters, and motorcycles, with expansions planned to include additional vehicles. Tanks will have a cannon and a machine gun, helicopters will have missiles and a machine gun, while the motorcycle will allow the player to throw grenades and wield a samurai sword. Throughout the course of the game, upgrades will alter the abilities of each weapon (better missiles, more ammo for the machine gun, swords of awesome lethality, etc).
So, how do we plan our class structure in such a way that we can treat each vehicle the same at the high level, while allowing for flexibility in both the selected vehicle and the weapons it is currently using?
Ideally our top-level implementation should allow us to do something like PlayerVehicle.FireWeapon1() without concerning ourselves with the specific vehicle or weapon the player is using.
The bridge pattern gives us the flexibility we need.
First we create a vehicle base class.
public abstract class Vehicle
{
public IWeapon weapon1;
public IWeapon weapon2;
public abstract void Move();
public void ShootWeapon1()
{
weapon1.Fire();
}
public void ShootWeapon2()
{
weapon2.Fire();
}
}
By leveraging the “has-a” relationship between a vehicle and its weapons we allow the weapons to vary. The exposed ShootWeapon1 and ShootWeapon2 functions perform the same function in this case as calling .weapon1.Fire() on the vehicle itself. By making Vehicle an abstract class we leave all details of movement up to its concrete implementations.
public class Tank : Vehicle
{
public Tank()
{
weapon1 = new SimpleCannon();
weapon2 = new BasicMachineGun();
}
public override void Move()
{
// Check for physical obstacle, if no obstacle move the tank.
}
}
public class Helicopter : Vehicle
{
public Helicopter()
{
weapon1 = new AirToAirMissile();
weapon2 = new BasicMachineGun();
}
public override void Move()
{
// Move helicopter
}
}
As a result, both the Tank and Helicopter listed above will work as the vehicle in the following code sample.
Vehicle vehicle = new Tank(); vehicle.Move(); vehicle.ShootWeapon1(); vehicle.ShootWeapon2();
The bridge pattern allows us to change vehicles and weapons independently. This concept is extensible to as many degrees as are necessary to allow independent variation. For example, a futuristic update to the game might add varying kinds of passive or reactive shields to the vehicles. No problem, just create an IShield interface and add it to the Vehicle abstract class.
Essentially, the bridge pattern is just an implementation of a recognition that two concepts exist in a “has-a” relationship and need to vary independently. As such, it provides the required flexibility with no drawback other than a small increase in the complexity of the class hierarchy.
David Cooksey is a Senior .NET Consultant at Thycotic Software, an agile software services and product development company based in Washington DC. Secret Server is our flagship password management software product.
The Dangers of Single Responsibility in Programming

October 16th 2009 | David Cooksey
The Dangers of Single Responsibility in Programming
The principle of single responsibility is an important and well-known object-oriented guideline. Systems designed without any consideration for this principle often result in the God-object anti-pattern, with predictably unfortunate results. However, taking single responsibility too far also results in code that is difficult to read and maintain.
Let’s take a look at a possible system built for a company that sells a wide variety of products. This system was originally built around a Product object, and over the years the product object has continued to grow and acquire responsibility as new features were added to the system. The IProduct interface now looks like this:
public interface IProduct
{
int Id { get; set; }
string Name { get; set; }
int TypeId { get; set; }
DateTime AddedDate { get; set; }
decimal Cost { get; set; }
decimal BasePrice { get; set; }
decimal SalesPrice();
decimal Price(int customerId);
decimal Discount(int customerId);
decimal GetShippingCharge(int customerId, string stateCode);
int GetMinQuantity(int customerId);
DateTime GetNumAvailable(int customerId);
}
This company has built its business model on special services for frequent customers, including special discounts, shipping rates, lower base prices, etc. Some customers receive lower prices on specific products in return for promises to order at least a certain quantity each time. The net result is that the full cost depends on who and where the customer is as much as it depends on the product itself.
Now imagine that a developer on this project has read about the fascinating new concept of single responsibility and decides that IProduct is responsible for too much. In fact, it’s responsible for everything. So he creates a PriceProvider that contains a GetPrice method as shown below, moving the logic of the method directly from the Product class to the PriceProvider.
public decimal GetPrice(IProduct product, int customerId)
{
decimal price = product.BasePrice;
ICustomer customer = GetCustomer(customerId);
if (customer.GoldLevelCustomer)
{
price = price * (1 - GetGoldLevelDiscount());
}
if (ProductIsOnSale() && !FixedDiscountAgreementExists(customer, product))
{
decimal salePrice = product.SalesPrice();
if (salePrice < price)
{
price = salePrice;
}
}
return price;
}
So far, so good. The logic is adequately complex and involves enough dependencies that it should probably exist in its own class. Initially, our developer is happy. However, as he continues to look at this method, he decides that it is doing a lot more than it should. After all, any number of business logic changes could make this class change, and a class should have only one reason to change, right? So he rolls up his sleeves and gets to work, eventually producing the following:
public decimal GetPrice(IProduct product, int customerId)
{
decimal price = product.BasePrice;
ICustomer customer = GetCustomer(customerId);
if (goldLevelDeterminator.IsGoldLevelCustomer(customer))
{
price = price * (1 - goldLevelDiscountProvider(product));
}
if (saleProvider.IsOnSale(product) && !fixedDiscountAgreementProvider.AgreementExists(customer, product))
{
decimal salePrice = product.SalesPrice();
if (useSalesPriceInsteadOfPriceDeterminator.UseSalesPrice(price, salePrice))
{
price = salePrice;
}
}
return price;
}
The goldLevelDiscountProvider, saleProvider, and fixedDiscountAgreementProvider probably refer to their own tables, given the code structure shown, so it makes sense to split them out. However, the goldLevelDeterminator is literally calling the GoldLevelCustomer property on customer and returning it, and the useSalesPriceInsteadOfPriceDeterminator is simply comparing the sales price to the price.
These latter two changes are examples of implementing the principle of single responsibility at a level of granularity below that of the business requirements. It is possible that the company’s needs will change in such a way that these classes will become necessary, but they do not need their own class unless and until their complexity warrants it. The creation of two determinator classes here implies that significant logic is involved in determining whether a customer is a gold level customer, or whether the sales price should be used.
Unnecessary classes like the two mentioned above cause a number of problems. Firstly, they increase the complexity of the code. A developer reading through this class for the first time will need to open both determinators up and mentally piece their contents back into the main function instead of simply reading them. Secondly, their existence as independent entities implies that they are reusable. However, their creation was solely based on a desire to separate method calls into their own class, not a thorough investigation of how the class meshes with the rest of the classes in the project.. Quite often, classes like these are not reused and in fact their functionality is duplicated in other tiny classes used in other places.
In short, when you’re designing or refactoring systems, plan your class structure around business needs, not logical decision points. A method with two if statements should not automatically be considered as having two reasons to change. After all, those two if statements may represent a single business concept.
David Cooksey is a Senior .NET Consultant at Thycotic Software, an agile software services and product development company based in Washington DC. Secret Server is our flagship password management software product.
Bringing Plausible Deniability to Development: the Strategy Pattern

July 30th 2009 | David Cooksey
Bringing Plausible Deniability to Development: the Strategy Pattern
If the template pattern is a benevolent dictator the strategy pattern is a politician concerned with plausible deniability: Don’t tell me the details, just do it. The strategy is defined solely in terms of its inputs and outputs.
Let’s say you are writing a program that cuts checks for employees. The code that handles the physical printing of the checks is complete, all that remains is determining how much to print on the check for each person. The company contains both salaried and hourly employees in addition to salesmen whose pay is based on commissions. Also, the company sends out holiday checks to all employees at various times of the year based on how the company performed recently.
You want to be flexible, so your payment generator is designed as a windows service that polls a PaymentRequest table periodically. It then examines the type of payment to determine how the amount should be calculated. The next step is to write and organize implementations of the different ways to calculate payments.
The design should be flexible enough that it makes adding new payment types as simple as possible, while also providing as much flexibility as possible with respect to implementation details. You don’t want to mandate that a particular step in calculation occur, because you don’t know what future payment types might require.
This is where the strategy pattern comes into play. You can use a simple interface that defines your payment strategy to streamline your code and cut down on the number of decision points. All you really need is a block of code that looks at the payment record and decides what strategy to use. The other code should be the same regardless of the payment type. Here is some pseudo code for what this would look like:
public interface IPaymentStrategy { double CalculateAmount(IPaymentRequest paymentRequest); } public class PaymentGenerator { public void LookForPaymentRequests() { IPaymentRequest[] paymentRequests= GetNewPaymentRequests(); foreach (IPaymentRequest paymentRequest in paymentRequests) { Process(paymentRequest); } } private void Process(IPaymentRequest request) { IPaymentStrategy strategy; switch (request.PaymentType) { case 1: strategy = new HourlyPayment(); break; case 2: strategy = new SalariedPayment(); break; case 3: strategy = new CommissionPayment(); break; case 4: strategy = new HolidayPayment(); break; default: strategy = new FlatPayment(); break; } double amount = strategy.CalculateAmount(request); WriteCheck(amount); } }
IPaymentStrategy defines a simple interface that accepts an IPaymentRequest and returns the amount calculated. The PaymentGenerator pulls in new payment requests from a table. It picks the appropriate payment calculation method based on the payment type Id and uses it to generate the correct payment amount.
If a new payment type is added, it requires no code restructuring other than the creation of a new class that inherits from IPaymentStrategy, a new case block, and a new row in the PaymentType table.
This code structure places no restrictions at all on the implementation details of the individual payment types. If a lot of code is shared among the payment types, inheritance, a common dependency, or any other method can be used to reduce or eliminate code duplication entirely at the discretion of the programmer.
This makes it easier to ignore the gritty details of payment calculation which a more strict pattern such as the Template Pattern would force you to consider.
Flexible
Maintainable
Plausibly Deniable
The Strategy Pattern.
The Template Pattern A Benevolent Dictator

July 22nd 2009 | Ben Yoder
The Template Pattern: A Benevolent Dictator
The Template Pattern is unique because of the level of control maintained at the top level. An abstract class controls the steps and the possible default implementations of the algorithm, but it’s kind enough to let its subclasses modify the behavior in pre-defined methods.
Similar design patterns, and specifically the Strategy pattern, prescribe the encapsulation of individual algorithms and logic into single classes that can be called independently.
The Template Pattern is useful for avoiding code duplication and keeping code maintainable. When you copy and paste the same—or very similar—logic across code you should encapsulate that code to prevent drift. This is when a benevolent dictator class helps clean up your code.
Drift may occur due to a change in requirements. Imagine you are working on an application that has a requirement to create an audit record whenever a user edits information on a form. During version 1.0, you created an AuditLogger class that simply writes a record to the database.
public class AuditLogger { public void InsertAuditRecord(){...} }
However, for version 2.0 you have this requirement: whenever a regular user edits information on certain forms, an email should be sent to a system admin. Additionally system admins, due to their higher level of access, require separate security audit records to be created elsewhere. As quick fix, you could add methods called EmailNotification() and InsertAdminAuditRecord() to AuditLogger which can be called from the Save() method on the forms depending on the user type.
But after that’s been wrapped up, requirements change and a new power user type has been added to the system. This user type requires a single audit record, but this time there is no need to send an email notifying administrators. You could create a mess on all your forms by adding methods to AuditLogger and making decisions on the form, or you could encapsulate what differs between the auditing logic per user-type, recognizing that requirements may change again.
In this case, AuditLogger currently looks like:
public class AuditLogger { public void InsertAuditRecord(){...} public void InsertAdminAuditRecord(){...} public void EmailNotification(){...} }
In refactoring this to a Template Pattern, you’ll notice that InsertAuditRecord() and InsertAdminAuditRecord() are essentially the same logical step. By default, users should write a standard audit record, but administrators should write a special audit record. So in creating your Template class, you should define just a single virtual InsertAuditRecord() method that inserts a standard record and a virtual Notify() method that sends emails by default.
public abstract class AuditLogger { public void Audit() { InsertAuditRecord(); Notify(); } public virtual void InsertAuditRecord() { Console.WriteLine("Auditing User..."); } public virtual void Notify() { Console.WriteLine("Emailing Admin..."); } }
Next, create concrete implementations to define specific implementations of the methods, where needed. Your standard AuditLogger will simply be a concrete that extends AuditLogger with the default implementations, but your Admin and PowerUser loggers will override separate methods.
public class StandardAuditLogger : AuditLogger { } public class AdminAuditLogger : AuditLogger { public override void InsertAuditRecord() { Console.WriteLine("Auditing Admin User..."); } public override void Notify() { return; } } public class PowerUserAuditLogger : AuditLogger { public override void Notify() { return; } }
The advantage of this is as requirements change, your specific logic is encapsulated, but you can continue to define default implementations. So if everyone except admins needs to send email notifications, you could pull the Notify() override out of the PowerUserAuditLogger and be done. And if another step was to be added to the audit process, a default method could be defined and called in the template without having to touch anything else.
The Template pattern becomes less useful the more the algorithms diverge. If you find yourself overriding every single method of the abstract Template class and adding in a lot of hook methods to control the flow from the subclasses, then the Template Pattern may not be your best choice. But if it looks like your code could use some iron fisted governing, let the Template call all the shots—and see how much simpler maintenance becomes.
StrictMock vs. DynamicMock: What are You Testing Here Anyway?

July 16th 2009 | Jimmy Bosse
StrictMock vs. DynamicMock: What are You Testing Here Anyway?
Here at Thycotic, we are TDD enthusiasts and pair developers. Test Driven Development and Pair Programming go together like chocolate and peanut butter, especially when you tackle a brand new piece of functionality and practice some green-field Ping-Pong programming.
For those unfamiliar with the concept of Ping-Pong programming, it’s a fun way to develop a new piece of business logic when you are not sure what the best method of implementation will be.
To start, one of you writes a failing test. The other makes the test pass, and then writes the next failing test (refactoring as needed). You make that test pass and write a new failing test. The goal of the session is to write the smallest amount of code possible, then try to write a test that effectively tests the desired functionality while providing a challenge to your pair. The session is easy at first, but as the tests move toward satisfying the more complicated requirements of the business, the exercise becomes more challenging.
Once your code becomes suitably complex, you’ll start to have multiple classes with dependencies—and with these dependencies come mock tests.
Then you have to decide: StrictMock or DynamicMock?
The problem with Strict Mocks is that you are required to set up your entire mock dependency far beyond the scope of the subject/system under test (SUT).
Take the following example.
[Test] public virtual void ShouldSubscribeToViewEventWhenConstructed() { MockRepository mocks = new MockRepository(); IView mockIView = mock.StrictMock<IView>(); mockView.SomeEvent += delegate{}; LastCall.Constraints(Is.NotNull()); mocks.ReplayAll(); IPresenter presenter = new Presenter(mockView); mocks.VerifyAll(); }
To implement a presenter:
public class Presenter : IPresenter { private IView _view; public Presenter(IView view) { _view = view; BindToEventsOn(_view); } private void BindToEventsOn(_view) { _view.SomeEvent += SomeEventHandler; } private void SomeEventHandler() { //Do something… } }
The test is now green because you’ve subscribed to the event. But now that you’ve bound to the view in your constructor, you must always expect a call in your test whenever you mock IView with a StrictMock. This will make your tests verbose and it will be difficult to determine the actual SUT in each test.
Another issue is this: When you use a StrictMock you are essentially telling your pair what to program. Let’s say you and your pair sit down to create a calculator business object that must be able to add numbers together.
Your pair writes the following test:
[Test] public virtual void ShouldReturnFourWhenGivenThreeAndOne() { int firstNumber = 3; int secondNumber = 1; int expectedSum = 4; MockRepository mocks = new MockRepository(); IAdder mockIAdder = mock.StrictMock<IAdder>(); IAdderFactory mockIAdderFactory = mock.StrictMock<IAdderFactory>(); Expect.Call(mockIAdderFactory.Create()).Return(mockIAdder); Expect.Call(mockIAdder.Add(firstNumber, secondNumber)).Return(4); mocks.ReplayAll(); ICalculator calculator = new Calculator(mockIAdderFactory); int result = calculator.Add(firstNumber, secondNumber); mocks.VerifyAll(); Assert.AreEqual(expectedSum, result); }
Well, there’s nothing to think about here is there? If this is the way you want to write tests, invest some time and write a tool that will parse your test and create your business object for you. The test tells you “use the factory, create an adder, call the add method on the adder and return the result. Where’s the fun in that? What are you actually testing? Does it really matter how the calculator does what it needs to do?
Actually, I think the above test could be a good one if it was created three days into the calculator object—when you were refactoring the different pieces of the calculator into distinct service objects.
But right now, all you need is a calculator that can add two numbers together:
[Test] public virtual void ShouldReturnFourWhenGivenThreeAndOne() { ICaclulator calculator = new Calculator(); Assert.AreEqual(4, calculator.Add(3, 1)); }
This should be your first failing test. I don’t care how you add it, but by golly you’d better give me back 4 when I give you 3 and 1.
I love DynamicMock because I am a believer that a test should test a very specific piece of code. Recently, however, I came across this poignant counterpoint that shattered my DynamicMock utopia. I had written tests and an object that looked something like this:
[Test] public virtual void ShouldReturnTrueIfBigIsTrueAndBadIsFalse() { MockRepository mocks = new MockRepository(); IDataWrapper mockIDataWrapper = mock.DynamicMock<IDataWrapper>(); SetupResult.For(mockIDataWrapper.IsBig).Return(true); SetupResult.For(mockIDataWrapper.IsBad).Return(false); mocks.ReplayAll(); IDad dad = new Dad(); Bool result = dad.IsABigBad(mockIDataWrapper); mocks.VerifyAll(); Assert.IsTrue(result); } [Test] public virtual void ShouldReturnTrueIfBigIsFalseAndBadIsTrue() { MockRepository mocks = new MockRepository(); IDataWrapper mockIDataWrapper = mock.DynamicMock<IDataWrapper>(); SetupResult.For(mockIDataWrapper.IsBig).Return(false); SetupResult.For(mockIDataWrapper.IsBad).Return(true); mocks.ReplayAll(); IDad dad = new Dad(); Bool result = dad.IsABigBad(mockIDataWrapper); mocks.VerifyAll(); Assert.IsTrue(result); } [Test] public virtual void ShouldReturnFalseIfBigIsFalseAndBadIsFalse() { MockRepository mocks = new MockRepository(); IDataWrapper mockIDataWrapper = mock.DynamicMock<IDataWrapper>(); SetupResult.For(mockIDataWrapper.IsBig).Return(false); SetupResult.For(mockIDataWrapper.IsBad).Return(false); mocks.ReplayAll(); IDad dad = new Dad(); Bool result = dad.IsABigBad(mockIDataWrapper); mocks.VerifyAll(); Assert.IsFalse(result); } public interface IDataWrapper { public IsBig { get; } public IsBad { get; } } public class Dad : IDad { public virtual bool IsABigBad(IDataWrapper dataWrapper) { return dataWrapper.IsBig || dataWrapper.IsBad; } }
My test was green and I was happy, but my pair informed me that a bug could be introduced accidentally and no one might ever notice:
public interface IDataWrapper { public IsBig { get; } public IsBad { get; } public IsFat { get; } } public class Dad : IDad { public virtual bool IsABigBad(IDataWrapper dataWrapper) { return dataWrapper.IsBig || dataWrapper.IsBad || dataWrapper.IsFat; } }
Because a DynamicMock will not throw an exception for unexpectedly calling IsFat and will return false as the default for the bool base type, my tests will all remain green. But in production my code might not work as expected.
There is seldom a single solution that works in every situation. I have learned to find the proper place for both Dynamic and Strict Mocks in my TDD toolbox and hope that this encourages you to think more deeply about your own toolbox.

