Unit Testing Events

Recently I have had to unit test some events in an application I work on. I came up with a workable solution, but I didn’t really like the way it was working, and it just looked ugly. So I did a little digging on Google, and found this helpful question on StackOverflow.

Here is my take it. I’m putting it here so I can find easily find it again. Basically it’s the same, but I’m using a lambda to create my anonymous delegate:


[Test]
 public void UnitTestNodeChanged()
 {
 var receivedEvents = new List<XmlNodeChangedEventArgs>();
 var document = new XmlDocument();

 document.NodeChanged += ((sender, e) => receivedEvents.Add(e));
 document.Load("C:\file.xml");

 Assert.That(receivedEvents.Count, Is.EqualTo(1));
 }

Nice and short, and to the point. We can test the fact that the event was raised (or not); how many times the event was raised; and, we can test the event arguments.

I like it. Some people may not, but it suits my purposes.

Share this post:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • StumbleUpon
  • Technorati
Posted in C#, Coding | Leave a comment

Well I certainly didn’t know that Word could do this

Whilst I was watching football I had this amazing idea that I was going to write a plugin for Word that would let you write blog posts and publish them onto your blog. I literally had no idea that Word would have this baked in by default.

Obviously I’ve had to test this out immediately.

Share this post:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • StumbleUpon
  • Technorati
Posted in Uncategorized | Leave a comment

Revisting the Project Euler problem runner

I’m sure that you must have heard about Project Euler, which “is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve”. I have blogged about tackling the Project Euler problems before, and at the time, I developed a simple program to try to automate running the problems.

That was about 18 months ago, I’ve learned a lot since then and I think that it is high time to take a look back at the code and see if I can spot if there is any room for improvement.

The current project

The current structure of the project

Current structure

Let’s have a look at how I structured the project when I set it up. The first thing that you will notice, is that I messed up the package names. It should be “uk.co”, and not “co.uk”, according to the Java language specification. A minor point, and not really a big deal, we can easily sort it out.

Something else I did, was lump everything together into the same project and package – the runner program, the utils (e.g. helper classes that you write as you progress through problems), resources and the problems themselves.

I don’t think that this was necessarily a bad idea at the time, I don’t think that it is inherintly a bad idea now, it’s logical for everything to share the same package. Or should I say, it was logical for everything to share the same package.

I am going to put the code for the problem runner onto Github, but I don’t want to share the answers to the problems. To answer your question, I think that it goes against the point of Project Euler, that of having a set of problems that the inquisitive person can solve with some math and programming. I have also found that the problems also help in getting comfortable with the syntax of a new programming language – after all the solutions to the problems remain the same, however the implementation is subtley different depending on the language being used.

Re-Design

Examining the current code and design, we can immediately identify some changes which we are going to make  I’m going to seperate the uk.co.temporalcohesion.euler package into three packages, which are more distinct from each other, but still keep them all in the same project. Why? Well, it is obvious that there are three tasks which we have to manage:

  1. Running problems.
  2. Provide an API to run the problems.
  3. Store the problems somewhere

To shed some light on my thinking here, lets examine these in more detail. This will also identify areas of possible improvement in the design.

1. I want someway of consistenly running a problem (or group of problems) to test the solution(s) to (a) Project Euler problem(s). This is basically our console runner application, which doesn’t have to know exactly how this happens, it recieves input, and returns output – how that output is generated is irrelevant to it.

2. I want an easy to use API which I can leverage to easily implement the solution to a Project Euler problem, so that I don’t have to worry about re-writing all the input/output code over and over again. I also want to be able to share this API, without sharing the answers to the problems themselves.

3. I need to have somewhere I can put the answers to the problems, and associated helper classes (Prime number generators, etc) which I can easly backup, and easily run the problems from.

These are sounding a bit like user stories, and I suppose they are. They can be formalised as so:

As a Problem Solver, I want to run the solution, or group of solutions, to a Project Euler problem.

As a problem solver, I want to concentrate implementing the solution to a euler problem, not on implementing input/output for the problem.

As a problem solver, I want a place to develop and store the problems, from which I can run the problems to test the solution.

Fairly concise and simple requirements, which we will revisit later. We still have to examine the code in a little more detail so that we can identify exactly what it is we are going to refactor.

Code review

The main class to examine is Euler, in Euler.java.  The first to say without even looking at the code, is that the name is fairly awful. Then when we examine the code in more detail, we can see the name is even worse. The class has the main entry point for the program, as well as all the code to actually run the problems. This class is doing everything, there is definately no Seperation of Concerns. It is responsible for accepting user input, loading and running the problems and displaying the output. Wow.

The class is designed around the Command Pattern, and it has worked quite well. Looking at it now, a further two patterns could be used, namely Strategy and Template method.I’m still in two minds about refactoring the design pattern in use, but that discussion can be put off for the time being, as I have other things to concern me.

There are 144 SLoC, not a massive amount, but when you consider the above and what the class should be doing, then it is clearly a bit weighty. There are 7 functions in total, not counting the constructor, not a massive count, but as the SLoC count indicates, some of those functions are a bit long. The worst offender is the following method.


private void loadClasses() {
 InputStream fis = null;

 Properties p = new Properties();

 try {
 fis = ClassLoader
 .getSystemResourceAsStream("co/uk/temporalcohesion/euler/resources/problems.properties");
 p.load(fis);

 Enumeration<?> e = p.propertyNames();
 while (e.hasMoreElements()) {
 String key = (String) e.nextElement();
 String value = (String) p.getProperty(key);

 Object o = Class.forName(value).newInstance();
 if( ( o != null) && (o instanceof Problem)){
 Problem problem = (Problem)o;
 problems.put(Integer.parseInt(key), problem);
 }
 }
 }

 catch (FileNotFoundException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 } catch (ClassNotFoundException e) {
 e.printStackTrace();
 } catch (InstantiationException e) {
 e.printStackTrace();
 } catch (IllegalAccessException e) {
 e.printStackTrace();
 } catch (ClassCastException e) {

 }
 finally {
 try {
 fis.close();
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
 }

Wow, that’s a lot of code for something which is relatively straightforward. It’s not exactly easy to read, and it violoates the Single Responsibility Principle: by loading in and enumerating over a properties file, instantiating new instances of problem classes, and handling all the exceptions which can be thrown. There will definately be some room for improvement there.

Getting back to the main Euler class as a whole, there is an even worse problem…

There are no unit tests!

This is a disastrous situation, because it means I cannot refactor the class with any confidence. The me of 18 months ago has a lot to answer for. I’ve got a bit of work to do. Check back next time to see how I’ve progressed things.

Share this post:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • StumbleUpon
  • Technorati
Posted in Java, Project Euler | Tagged , , | Leave a comment

Even more on the generic plugin manager

I’ve written previously about writing your own generic plugin manager/framework.

I believe that this is a worthwhile exercise for the beginning programmer, because it firstly teaches you a lot about reflection, and secondly teaches you the advantages that proper use of interfaces can bring to your code. Thirdly it can also teach you to think about how your API might be used by someone else when they write a plugin for your program. In short I think it’s a great exercise.

While writing and using my own plugin framework has been a great learning experience for me, I’ve found that I have outgrown it’s usefulness to me. What made me see this was when I started to think about and begin implementing a way for me to use the framework as a IoC/Dependency Injection tool. This led me off on some Googling and I found Funq, and the the associated screencasts by Cazzulino.

This got me to thinking about DRY. Don’t Repeat Yourself can just as easily mean Don’t Repeat Work Other People Have Already Done (If You Don’t Have To), but DRWOPHADIYDHT doesn’t sound/look nice as an acronym. Perhaps a better way to express that sentiment is “lazyDRY”, or “The re-use of prexisting libraries and code can save you a lot of time, and which effort you can put into your application at a higher level.”

Or in other words, it is foolish to ignore the work that other people have done, unless you have a compelling reason to do so. If you really want to write your own IoC/DI container, then great, knock yourself out. No one is going to stop you.

I’m lazy though. Nanos gigantium humeris insidentes.

Depending on the blogs in your feed reader, or who you follow on Twitter, or just in general googling, you will probably come across references to the same group of IoC/DI containers. Chiefly:

There are others, but it would seem hardly anyone uses them. Of those above, I have so far only used StructureMap and Ninject, and have really liked using both of them. I will try out the others at some point, but so far I’ve liked what I’ve seen in StructureMap and Ninject, I honestly don’t think that any of the others will have anything better to offer me. Besides which, StructureMap has a built in method of using it as a plugin framework. Win.

In Conclusion

What can I draw from all this? I don’t think that I wasted any of my time or effort in writing my own plugin framework. It was a worthwhile exercise which taught me a lot of things, and I urge you to do the same.

Share this post:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • StumbleUpon
  • Technorati
Posted in C#, Coding | Tagged , , | 2 Comments

You don’t have to kneel at the altar of the cult of Apple

Unless you’ve been living under a rock

You will have seen, heard and read the buzz about the Apple iPad. What it is, what it does and why you should buy it. This post is not about all that – it’s covered in excruciating detail elsewhere on your favourite tech site. Ever since the iPad was just a rumour, and since it was officially announced, we have been arguing about it at work. Whose going to buy one? Who is an idiot for wanting to buy one? Who is an idiot for not wanting to buy one?

Note: I should mention that I do happen to own an iPhone (via an O2 two year(!) contract), and I think it is probably the best mobile phone I’ve ever owned, however, I will take some convincing to enter into another two year contract again. But I digress. I have a couple of old iPods, nothing else: I am not a fanboy.

The niche that the iPad and devices like it fill is undoubtedly there, or else these products would not be developed. The key thing here is “…and devices like it…”. There isn’t just the iPad to consider.  This is the fantastic thing about our society: we have a huge freedom of choice in our purchasing decisions. We are free to evaluate, consider and weigh all the pros and cons of a particular product before we make the commitment to purchase.

Unless you are an Apple fanboy

In which case, you have already sub-concisiously made the decision to purchase anything with an Apple logo on. Are you an Apple fan boy? You have a Mac of some discription. You bought (and probably still have) a first-gen iPod. You bought an iTouch the day it was release. You were the first in your office to get an iPhone. You were the first to upgrade to an iPhone 3G. You were the first to upgrade to an iPhone 3GS. You hammer F5 on your favourite liveblog of an Apple event. You wouldn’t even consider buying a laptop from Asus, Acer or Dell (or whoever) which as powerful and costs half the price of something which has a fucking Apple logo on it.

Fanboy. Acolyte. Get out. You have already made your choice. You cannot win an arguement with someone who fanatically believes they are right.

Open minded? Continue from here

For those who are prepared to broaden our horizons, there is a bewildering array of choice just around the corner. Rather than rehash other people’s hard work from around the interweb, and because I’m lazy, I refer you to this article on About.com: http://portables.about.com/od/otherdevices/tp/Slate_tablet_roundup.htm, which offers a succinct highlight of varous slate tablet computers. Engadget also has some details of Microsofts offering, the ‘Courier’, which looks promising.

In Conclusion

You do not have to kneel at the alter of the cult of Apple. You have a choice. Use it wisely.

Share this post:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • StumbleUpon
  • Technorati
Posted in Uncategorized | Leave a comment