Friday 12 December 2014

Share the knowledge

Everyone has their list of technical sites / blogs they enjoy visiting from time to time. I think it's imperative to get yourself (and sometimes force yourself) to read something technical, even if it's something you think you already know. It's always a chance to fill any gaps or simply refresh your knowledge.

I've found some sites that are great, especially when it comes to the refreshing what you know. There are a lot more blogs I regularly visit but I like these 3 when I just want to quickly learn/review something.
Please feel free to share any of your favourites.

Tuesday 25 November 2014

Guard yourself

It's often handy to have "Guard" logic in your code to validate expectations. It's an integral part of the code and is generally used to throw exceptions when something does not meet expectations. The bulk of the Guard code would live at the beginning of methods to validate arguments, but in theory it could be used anywhere for anything.

There are a large number of open source libraries that provide this functionality (try a nuget search for guard). While it's always nice when somebody else has already done the hard work, in this case the work isn't really that hard. So you might, for reasons of flexibility, want to write your own. Here is a very simple example that I think gives full flexibility and allows you to add any bespoke checks you may need.

First we have a very simple static class that is the heart of the implementation.


I told you it was simple! This would allow you to validate anything and throw any exception. I've gone for "Ensure.That()" so there is less likelihood of naming conflicts and I really like how it reads, "Ensure that ...".

Next, I've created another very simple static class with the validations.


This is a very small subset of the methods you might require (although it would probably cover the bulk of your validations). You would be able to add as you go. Obviously you don't need to use methods from this class to do the validation but it is handy having everything in one place.

Here is an example of it in action


Very simple and again I like the way it reads, "Ensure that value is ...".

Tuesday 18 November 2014

Small Things - Recursive Lambda

In hindsight recursive lambda is obviously possible, but it's nothing I've ever come across and nothing I'd ever tried. I think it has a very high coolness factor! But not entirely sure how often it would be useful.

Anybody have any interesting examples of actual use in the wild?


Wednesday 1 October 2014

Nicely Dynamic

The dynamic keyword scares me. I understand why it exists (interaction with COM and scripting languages like IronPython) but I know what developers are like. Dynamic used everywhere for no apparent reason other than to try it, resulting in code that is hard to read and maintain. OK, probably not that bad, but I think it's fair to say that under normal circumstances a developer should not use dynamic. Unless...

I think I found a justifiable use of dynamic. Consider a Dictionary<Type, IConverter<T>> where Type and T should be the same. But how would you manage the dictionary. Dynamic to the rescue.


I really like this approach. The use of dynamic is nicely abstracted within your class so nobody ever needs to know. And because you're managing the getting and setting you can be very confident that the dynamic value extracted from the Dictionary is always what you expect.

Thursday 4 September 2014

UX Smoke and Mirrors

I recently had to implement a requirement where the specification was (roughly):
1. Take a table of data and print it using a FlowDocument
2. The font size must decrease to fit as many columns as possible up to a minimum font size.

(Just a heads up, the next part is a bit boring. Feel free to skip to the last paragraph if you want to get to the point of the post quickly)

At first it seemed like a not very trivial thing to do. One approach I thought of was to loop through each column and each row, calculating the width of the text when rendered, therefore the expected width of each column. Then repeat that process, decreasing the font size, until all the columns fit or the minimum font size is reached. It's possible to calculate the expected rendered width of the column by creating a FormattedText object and getting the Width property.

This works, but it is immensely slow. If we have 100 rows with 100 columns, we're measuring the width of 10,000 strings, as many times as it takes to fit the data to the page. Not ideal.

Then I hit on a winner. What if I measure everything just once at the default font size and calculate the widths of each column. I have the width of the document so I know how many columns can fit. Here's where it gets interesting. A WPF Grid can be added to the document (it's possible to add a UIElement to a FlowDocument by adding it to a BlockUIContainer) and a scale transform can be applied to shrink it to fit the page (or as many columns as possible).

The scale ratio can be calculated by comparing the document width with the total column widths. There must be a minimum scale ratio (to ensure we don't minimise the font size too much) which can roughly be calculated by comparing the default font size and the minimum font size (took a bit of trial and error). So our scale ratio is the bigger of the calculated scale ratio and the minimum scale ratio.

Now it becomes relatively easy to add columns one at a time until no more columns will fit, using the column width and the scaling ratio in the calculations. Then create the Grid with the columns, apply the scale transform using the calculated ratio and add it to the document.

This worked like a dream. It was however still a bit slow for my liking. So I added logic to find the longest string in the column and calculate the width of that text. This made it lightning fast. Unfortunately it turns out not all text is created equal. Upper-case characters take up more space than lower-case so sometimes the data in a column was being truncated. To solve this I gave upper-case letters a slightly higher weighting than lower-case, compared the summed weightings of the text of each column to find what "should" be the longest text when rendered, then calculated the column width with that text.

All of that obviously super exciting for the reader. Maybe. And means very little to you with no code to look at. But the point I'm trying to make in this post is that with UX development, smoke and mirrors can sometimes be your best friend. If you can use a bit of magic to deliver your requirement and it does what the user expects, mission accomplished. And if your smoke and mirrors helps considerably with performance, even better.

Friday 25 July 2014

Small Things - String Indexer

Great software doesn't just happen. It's a result of very many decisions of which some are small, others more vital, but all of them incrementally adding to the final solution. Any decisions taking you in the wrong direction (i.e. away from an amazing end product) is a poor decision. Even the small, seemingly insignificant ones. Here's one that I've seen recently.


String literals should be replaced with a string constant declared somewhere and re-used.


I realise this may seem pedantic and in a way it is. But this simple act of laziness (yes, lazy) is a decision taking you in the wrong direction. It results in code that is less robust. But almost more importantly it's a sign that bad decisions are being made. Be a good citizen and keep making good decisions.

(Now please look away as I dismount from my high horse)

Friday 4 July 2014

Save those Eyes

A few months ago I was listening to a Dave Asprey podcast about lighting and the effects it can have on us. The podcast goes into detail on why and how lighting can affect us negatively. Bottom line, staring at a computer screen bathed in fluorescence is not ideal. It puts our eyes and brains under unnecessary strain.

Some background. I had laser eye surgery about 4 years ago. The results have been nothing short of amazing! Perfect vision. But I noticed that by the end of each week, my eyes would feel a bit blurry. Nothing serious, but definitely noticeable (it would improve over weekends and holidays). I'd just accepted it as an occupational hazard.

So I started looking into anti-glare glasses. After some googling I found a brand called Gunnar. The reviews and forums were mixed (as they always are I guess) but there were a number of people who were adamant that they helped with eye strain. So I figured why not and bought myself a pair.

Money very, very well spent! At the end of a week I don't feel any strain and I don't notice any blurriness. If anything I'd swear my eyesight has improved since I started wearing them. I understand that this n = 1 experiment is extremely subjective. "My eyes feel better" is hardly a scientific measurement, but it has me sold. And even if it's just a placebo, that doesn't make it any less effective.

The only downside I noticed was the (very much expected) ridicule I received in the office for wearing tinted glasses. But that passed and was very quickly followed by "Hmmm, you say they work? Where can I get a pair".


Monday 30 June 2014

Small things - Select Rectangle of Text

I found something really small and simple, but it's changed my world (ok, slight hyperbole). While most C# developers already know about it, for some reason I'd never come across it.

It's possible to select a rectangle of text with Visual Studio. And all you have to do is hold down alt while you're holding down the left mouse button. Easy peasy! This is especially handy when you're using something like Specflow and you have tables of data you're updating. Give it a go, it's awesome.

Monday 23 June 2014

ViewModel Properties (3 of 3)

In part 3 I'm going to take what we've done with ViewModel Properties and show you how it dove tails very nicely into testing.

I use Specflow as my Gherkin tool of choice (you will need to install it if you want to play with the example). I won't go into detail about the philosophy of BDD and Gherkin. If you want to do some reading you can go here and here. But in short I've used it on several projects and I'm starting to think it's a pre-requisite for any large project.

Before we go any further here is a peek at one of the Gherkin tests. You'll see they are very simple and easy to read (even a BA with no coding ability would be able to understand it). For each Given/When/Then line there is a method in code that handles the step. It all takes a bit of getting used to but it's very much worth the effort!


Let's take a look at why our ViewModel Property helps us with testing. If you recall, we have a ViewModel Property Collection within our ViewModel to help us keep track of and manipulate our Properties as a whole. What this also gives us is a method called GetSnapshot. This method will return a Dictionary (key/value) with all the relevant data for a Property (it just iterates over all the ViewModel Properties and calls GetSnapshot on them). With this data we have a snapshot of the state of our ViewModel.


From there setting up the tests becomes relatively trivial. You create the tests using actions applied to your ViewModel and expected states of your ViewModel as validation (that's all testing is really, perform an action and validate the state of the object we're testing). If you're using BDD you could create Acceptance Tests off the back of your Specifications. If you're using TDD, you would create all the test scenarios before you've written any code.


Obviously there is a lot I haven't discussed here. The best way to learn about something is to get your hands on it and dive right in. So please, if you are interested in this approach, go to the GitHub repository, and have a play. And of course, any feedback would be appreciated!

Tuesday 10 June 2014

ViewModel Properties (2 of 3)

It's time now to go over an example of how we could use our funky new ViewModel Properties. I've created a very simple Person example. In fact it's so simple you'll have to forgive me. There is no dependency injection and I'm creating a ViewModel in code behind, but it's all just to get the point across.


Lets look at PersonViewModel (or the start of it as seen above). You'll see on line 13 I'm creating an instance of the Collection. Then lines 15 to 20 are the Property definitions. And then at the bottom the constructor takes the Controller as a parameter and calls Initialse. All very clean and easy. So what happens in Initialse?


This is where the fun begins. We're creating all of our properties and specifying their behaviors. Lets look at Age (line 47) as a good example. The New method has to specify Name and the default "getter". This is the bare minimum. Next we add a description which can be used (and is in the example code) for binding to a TextBlock, then we set it to not be editable and we specify the format. And finally we call the Build method to return the built ViewModel Property.

Now how would the binding work?


PersonView is very simple, just a few TextBlocks and TextBoxes binding to our ViewModel Properties. You can see that all the TextBlock "labels" bind very nicely to the description of the Property. You can also see that each TextBox binds very nicely to the Value of our Property or in the case of Age to the FormattedValue of our Property. It can also very easily be made ReadOnly by binding to IsEditable (although you do need a converter that inverts the value). For fun I've also added something to display when City or occupation are updated and when they're invalid.

As (I hope) you can see the xaml becomes nice and clean and declarative, as it rightly should be. There are no string literals in the xaml because we're binding everything to our ViewModel, including any labels. The ViewModel completely defines the View.

I really like this approach because it seems to make everything that little bit neater. It appeals to the OCD in me. But in my opinion the greatest advantage to this approach will be addressed in my next post: testing.

P.S. You may have noticed that I haven't mentioned anything about the Commands in the ViewModel. They're using a similar approach I'm just not going into them to keep the post lighter. But feel free to take a look at it in the code.

You can view all the code here.

Friday 6 June 2014

ViewModel Properties (1 of 3)

My previous post discussed using a Controller in conjunction with the standard MVVM pattern. One of the reasons for this approach is to simplify/clean the ViewModel. Another way I've found to do this is by using a class that represents a ViewModel property. Quite often when binding to a property on your ViewModel you require the property, whether it's enabled, whether it's been updated, it's visibility, etc. What if you could abstract all of this into a simple and easy to use class. Enter the ViewModelProperty (I know, not the most creative name).


As you can see this provides us with the Value, a formatted version of the value (if a format was set), validation, visibility and editability. It also removes the need to inherit from INotifyPropertyChanged in every ViewModel (although I guess you may still need to for other reasons). It's encapsulated everything into a single class.

I've also incorporated a Builder class and a Collection class. The Builder allows the user to create a property in a fluent manner (looks very pretty in code) and the Collection allows the ViewModel to view and act on all the ViewModel properties that are created. For example, let's say you want to reset all changes made to the properties, you could simple call ResetValues() on the Collection and it will do all the hard work by resetting each property instead of you having to manage it. Or you could very quickly check the validity of all the updates to your ViewModel properties through the IsValid property on the Collection.

You can view all the code here.

Friday 23 May 2014

MVVMC thought experiment

Who doesn't love MVVM right? Nice levels of abstraction and a simple binding model. Most of my MVVM experience has been with WPF and it’s been fun. However I have noticed an irritating trend where View Models tend to become bloated. The View is the view, the Model is clean (or should be) but the View Model becomes a bit of a dumping ground. Everything from loading the Model(s), manipulating the Model, business logic, interacting with services and repositories, validation, etc. It all adds up.

Bring in MVVMC. Now I thought I was being really original by coming up with this all on my own. Then I turned to trusty Google and surprise, surprise, it’s already a thing. It’s really hard to be original these days. The C stands for Controller and it’s where we want to move all the code that is not View Model specific. So to my mind you get this:


Now your View Model becomes squeaky clean. But haven’t we just moved our dirt from the View Model to the new Controller? Yes, but not really because you've moved it to a class that specifically exists to contain loading and logic for the View Model. It’s all in one place but now it’s the right place. You've increased the cohesion of your classes. Happy days!

As I see it a Controller could be shared by multiple View Models (if they’re part of the same component and share functionality). As an example, imagine you have a grid of data. You could structure it as a parent View Model with multiple child View Models and each child View Model wraps a Model. If every View Model knows about the Controller then parent and child need to know nothing about each other (except for the parent View Model having a collection of the child View Models) but both still have access to any logic in the Controller. This could be handy if say you want a Command on the parent that acts on all children and a Command on the children that only acts on itself. It would be one method (possibly overloaded) on the controller.



Two final thoughts. It makes sense to have your Controller as the starting point. So you create the Controller and that hydrates itself with View Models. It comes in very handy to have a Factory class that creates the View Models that can be injected into the Controller. With all of that you should be able to do something along the lines of Resolve<MyController> and as long as you've exposed your View Model on the Controller you're golden.



Thursday 15 May 2014

Introductions

Hello to all

I'm a C# .NET developer living and working in London. A large chunk of my experience has been in the financial industry, although I've worked in a number of others.

I feel rather lucky to have become a software developer. It turns out I really enjoy my job. I find the art (and it is most definitely an art) of software development to be awesomely fulfilling with equal parts logic, problem solving and creativity.

I've started a number of blogs in the past with very poor follow through. I'm hoping this particular attempt will have staying power. I'd like to use this as a place to put my ideas down on paper as it were and share them with the world.