Tuesday, May 31, 2005

Musical Office

I frequently work with teams that like to listen to music while developing. I hate headphones. I find they are worse than putting each developer in their own office for team communication. Better to have some music you all agree upon listening to and have an Office Jukebox.

Currently we are using WinAmp with WinAmp Web Interface. This allows anyone on the team to change track, change volume, etc.

Mocking actors and critics

Talking with Craig the other day he mentioned the names 'Actor' and 'Critic' when talking about the roles of a mock object.

Looking at the EasyMock API more this week, it seems there may be a way to use the SetDefaultValue() methods to achieve what I want. We shall see.

Saturday, May 28, 2005

EasyMockNET vs NMock

Recently I have been convinced to try easy mock instead of NMock (my mocking framework of preference). Here is how I went...

I started using NMock when all that was available was a dll you could download from sourceforge. There was absolutely no documentation and no source code. I ended up using Reflector (great tool) to work out how to use it. NMock soon became an indispensable tool.

There are a choice of mocking frameworks now (a good list is available on testdriven.net). Most are basically the same. I have been happy with NMock but it does have one problem though. Here is an example of an NMock Test.

[Test]
public void LoadingScriptWithSingleKnownAction()
{
DynamicMock mockActionLoader = new DynamicMock(typeof(IDbActionLoader));
IDbActionLoader actionLoader = (IDbActionLoader)mockActionLoader.MockInstance;

DynamicMock mockAction = new DynamicMock(typeof(IDbAction));
IDbAction action = (IDbAction)mockAction.MockInstance;

DBScriptLoader loader = new DBScriptLoader();
loader.RegisterActionLoader(actionLoader);

string scriptTxt = @"CreateTable
Name: newTable";

mockActionLoader.ExpectAndReturn("HasName",true,"CreateTable");
mockActionLoader.ExpectAndReturn("LoadAction",action,scriptTxt);

IDbScript script = loader.LoadScript(scriptTxt);
Assert.AreEqual(1,script.Length);
Assert.AreEqual(action,script[0]);
mockActionLoader.Verify();
}


Notice the "ExpectAndReturn" calls require you to specify the name of the method you are expecting as a string. The problem with this is that refactoring tools (i.e. Resharper) doesn't know these are method names. If you rename one of these methods you will have to manually rename the string to match. This sort of test maintenance increases the cost of having tests. Anything that increases the cost of tests is bad as it pushes you towards writing less tests and that is where the map is marked 'here be monsters'.

EasyMock has another way of writing tests. The mock object that is created has two modes. It starts in recording mode. To set expectations you just call methods on the object. When you have set all your expectations you then switch all the objects to replay mode. To set the return value of a method call you have to call 'SetReturnValue' just after the method has been called. This is ugly, but luckily there is some syntactic sugar to wrap this up in most cases. Here is the same test again in EasyMock (using the ExpectAndReturn syntax).

[Test]
public void LoadingScriptWithSingleKnownAction()
{
MockControl mockActionLoader = MockControl.CreateStrictControl(typeof(IDbActionLoader));
IDbActionLoader actionLoader = (IDbActionLoader)mockActionLoader.GetMock();

MockControl mockAction = MockControl.CreateStrictControl(typeof(IDbAction));
IDbAction action = (IDbAction)mockAction.GetMock();

DBScriptLoader loader = new DBScriptLoader();
loader.RegisterActionLoader(actionLoader);

string scriptTxt = @"CreateTable
Name: newTable";

mockActionLoader.ExpectAndReturn(actionLoader.HasName("CreateTable"),true);
mockActionLoader.ExpectAndReturn(actionLoader.LoadAction(scriptTxt),action);

mockActionLoader.Replay();
mockAction.Replay();

IDbScript script = loader.LoadScript(scriptTxt);
Assert.AreEqual(1,script.Length);
Assert.AreEqual(action,script[0]);

mockActionLoader.Verify();
mockAction.Verify();
}


ExpectAndReturn in Easymock is the syntactic sugar to make the interface look like NMocks. The following are equivalent...

mockActionLoader.ExpectAndReturn(actionLoader.HasName("CreateTable"),true);

or

actionLoader.HasName("CreateTable");
mockActionLoader.SetReturnValue(true);


In the ExpectAndReturn methods the first parameter is ignored. It is just a nice place to put your method call to the mock object.

I started using EasyMockNET on a new project and quickly found that a simple helper class makes using EasyMock even easier.

public class MockManager
{
private ArrayList mocks = new ArrayList();
public MockControl CreateMock(Type typeToMock)
{
MockControl strictControl = MockControl.CreateStrictControl(typeToMock);
mocks.Add(strictControl);
return strictControl;
}

public void StopRecordingAndStartPlayback()
{
foreach (MockControl mock in mocks)
{
mock.Replay();
}
}

public void VerifyAllExpectations()
{
foreach (MockControl mock in mocks)
{
mock.Verify();
}
}

public void ResetAllExpectations()
{
foreach (MockControl mock in mocks)
{
mock.Reset();
}
}
}


By creating an instance of this class in the SetUp method of the test fixture, and using CreateMock instead of MockControl.CreateStrictControl it allows you to verify, reset or replay all the mocks in one go.

One problem I have with mock objects (in general) is how easy it is to make your test dependent on the implementation details of the class under test. A good unit test should verify the external behavior of the class, not the method it uses. The very nature of mock objects forces you to set expectations on how a class is used. I don't care if the calling class uses my "Has Items" method as long as it doesn't try to access the items when there aren't any. If the calling class decided to call this method two or three times I don't really care either. So... I want to be able to say "method, don't expect to be called, but if you are with these parameters then return this value". I have added such a method to my local version of NMock. I guess I will have to add something similar to EasyMockNET.

When I am writing a test with mock objects I find that I use them in three ways. One is to set up data so I can put the class under test into a known state before I begin my real test. Another is as a simple data object that I verify is passed around correctly (no expectations are set). The other is the actual expectations I wish to validate for the test. Again the first set of expectations I don't actually want to verify for this test (they should be tested elsewhere). Thoughtfully EasyMock provides a Reset method which throws away all the expectations set so far. You can therefore set up mocks to return values, call the init methods on your class under test so its state is set, then call Reset on all mocks. You are not ready to set your real expectations.

So... My conclusion? I'm using EasyMockNET on all my projects from now on. The fact that refactorings tools can keep my tests up to date is a big win for me. If I change my mind later, I'll let you know ;)

Wednesday, May 18, 2005

How to change your life

I have been reading a great book recently "It's your life. What are you going to do with it?" by Anthony Grant PhD and Jane Greene.

It is a book about how to be your own life coach. Every piece of advice is practical and based on research. I recommend giving it a read if you have any unfulfilled goals.

One gem I have taken away from it so far (and it is typical of this book that the advice seems obvious once you hear it) is...

If you want to make a change in your life, there are several phases that you go through.
* Preconception - before you start thinking of making a change.
* Contemplation
* preparation
* Action - start to take steps
* Maintenance - conscious effort required to follow new behavior (leading to relapse or termination)
* Relapse - fall back to old habits (leading back to Contemplation)
* Termination - The new behavior is now part of your personality

So.. You can help make changes be facing each of these phases full on.
When it occurs to you that you should change something evaluate the pro's and con's on paper. This will help you decide if you really want to make the change. This will lead you quickly to the preparation stage. Plan what changes you want to make to achieve your goal. Make them attainable and measurable. This readies you for Action. Put in place your plans. Measure your progress in a way that you can visibly see how you are getting on. By measuring how you are progressing you can use feedback to adjust your goals to ensure they are attainable. This will help you enter the Termination stage. Even if you don't attain your original goal, from this new position your original goal may now be attainable. Relapse is expected and is not failure. Don't beat yourself up for it. Return to Contemplation and reevaluate your original reasons for wanting to make the change. This is where having defined a good list of pro's and con's at the beginning will help. Review them. If they are still correct then this should help get you quickly back to preparation. Take the time to reevaluate the plans you previously made. Adjust them if they are not measurable and attainable.

and repeat.

Skype on PDAs

Can someone do me a favor?

If you have a window CE PDA with speaker, mic and wireless... Install skype on it!
Being able to send and recieve free calls with friends while you are in range of a network sounds cool.

Anyone tried it? I'd love to hear how it went.

Cheers

Refactoring Thumbnails

It is a cool way to view refactorings.
http://refactoring.be/thumbnails/ec-proxy.html

Tuesday, May 17, 2005

How OO are you?

I once introduced a very smart C coder to C++. I had the pleasure of working with the guy, and what impressed me most was how he followed a coding standard of his own invention.

Namely:
* All methods take as their first parameter a structure.
* Only methods related to a structure lived in the same .h and cpp files.

Basically the guy was doing OO and didn't know it.

So... What is the opposite of OO?

I recently had to interview a guy that claimed to know C++, Java, C# and more. In the interview it turned out that he didn't like objects and preferred to just use functions and global variables. In Java, for example, his code would consist of a single class containing all methods and variables.

It seems that Procedural and OO are different ends of some spectrum. Which makes me think 'Where about on this spectrum does my code live?' I hope its up the OO end. That's my aim. I have found that TDD has help me move much closer to the OO end than I thought possible. I am going to make a conscious effort to see if I can get any further away from procedural code.

Basically I am going to try to make all method bodies as small as possible (try to get to one line) and use objects not basic types (try to pass at most one parameter to each method). Also I'll make sure no methods have any side effects. :)

We'll see how I get on.

Friday, May 13, 2005

Hungarian Notation is good? Since when?!?

Wow! It seems that the completely pointless naming standard I was taught years ago called 'Hungarian Notation' was a misinterpretation of a slightly more useful coding standard.

Check out JoelOnSoftware for the details : Making Wrong Code Look Wrong
http://www.joelonsoftware.com/articles/Wrong.html

Thursday, May 05, 2005

Refactoring is optimization

Refactoring is a form of Optimization. You are optimizing the code for maintainability and clarity.

The rule of premature optimization is that you don't do it till you need it. This prevents you spending time optimizing code that doesn't need it. You measure where you need to optimize before optimizing. In reality the optimizations needed are never where you would have guessed. So the question is... In the case of refactoring, what is premature optimization?

In my opinion, premature optimization is when you design the code before you write it. You are guessing at what concepts you are going to need to hold in the code, and not being driven by the actual need of the system. You end up over-designing system that a simple solution would work just a well for. (see YAGNI).

Hence the order of Red, Green, Refactor.
* Red - Add an idea to the requirements.
* Green - Add the concept to the code.
* Refactor - Distill the new concepts for clarity.

Note that refactor is after the idea is in the system, not before!

These thoughts came out of a chat with Simon Harris the other week.

What the hell was MSWord thinking?

Right
Resharper makes an icon appear to say 'I know how to do some stuff with the thing you have highlighted'. The user is not interrupted. The code doesn't change without being asked (well except in Visual studio's VB editor, but that doesn't count).

Wrong
MSWord changes stuff while you type without asking. It then highlights the changes to give you the chance to undo them. I spend more time undoing the mistakes it makes with its guesses than any possible benefit I get from its changes.

Editors should be intelligent, but they should offer assistance when asked, NOT when they feel like it.

You do that a lot! Want to automate it?

Imagine an IDE that watched your key presses/edit actions. It look for duplication in the stream of actions and say "Hey, are you doing that thing you did before? Do you want me to the rest for you?" humm... Sounds horridly like "you seem to be writing a letter..." arrgh.

ok.. Better... You activate a 'I've done this a couple of times, can you do it for me' function. It suggests a list of things you keep doing. You get to store away auto-macros (as I am now calling them) so you can keep them if they are useful.

The list could be ordered by recent, or popular.

Just a thought

Rapid feedback

Ok.. This is a flight of fancy I had a few months ago, but its still in my head, so I thought I would let it free on the web.

Imagine an IDE where as you type in new code you not only get told if the code compiles, but also if the unit tests pass with this new code.

IDEs now hold a parsed version of your code so they can highlight compiler errors as you type. Its not that big a step to then interpret the tests over the in memory parse-tree to see how the code will execute. The IDE could keep track of which lines of code are executed by which test easily enough. Then it would be a case of only re-interpreting the tests that are potentially effected by each edit.

This would be the ultimate in rapid feedback :)

Wednesday, May 04, 2005

.Net on Rails?

Castle.Net is a bunch of libraries for everything from IoP to 'Castle on Rails'. There are a couple of tutorials on Code Project (http://www.codeproject.com/csharp/IntroducingCastleII.asp).

I intend to have a play with it, so expect to see more posts on Castle in the future. :)

Atom Feed

I have an atom feed on this site, but I just noticed that you can't get at the link easily due to the way the URLs are hidden on my site.

Here is a link you can use until the issue is fixed.

http://web.aanet.com.au/nigelthorne/blog/atom.xml

From the guys that wrote Ruby On Rails

Ruby on Rails was an offshoot from a product these guys made for project management. Thoday they released a site aimed at life management.

http://www.backpackit.com/

It's free to join... and has so much potential!

Check it out.

GitHub Projects