- Interfaces suddenly seem like a good idea.
- You stop using singletons and static methods.
- Private makes less sense than it used to.
- You pass dependencies in the constructor (the so called 'fat constructor')
- Smaller methods are the norm.
- You read tests before the code; it better explains the intention.
- Usability trumps cleverness.
- Premature performance optimisation is bad (YAGNI)...
- ... but test performance is crucial.
- Dependency is bad; you avoid 'God classes' and 'global hubs'.
- 'Clever' is dead. 'Clever' is hard to refactor. 'Clever' is hard to isolate, hard to internalize, hard to phrase in tests.
- Your IDE is only good if it allows you to do quick write/build/test cycles.
Thursday, August 30, 2007
Testing Will Challenge Your Conventions
Tuesday, August 07, 2007
Masters, Journeymen, and Apprentices
Monday, August 06, 2007
The Castle Project's Windsor Container and why I might need it.
SimpleReporter reporter = new SimpleReporter(); reporter.SendReport();And the SendReport method might look like this:
public void SendReport()
{
ReportBuilder builder = new ReportBuilder();
Email email = builder.CreateReport();
EmailSender sender = new EmailSender();
sender.Send(email);
}
It creates uses a class called ReportBuilder to create an email report and then another class called EmailSender to send it.
This is the kind of thing I used to write before I got into TDD. It works, but in order to test it I've got start up my application and use the UI to create and send a report. I then have to check my emails to see if the report has arrived. I'm not testing just my SimpleReporter class, I'm testing the SimpleReporter, the ReportBuilder and anything it relies on, the EmailSender, my SMTP server, my email client, my application's UI and probably a relational database and my data access layer. In short I'm testing a large chunk of my application and infrastructure. If something goes wrong I'm into a serious debugging session trying to work out why my Email hasn't arrived. I can't automate this test easily so I'm not going to do it very often and if a bug is introduced by a change to some other part of the system I'm not going to notice it immediately.
Now I would use inversion of control and dependency injection with a mock object framework like NMock to just test my Reporter and nothing else. I blogged about NMock a while back. Here's the new Reporter class, note how I pass a report builder and emailSender in the contructor and how I'm only referencing interfaces not concrete classes.
public class Reporter
{
IReportBuilder _reportBuilder;
IEmailSender _emailSender;
public Reporter(IReportBuilder reportBuilder, IEmailSender emailSender)
{
_reportBuilder = reportBuilder;
_emailSender = emailSender;
}
public void SendReport()
{
Email email = _reportBuilder.CreateReport();
_emailSender.Send(email);
}
}
And here's its NUnit test.
[Test]
public void ReporterTest()
{
string theText = "Hello, I'm the report!";
Mockery mocks = new Mockery();
IReportBuilder reportBuilder = mocks.NewMock();
IEmailSender emailSender = mocks.NewMock();
Email email = new Email(theText);
Expect.Once.On(reportBuilder).Method("CreateReport").Will(Return.Value(email));
Expect.Once.On(emailSender).Method("Send").With(email);
Reporter reporter = new Reporter(reportBuilder, emailSender);
reporter.SendReport();
mocks.VerifyAllExpectationsHaveBeenMet();
}
NMock provides me with mock object instances to pass to the Reporter class' constructor. I don't even need to have writen concrete implementations of ReportBuilder or EmailSender at this stage. I can test that the Reporter class does the correct thing with reportBuilder and emailSender and I'm not testing anything else about the application at this stage. Most importantly this is an automated test that can be run in an instant along with every other automated test for my application. If I make a change that breaks Reporter I'll find out instantly.
Discovering TDD has made me a much better and productive developer. Not only are my apps more robust, they are also better architected because testing forces you to do good software design.
However, I've noticed a rather unfortunate side effect of doing things this way, in the finished product we'll have to provide concrete instances of EmailSender and ReportBuilder.
ReportBuilder reportBuilder = new ReportBuilder(); EmailSender emailSender = new EmailSender(); Reporter reporter = new Reporter(reportBuilder, emailSender);Now that doesn't look too bad, but this is a really really simple example. In a real application there could be hundreds of classes that need to be knitted together like this and it becomes a complex piece of code, not only to maintain, but to decide where in your app you should do it because the class(es) that do the knitting have to know about everything. An alternative that I experimented with was to have a default contructor for each class that provided the concrete instances alongside the one that injected the dependency, so our Reporter class would now look like this:
public class Reporter
{
IReportBuilder _reportBuilder;
IEmailSender _emailSender;
public Reporter(IReportBuilder reportBuilder, IEmailSender emailSender)
{
_reportBuilder = reportBuilder;
_emailSender = emailSender;
}
public Reporter()
{
_reportBuilder = new ReportBuilder();
_emailSender = new EmailSender();
}
public void SendReport()
{
Email email = _reportBuilder.CreateReport();
_emailSender.Send(email);
}
}
But this feels really dirty. I've now got a direct dependency from the client back to the server thus breaking the Inversion of Control priciple. I can't easily use a different kind of reportBuilder or emailSender without recompiling the Reporter.
Another possibility would be to use the provider pattern that's a core part of .NET, but it's not really intended for this scenario and to use it for every service class in your application would be total overkill.
Of course the .NET framework also provides a component architecture, but it's also quite heavy for what we want here since it requires that each component implement IComponent and provide the plumbing to publish its service.
What I need is something that will magically provide concrete instances of the interfaces that each class requires without me having to maintain a vast wiring exercise somewhere in the startup code of my application. Enter Windsor! Here's how you could use it with our Reporter example:
WindsorContainer container = new WindsorContainer();
container.AddComponent("reportBuilder", typeof(IReportBuilder), typeof(ReportBuilder));
container.AddComponent("emailSender", typeof(IEmailSender), typeof(EmailSender));
container.AddComponent("reporter", typeof(Reporter));
Reporter reporter = container.Resolve<Reporter>();
reporter.SendReport();
You create a new container instance and register each interface in your application along with the concrete class that you wish to represent it. You can get a new instance of your class by using the Resolve method. Here we get an instance of Reporter and call SendReport(). Nowhere in the code did we have to explicitly pass instances of ReportBuilder or EmailSender to Reporter or even know that Reporter required those instances. Windsor also allows you to describe your components in a configuration file rather than hard coding all those AddComponent statements.
You can see the benefits. Say I wanted to write another class that needed to use IEmailSender. I would just write that class with an IEmailSender as one of its constructor parameters and add it to the container. The container would then automatically provide an IEmailSender instance. In fact, by default it would provide the same IEmailSender instance that it supplies to any other class that required this interface, although that behavior can be modified. Now, say I want to use ExchangeEmailSender rather than my existing EmailSender throughout my application, I only have to change the one configuration entry (or line of setup code) to do it, rather than searching through my application looking for every place where an IEmailSender is passed as a constructor parameter.
If you want to pass ExchangeEmailSender to some components and EmailSender to others, then that can be configured too.
There's much more to the Windsor container than just the inversion of control container, it also provides Aspect Oriented Programming features, automatically providing interface proxies so that you can intercept method calls and provide cross cutting services. This opens up all kinds of exciting possibilities, the obvious ones being logging, auditing, transactions and security, and I hope to blog about it some more in the future.
I haven't used any of this in anger yet so I can't say what the drawbacks might be, but I can imagine that maintaining the component config file for a large project could get a bit tiresome. The advantages are obvious. It really is lightweight component based development where you provide service components that can be consumed by other components without ever having to have any direct dependencies. I'd really like to see it used in a major application.
It also begs the question: shouldn't this stuff be provided by your programming language? The CLR has the potential to do a lot of this quite easily. It already knows about all the types that an application requires, it knows about interface implementation, it can intercept method calls. It's easy to imagine a future version of C# where component based programming is provided out of the box.
Thursday, July 26, 2007
Jeremy Miller's build your own CAB series
Thursday, July 19, 2007
How to structure Visual Studio solutions
Wednesday, July 18, 2007
Serializing lots of different objects into a single file
using System;
using System.IO;
using NUnit.Framework;
namespace SerializerTest
{
[TestFixture]
public class SerializerTests
{
[Test]
public void SerializeLotsOfObjects()
{
// get the path for the file we're going to serialize into
string path = @"c:\SerializedObjects.ser";
// create the file we're going to use
using(File.Create(path)){}
// create some animals
for(int i=0; i<10; i++)
{
Animal animal;
string name = string.Format("Animal_{0}", i);
int age = 5+i;
// make even numbers dogs, odd numbers cats
if((i % 2) == 0)
{
bool trained = ((i % 3) == 0);
animal = new Dog(name, age, trained);
}
else
{
int lives = 9-i;
animal = new Cat(name, age, lives);
}
// write each animal to a file
WriteAnimalToFile(path, animal);
}
// read the animals back one by one.
long position = 0;
while(true)
{
Animal animal = ReadAnimalFromFile(path, ref position);
if(animal == null) break;
Console.WriteLine(animal.Introduce());
}
}
private void WriteAnimalToFile(string path, Animal animal)
{
// create a new formatter instance
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
// open a filestream
using(FileStream stream = new FileStream(path, FileMode.Append, FileAccess.Write))
{
formatter.Serialize(stream, animal);
}
}
private Animal ReadAnimalFromFile(string path, ref long position)
{
// create a new formatter instance
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
// read the animal as position back
Animal animal = null;
using(FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
if(position < stream.Length)
{
stream.Seek(position, SeekOrigin.Begin);
animal = (Animal)formatter.Deserialize(stream);
position = stream.Position;
}
}
return animal;
}
}
[Serializable]
public abstract class Animal
{
string _name;
int _age;
public Animal(string name, int age)
{
_name = name;
_age = age;
}
public abstract string Introduce();
public string Name{ get { return _name; } }
public int Age{ get { return _age; } }
}
[Serializable]
public class Dog : Animal
{
bool _isTrained;
public Dog(string name, int age, bool isTrained) : base(name, age)
{
_isTrained = isTrained;
}
public override string Introduce()
{
return string.Format("I am a dog called {0}, age {1}, {2}trained.", Name, Age,
(_isTrained ? "": "not "));
}
public bool IsTrained{ get { return _isTrained; } }
}
[Serializable]
public class Cat : Animal
{
int _lives;
public Cat(string name, int age, int lives) : base(name, age)
{
_lives = lives;
}
public override string Introduce()
{
return string.Format("I am a cat called {0}, age {1}, with {2} lives",
Name, Age, _lives);
}
public int Lives{ get { return _lives; } }
}
}
The output should look like this:
I am a dog called Animal_0, age 5, trained. I am a cat called Animal_1, age 6, with 8 lives I am a dog called Animal_2, age 7, not trained. I am a cat called Animal_3, age 8, with 6 lives I am a dog called Animal_4, age 9, not trained. I am a cat called Animal_5, age 10, with 4 lives I am a dog called Animal_6, age 11, trained. I am a cat called Animal_7, age 12, with 2 lives I am a dog called Animal_8, age 13, not trained. I am a cat called Animal_9, age 14, with 0 livesNote that you can't do this trick with the XML Serializer since we have to specify the type we're expecting. Also a single file with multiple XML documents would be malformed.
Monday, June 18, 2007
Four ways of doing a test with a result.
RejectResult result = email.IsRejected;
if(result.Rejected)
{
DoSomethingWith(result.Reason);
}
But I don't really like this because the if statement looks like it's saying "if result is rejected". The result's not rejected the email is. I'd like the code to say "if email is rejected", so how about this, using out parameters:
Reason reason;
if(email.IsRejected(out reason))
{
DoSomethingWith(reason);
}
OK, this is a bit better, but now it's saying "if email is rejected reason", leaving out 'out' which is just syntax, which still isn't what I really want. Also there's a practical problem here that my favorite unit test mocking framework NMock2 makes a real meal out of out parameters. OK, so how about this one:
if(email.IsRejected)
{
DoSomethingWith(email.RejectReason);
}
The if statement reads nicely now, but there's a serious practical problem in that we're not expecting email's state to change between testing for rejection and examining the RejectReason, this would be especially serious if email wasn't thread safe but even if it is it's relying on convention; what does RejectReason mean before IsRejected has been tested? Not wrapping the IsRejected and RejectReason in a single method of email is just plain bad. My favorite solution was suggested by NMock2. I really like its conversational style, 'Expect.Once.On(mymock).With(myparam).Will(Return.Value(myreturnval));', so how about this:
Reason reason;
if(email.IsRejected.For(out reason))
{
DoSomethingWith(reason);
}
It reads really nicely "if email is rejected for reason", mocks nicely because you can just Mock RejectResult (returned from IsRejected) and is essentially the first and very obvious method above with only a small change to the RejectResult class (the addition of the For method). Here's the Email class and RejectResult class:
public class Email
{
public RejectResult IsRejected
{
get{ return new RejectResult(true, new Reason("The reason this was rejected")); }
}
}
public class RejectResult
{
bool _rejected;
Reason _reason;
public RejectResult(bool rejected, Reason reason)
{
this._rejected = rejected;
this._reason = reason;
}
public bool For(out Reason reason)
{
reason = this._reason;
return this._rejected;
}
}
I love code that just explains itself without the need for copious comments!
Thursday, May 24, 2007
A problem with ASP.NET client side validation and IIS host headers
I've just had an interesting issue when deploying an ASP.NET application on to a web site that uses host headers. Host headers is where you can point multiple domains at a single IIS and IIS can resolve them to multiple virtual directories. ASP.NET requires some javascript files in a virtual directory under the root called ‘aspnet_client’ for its client side functionality such as the validation controls. If you’re creating your application in a virtual directory, e.g: http://www.mydomain.com/myapplication/ Then installing the .net runtime will put those files in the right place for that app: http://www.mydomain.com/aspnet_client/ The problem comes when you use host headers to resolve additional subdomains to a virtual directory: http://subdomain.mydomain.com/ ASP.NET looks for its javascript files here: http://subdomain.mydomain.com/aspnet_client/ But it won’t find them unless you remember to manually copy that directory to the root of your application. It’s something to be aware of (especially since it happened to me twice, double duh!)
Tuesday, May 15, 2007
Playing with JSON
string jsonText = JsonConvert.ExportToString(myObjectGraph);Because JSON is effectively native javascript you 'de-serialize' your graph on the client by simply calling 'eval' with your JSON text:
val myObjectGraph = eval(jsonText);For this simple scenario to work, the objects in your graph have to have a default public constructor and all properties must be settable and gettable, just like when you use the .NET XmlSerializer. But really, so much easier than all that messing around with XML. Of course JSON is extensively used in AJAX applications, even though the 'X' stands for XML :) And there's JSON support built into ASP.NET AJAX (formerly Atlas) in the System.Web.Script.Serialization Namespace, specifically the JavaScriptSerializer class. So if you are doing ASP.NET 2.0 work, you can use that instead of Jayrock. All I need now is an excuse to do some serious Ajax programming.
Monday, May 07, 2007
My new Web Service Test tool, WsdlWorks
As you can see it creates a new Visual Studio project, you right click the project node, select 'Add WSDL from URL', enter your WSDL's URL in the dialog that appears and then WsdlWorks automatically creates nodes for all the services and their operations. It also creates initial requests for each operation, but you can add as many as you want. To execute the request, you just right-click on the request node and select 'Run'. When you create a request it reads the WSDL's XSD for the request types and creates example data in the request. I used XmlSampleGenerator, by Priya Lakshminarayanan to do this. I tried to get it working with WCF multipart WSDLs, but haven't succeeded yet.
The error handling, icons and other stuff is also still on the 'to do' list, so it's far from production ready, but I thought I'd release it now in the best open source tradition since it's in its initial working state.
You can't release Visual Studio packages without a package load key, and you can't get a package load key without having a homepage for your project. But now I've got a homepage I can get the PLK. Expect an installer pretty soon. For the time being, if you want to play with WsdlWorks you'll need .NET 3.0 and the Visual Studio SDK so that you can run it in the experimental hive.