Stuff - mainly geek, a little diabetes, some rant. Possibly all three in the same post. Basically anything I find interesting and/or worth sharing.
These are my personal views, unless I've been hacked.
Why did you change it? What was wrong with it as it was? Where's the feedback now?
Imagine the scene... you're travelling along the motorway at 69.7mph, 315ft behind the car in front. The windscreen is getting slightly misty so you decide to use your car's blower to direct a blast of air on the windscreen. You risk a glance at the digital climate control console:
That's blowing on the windscreen and your feet.
You look for *the button*
You press it, and risk another glance at the console:
That's now blowing at the windscreen, your feet and your face; that's less effective than the last one, so you press the button again. And another glance:
Hmm, now it's not blowing on the windscreen at all. Just your feet and face. The windscreen's getting more misty now. Let's see what the button does this time:
I don't even know what this symbol means. I get feet and face, but "up"? Symbolised by an empty triangle instead of filled... still, it's not blowing on the windscreen, so let's hit the button. Again. And look. Again.
Ok, it's not pointing at your feet any more. Just your face, and "up". You sigh. The windscreen mists up even more. You press the button. Surely...
No. It's just blowing directly at your face. You wish hard, and press the button again.
At last, you now have air blowing at your windscreen.
But at what potential cost? Assuming you followed the instructions above, you will have taken your eyes off the road 8 times. There's no link between a push of the button and its result. Compare this to the more traditional analogue heater/blower console:
One glance and you can see that to get air on the windscreen, you need to twist the right-hand dial 1/5 clockwise. You'll feel the 1/5 turn, you'll get instant feedback. Simple. Great UX.
I read this blogpost a few days ago and was intrigued enough to have a go at refactoring its monster switch statement myself, during the Grand Prix. Here's my approach:
First task, get the creation of a "TaskClass" into a factory. A factory will need an interface to work with, so I defined the simplest one possible:
public interface ITaskClass { }
...and implemented it on each taskclass
public class Task1Class : ITaskClass { public void ExtractTop10Data(DateTime dtLastRun) { return; } }
Next, I created a TaskClassFactory, and duplicated the monster switch into the Create method
public static class TaskClassFactory { public static ITaskClass CreateTaskClass(string name) { switch (name) { case "Task1": return new Task1Class(); case "Task2": return new Task2Class(); case "Task3": return new Task3Class(); case "Task4": return new Task4Class(); } return null; } }
This gave me the opportunity to write some tests around the creation logic
[TestCase("Task1", typeof(Task1Class))] [TestCase("Task2", typeof(Task2Class))] [TestCase("Task3", typeof(Task3Class))] [TestCase("Task4", typeof(Task4Class))] public void CreateTest(string name, Type expectedType) { Assert.IsInstanceOf(expectedType, TaskClassFactory.CreateTaskClass(name)); }
Then I introduced the factory into the monster switch (please ignore the smell, this is very much work in progress)
Then I consolidated some of the repeated code; first the repeated catch block
try{ // switch on taskname.. //There were 22 task names in total making this method over 600 lines long! switch (task.TaskName) { case "Task1": var task1Class = (Task1Class)TaskClassFactory.CreateTaskClass(task.TaskName); task1Class.ExtractTop10Data(dtLastRun); task.LastRunTime = DateTime.UtcNow; UpdateTaskRunStatus(TaskStatus.Good, task); break; case "Task2": var task2Class = (Task2Class)TaskClassFactory.CreateTaskClass(task.TaskName); task2Class.CreateImageFeed(); task.LastRunTime = DateTime.UtcNow; UpdateTaskRunStatus(TaskStatus.Good, task); break; case "Task3": var task3Class = (Task3Class)TaskClassFactory.CreateTaskClass(task.TaskName); task3Class.DestroyImageFeed(); task.LastRunTime = DateTime.UtcNow; UpdateTaskRunStatus(TaskStatus.Good, task); break; case "Task4": var task4Class = (Task4Class)TaskClassFactory.CreateTaskClass(task.TaskName); task4Class.ProcessData(); task.LastRunTime = DateTime.UtcNow; UpdateTaskRunStatus(TaskStatus.Good, task); break; default: break; } } catch (Exception) { UpdateTaskRunStatus(TaskStatus.Error, task); Logger.LogError("Error details here"); }
and the common sweep-up tasks
try { // switch on taskname.. //There were 22 task names in total making this method over 600 lines long! switch (task.TaskName) { case "Task1": var task1Class = (Task1Class)TaskClassFactory.CreateTaskClass(task.TaskName); task1Class.ExtractTop10Data(dtLastRun); break; case "Task2": var task2Class = (Task2Class)TaskClassFactory.CreateTaskClass(task.TaskName); task2Class.CreateImageFeed(); break; case "Task3": var task3Class = (Task3Class)TaskClassFactory.CreateTaskClass(task.TaskName); task3Class.DestroyImageFeed(); break; case "Task4": var task4Class = (Task4Class)TaskClassFactory.CreateTaskClass(task.TaskName); task4Class.ProcessData(); break; default: break; } task.LastRunTime = DateTime.UtcNow; UpdateTaskRunStatus(TaskStatus.Good, task); } catch (Exception) { UpdateTaskRunStatus(TaskStatus.Error, task); Logger.LogError("Error details here"); }
One of the tasks has a parameter to its processing method. I assumed that out of the 22 others not shown there would be more variation to the processing methods. With a nod of acknowledgement to YAGNI, I decided that each task class that needed a parameter to perform its function should be constructed with these parameters; this would mean that I could create a parameterless processing function in the interface. More on this later. Anyway, to enable different constructor parameters to be used in the factory, I created a parameter object and added it to the Create method
public struct Parameters { public DateTime LastRunDate { get; set; } } ... public static ITaskClass CreateTaskClass(string name, Parameters createParams)
and in the monster switch:
TaskClassFactory.Parameters factoryParams = new TaskClassFactory.Parameters { LastRunDate = task.LastRunTime }; ... var task1Class = (Task1Class)TaskClassFactory.CreateTaskClass(task.TaskName, factoryParams);
This enabled me to define a parameterless DoWork method on the ITaskClass interface
public interface ITaskClass { void DoWork(); }
This meant I needed to implement the DoWork method in each of the TaskClass implementations. For those with no parameters on the processing method, the implementation was a simple call to that method
public class Task2Class : ITaskClass { public void CreateImageFeed() { return; } public void DoWork() { CreateImageFeed(); } }
The one with a parameter needed a little more scaffolding
public class Task1Class : ITaskClass { private DateTime _lastRunDate; public Task1Class(DateTime lastRunDate) { _lastRunDate = lastRunDate; } public void ExtractTop10Data(DateTime dtLastRun) { return; } public void DoWork() { ExtractTop10Data(_lastRunDate); } }
This forced the factory to change, to use Task1Class's new constructor
public static ITaskClass CreateTaskClass(string name, Parameters createParams) { switch (name) { case "Task1": return new Task1Class(createParams.LastRunDate);
This meant I could hide the existing processing methods in the task classes
Among my deficiencies is colour blindness; I'm not at the far end of the scale, but I have the traditional problems with reds/greens/browns. As Steve Fenton said (almost word-for-word) on his blog Test Your Website For Colour Blindness Issues, if you are not testing your website for colour-blindness, you are being stupid. I couldn't agree more.
So it's frustrating that when logging in to a major UK financial website, I am confronted by these buttons:
The vast majority of the thousands of you reading this will be thinking I don't get it; the rest of us will be thinking why did they choose the same colour for the "Log in" and "Clear" buttons?
The colours of these buttons are shown here, as various types of colour vision deficient people would see them (taken from the Color Blind Spectrum):
Normal
Protanopia
Deutanopia
Tritanoptia
#339900
#958600
#a58600
#518f9a
#cc0000
#786c1e
#886900
#cc1600
My colour blindness is Protanopia; you can see how I perceive the green and red buttons, and the lack of contrast between them.
With that in mind, imagine my delight when I pointed my web browser at the home page of the offending web site and saw a link that says High contrast
It does what it says on the tin; click it and you get this
In my naivity, I expected that when I clicked on the link to take me to the login screen, that too would be in High contrast mode. I expected the Log in and Clear buttons to be highly contrasted. This is what I got:
We have recently had a refit of the kitchen at work, and we have acquired some nice-looking canisters for tea, coffee and sugar. This is them:
How long does it take you to work out which one holds, for example, the sugar? Each time I make a cup of tea (and I drink a lot of tea), I need to put conscious effort into choosing the canister with tea in.
As Don Norman says in his book The Design Of Everyday Things, the designer probably won an award for them; and that's not a good thing. This is exactly what he talks about when he talks about knowledge "in the world" and not "in the head".
I'm revisiting my KenKen project, it's time for a little performance tuning - my unit tests take about 14 seconds to run, which is too long. One of the immediate fixes I need to make is remove the arbitrary limit of 10 calculation iterations, and swap it with some logic to decide if another iteration is likely to be useful.
The logic runs something like this
10 if grid solved then quit
20 if iterations >= 10 then guess a square, reset iterations and goto 10
30 iterations++
40 start an iteration, calculating as many squares as possible
50 goto 10
After 10 iterations, the grid is unlikely to be solved using the rules I've created; what usually happens is that by iteration 4 there are no squares left that can be calculated using my rules, so iterations 5-10 are pointless. This is an example of some tracing that illustrates the point:
The logic I needed to implement goes more like this:
10 if grid solved then quit
20 if previous iteration resulted in no work then guess a square and goto 10
30 start an iteration, calculating as many squares as possible
UPDATE
You're possibly the only person reading this, so thanks. I implemented the changes outlined above and it's shaved 1-1.5 seconds off the tests, so I'm happy. New tracing looks like this:
I needed a component that will hook into any event raised on any objects, to keep track of the number of events raised. Simple, huh?
Hardwired Proof of Concept
My first attempt was in the constructor of the observed object, that registered its events to be handled by a CountEvent method in an EventMonitor object.
It worked:
But it seriously ignored SRP in that the observed object shouldn't care how its events are handled.
Refactor I - The EventHandler Parameter
With SRP in mind, I created a RegisterEvent method to accept the object's event, so that the monitor could add its own handler - there still needed to be knowledge of observer and observed, but that could be handled in a builder object so no harm there. A nice side effect of this is that the method that actually handled the event (CountEvent) could be made private. This is the EventMonitor code:
Lovely. Next, time to implement the new RegisterEvent in the client:
Easy. Now, time to run it:
Hmm. I'm not entirely sure what happened there, but it appears that you can't just go passing events around like that as it doesn't give you access to the Add and Remove handlers that you need to call (using the += and -= syntax). Note to self: Jon Skeet will know.
The ref Keyword is Your Friend
However, a quick addition of the ref keyword seemed to work:
The Builder
Excellent. Next, I wanted to totally remove the responsibility of event registration from the observed object. Enter, the builder object:
You'll notice that the event passed as the argument to RegisterEvent is in an error state. The error that this produced is "The event 'ObservedObject.ObservedEvent' can only appear on the left hand side of += or -= (except when used from within the type 'ObservedObject')"
What a shame. I can't access the event outside of the class itself except to add or remove a handler. I did want to use the add handler, honest, but just not inside the builder. Ok, that clearly wasn't going to work so I changed tack, and added the event handler directly from inside the builder.
It worked
What's That Smell?
Lets revisit the objective of the exercise: I need a component that will hook into any event raised on any objects, to keep track of the number of events raised.
Clearly I didn't have this yet - I'd merely abstracted the construction of one object into a builder class. All good, but a long, long way from any event on any object.
Reflection
As we know, nothing is really safe from prying eyes in the .Net world; every object is available to be decomposed via reflection. And if you can't beat them, join them... I found an article on MSDN, How to: Hook Up a Delegate Using Reflection. This explained how to use reflection to discover an object's events, and crucially how to create a delegate and use it to handle the object's events.
Here's the final code for the event monitor:
Here's an extended ObservedObject, with a standard and custom eventhandler:
And the builder. Note, this just passes the ObservedObject through to the EventMonitor, ensuring that if the ObservedObject changes by adding events, its builder doesn't need to.
GitHub
The final version of the EventMonitor example is available to inspect here on GitHub
95% of the time, when I create a class in Visual Studio, I create a corresponding test class. The class ends up looking something like this:
To get to this from a standard "new class", it's approximately 100 keystrokes. As there's a finite number of keystrokes you can make before you die (see Scott Hanselmans evidence), it's important to cut down the number of keys you press as it will eventually kill you - unless I've deliberately misread the angle of Mr Hanselman's blog post. Anyway, what I needed is a VS template that gives me the above code.
Create The Content
The first step to creating a template is to write the code that you want to end up with - for me, that's the code as shown above. I saved this in a file called NUnitTestFixture.cs.
Define The Template
Next step is to create the mechanism for telling Visual Studio about your template. This is done via an XML definition of your template, saved as a file with a .vstemplate extension. This is the XML definition of the NUnitTestFixture template:
This is what the important parts of this file defines:
Lines 3 - 9 <TemplateData> defines how the item will appear in the VS "Add new item" dialog.
Lines 4 - 8 define the individual items of information, displayed in the dialog as shown:
Lines 10-12 <TemplateContent> define the items that will be added to the VS project when this item is selected.
Line 11 defines the single item of this template, the code template. I'll show later how to package the template so that these files are available to Visual Studio. The TemplateContent element defines a file that makes up part of the template - in this example there's just one element for the code file NUnitTestFixture.cs. If there was e.g. a help file, a resource file, a designer etc, these would each have a separate TemplateContent element. In the element in the example, the ReplaceParameters attribute indicates that placeholders in the file can be replaced with variables.
Replace Parameters
When a NUnitTestFixture class is required in a project, there will be details that are only known when the item is created, for example the default namespace of the project, and the name of the class as input by the user:
Templates are able to be parameterised so that at the time of creation, placeholders can be replaced with their correct values. There are several built-in parameters available to use, see the MSDN documentation for a full list.
For the variables shown above, the built in parameters that are needed are rootnamespace and itemname; rootnamespace is the default namespace for the project the item is being added to, and itemname is the name of the file as input by the user on the "Add new item" dialog. The convention for defining placeholders is to wrap the parameter name in $ characters, so NUnitTestFixture.cs needs to look like this
Package The Template
For Visual Studio to make the template available, it needs to have all the files supplied in the form of a ZIP archive. For the example here, the files to include are
the code file, NUnitTestFixture.cs
the 48x48 pixel icon file, M_J_O_N_E_S.ico
the template definition file, NUnitTestFixture.vstemplate
Put these files in the same folder, and add them to a ZIP file - the easiest way is to select the files, right click and choose Send To -> Compressed (zipped) Folder. The resulting ZIP file needs to be copied to Visual Studio's Item Templates folder, and will then be available on the "Add new item" list.
Tip: to find out where your Item Tempate folder is, go to Tools -> Options -> Projects and Solutions -> General.
Further possibilities
I've barely scratched the surface with this template and there is far more configuration available than this blog post shows. There's a heap more to read about this topic on MSDN.