At Leeds Sharp the other day, we started doing the F# Koans as a way of of trying out the language, with the aim of expanding our minds with some functional programming. A bit like coder’s LSD, if you will.
The koans are pretty good at introducing you to things, although initially it’s a bit too easy to get through them without really understanding what’s going on.
However, when you get to the stock example that all changes, as you have to actually use some of what you’ve learned to solve a more involved problem. The purpose of this post is to put up my solution in the hope of getting into a bit of a discussion with others who’ve done it, at Leeds Sharp or otherwise. I have no doubt that my implementation could be improved, so any advice would be more than welcome!
module ``about the stock example`` = let stockData = [ "Date,Open,High,Low,Close,Volume,Adj Close"; "2012-03-30,32.40,32.41,32.04,32.26,31749400,32.26"; // ... "2012-02-29,31.89,32.00,31.61,31.74,59323600,31.74"; ] // function to split a comma-separated string into an array let splitOnCommas (dataAsString:string) = dataAsString.Split([|','|]) // function to take the desired parts of the array as a tuple, // including opening-closing difference let createPriceDifferenceTuple (fullList:string) = ( fullList., abs (Double.Parse(fullList.) - Double.Parse(fullList.)) ) let maximumDifferenceTuple = // split strings into arrays, ignoring header List.map splitOnCommas stockData.Tail // map arrays to tuples |> List.map createPriceDifferenceTuple // get maximum tuple based on second element (price difference) |> List.maxBy snd [<Koan>] let YouGotTheAnswerCorrect() = let result = fst maximumDifferenceTuple // get date, first item in tuple AssertEquality "2012-03-13" result
For anyone using VS2010, one tool you need to try out is NuGet (actually pronounced new-get according to Microsoft, but what do they know?!).
What is it?
NuGet is Microsoft’s answer to the much-lamented gap in the .Net space for a package management tool like Ruby’s Gems or Linux’s RPM.
NuGet simply looks after the download and installation of tools and libraries you use in your projects. It will get the appropriate version of all needed DLLs, configuration files, and related tools, put them in a folder, and do any configuration if needed. Simple! Also useful is the fact that it will download any dependencies – so for example if we want to install Shouldly, which uses Rhino Mocks, NuGet will get the appropriate version of that as well.
And that’s about it. So it won’t change your world, but it will save you a good few hours each year hunting for, downloading, and installing tools.
NuGet started out as NuPack, which kind of took over from the Nu open source project. Indeed, NuGet is itself open source, continuing Microsoft’s trend of a more transparent and community-involving future, which is nice.
There are other package managers for .Net, including:
However, as usual, things don’t tend to take off in the .Net community until Microsoft makes their version, which then becomes king. I haven’t tried any of those package managers, but I wouldn’t want to bet on them being too successful now NuGet’s out.
Anyway, enough of the history lesson, how do I use this thing?!
Firstly, you need to get it installed, which is simple as it’s in the Visual Studio Extension Manager (Tools -> Extension Manager). Search the Online Gallery for ‘NuGet’ and you should find it:
A couple of clicks later and you’re ready to go!
Putting it to Use
There are two interfaces. You can either right-click on a project and select ‘Add Library Reference’, and find what you need with a handy visual interface (the same as the Extension Manager):
Or, by selecting Tools -> Library Package Manager -> Package Manager Console, you can use the Powershell-based console version, like a real developer!
(Check out some NuGet Console Commands, if that’s how you want to roll.)
Either way, you’ll end up with a new ‘packages’ folder in your solution, containing the bits you need (as well as having references automatically added to your project, and configuration set):
Et voilá! You’re ready to log/unit test/mock/whatever to your heart’s content.
You can also delete packages, update packages, and so on – it’s all pretty straightforward, so I’ll leave you to work that out.
So what are you waiting for? Go and nu-get it now!! (sorry..)
I just put up a page with a load of book reviews. It’s not finished yet but there are a fair few on there. Check it out if you’re looking for a good read!
describe User do it "should be in any roles assigned to it" do user = User.new user.assign_role("assigned role") user.should be_in_role("assigned role") end
it "should NOT be in any roles not assigned to it" do user.should_not be_in_role("unassigned role") end end
Aside from the test name being a string, you can see the actual assertions in the format ‘variable.should be_some_value’, which is kind of more readable than it might be in C#:
Admittedly, the second example is nicer to read – the trouble with that is that you’re checking a true/false result, so the feedback you get from NUnit isn’t great:
Test ‘Access_Tests.TestAddUser’ failed: Expected: True But was: False
Fortunately, there are a few tools coming out for .net now which address this situation in a bit more of a ruby-like way. The one I’ve been using recently is Shouldly, an open source project on GitHub.
And so on. Not bad, not bad, not sure if it’s worth learning another API for though. However, the real beauty of Shouldly is what you get when an assertion fails. Instead of an NUnit-style
But was: 2
– which gives you a clue, but isn’t terribly helpful – you get:
should be 3
but was 2
See that small but important difference? The variable name is there in the failure message, which makes working out what went wrong a fair bit easier – particularly when a test fails that you haven’t seen for a while.
Even more useful is what you get with checking calls in Rhino Mocks. Instead of calling
fileMover.AssertWasCalled(fm => fm.MoveFile(“test.txt”, “processed\\test.txt”));
and getting a rather ugly and unhelpful
Rhino.Mocks.Exceptions.ExpectationViolationException : IFileMover.MoveFile(“test.txt”, “processed\test.txt”); Expected #1, Actual #0.
With Shouldly, you call
fileMover.ShouldHaveBeenCalled(fm => fm.MoveFile(“test.txt”, “processed\\test.txt”));
and end up with
0: MoveFile(“test1.txt”, “unprocessed\test1.txt”)
1: MoveFile(“test2.txt”, “unprocessed\test2.txt”)
As you can see, it’s not only much more obvious what’s happening, but you actually get a list of all of the calls that were made on the mock object, including parameters! That’s about half my unit test debugging gone right there. Sweet!
Shouldly isn’t a 1.0 yet, and still has some missing functionality, but I’d already find it hard to work without it. And it’s open source, so get yourself on GitHub, fork a branch, and see if you can make my life even easier!
Perhaps strangely for a developer, I much prefer reading from actual, physical books & magazines than a computer screen. This is a bit problematic these days, as what with the rise of the Internet, nobody seems to be printing programming magazines any more (in the UK at least).
As such, I was most pleased to hear about MagCloud, an online service which offers printed magazines in a FUBU (For Us By Us) style. Basically, anyone can upload a magazine in PDF format, and for a charge of around $0.20 a page, MagCloud will print it out and send it to you. This works out at around £5-6 for a magazine of 40 pages, which is a little expensive but not too bad. (There’s a delivery charge of $2-3 too, so you’re better off getting a couple at a time). While the authors can make money from this (by adding on an extra charge per page), none of the ones I was looking at did so.
The two I checked out are well written and informative:
Hacker Monthly, a general programming magazine, and
Rails Magazine, about Ruby/Rails. I couldn’t find any specific .Net ones when I looked, but it’s pretty new so I’m sure one will appear at some point. So if anyone fancies starting a .Net mag, here’s your chance!
Now, many of these are available as PDFs for you to download as well, so you could quite easily print them off yourself and save a few quid. Personally, I’m too lazy/disorganised for that, and I like to have a proper magazine and not a scruffy collection of stapled sheets, but that’s just me.
Check it out. What have you got to lose?!
I’ve been writing a simple app to try out Windows Presentation Foundation (WPF) using the Model-View-ViewModel (MVVM) pattern, so I thought I’d post it in case anyone found it useful – there don’t seem to be many end-to-end examples using MVVM around. I’ve tried to stick to good practices, although there’s still a fair bit of discussion in some areas about what the best way to do things is.
Before you read any further, if you’re looking for an example of a decent WPF UI, stop now! I can assure you, you’ll only be disappointed.. I used a theme so it wasn’t grey, but that’s about it. It’s all about the code!
The source code is here: https://github.com/relentless/wpf-diet-recorder
You’ll need Visual Studio 2008 and above to use this (I haven’t tried it with 2010, but it should work Ok).
The app lets you record your weight and some notes on the Measurements screen:
This can be done for multiple users, which are set up on the Users screen:
(You might notice the Users screen allows you to define custom measurements for the users – these aren’t used anywhere at the moment, as putting that in was making it too complex for this example).
A couple of interesting things in there are:
- Automated Unit Testing (of course!)
- Composite views (the ‘custom measurements’ part of the Users screen is a separate user control with its own ViewModel)
- No code-behind
- Commands using DelegateCommand
Although there aren’t as many unit tests as I would like, there should be at least examples of the main things you’d want to test. (My only excuse for the lack of tests is this was my first WPF app, and as such basically a prototype, so I was working it out as I went along).
I’ve used Roy Osherove’s naming convention for the unit tests (MethodName_StateUnderTest_ExpectedBehaviour), as I like it. I’ve also stuck with the AAA pattern for the test layout (Arrange, Act, Assert), and when I’ve used Rhino Mocks for test isolation, that’s been in ‘AAA mode’.
There is still much discussion in MVVM circles about whether ValueConverters should be used, or if the ViewModel in MVVM should render them unnecessary. I’ve used ValueConverters as I don’t want to have too View-specific things (such as Visibilities and Colours) in my ViewModel, but some people (including Josh Smith, the father of MVVM) disagree. To be honest, it doesn’t matter much (especially if you’re just starting out), but it’s good to be aware of your options.
Always tricky to know where to put the validation – in this case, I’ve gone for validating the data type in the ViewModel, and any more complex validation (string lengths, max and min value, etc) in the model itself.
Libraries / Tools
The things I’ve used to build this (aside from VS2008) are:
- NUnit for unit testing
- RhinoMocks for isolation (mocking)
- Versant DB4O for the data store (it’s an Object Database, so don’t go looking for the SQL!)
- WPF Toolkit for the theme
- WPFMessageBox for the message box
If I was to continue developing this example, there are a couple of things I’d probably want to do:
- Make some kind of Application Controller, which would contain the ugly startup code from App.xaml.cs and be in charge of opening forms
- Use an IoC container such an Ninject to resolve those dependencies
- Probably take the data loading/saving logic out of the ViewModels and find somewhere more appropriate for it
Hopefully someone might find that useful. If you have any questions, feel free to get in touch.
TekPub is a website set up by Rob Conery and James Avery, two very respected named in the world of development, to deliver video content on many development-related subjects. Rob’s one of my development heroes, who previously worked for Microsoft on ASP.Net MVC, gave us the SubSonic data access framework, and has much good content on the web already in video and blog form.
Anyway, TekPub isn’t free, a year’s subscription costs $200 (or you can pay on a per video or monthly basis), but there are several free videos on there which are well worth watching. (I luckily won a year’s free subscription at a NxtGenUG user group meeting, which is what took me there in the first place).
There are two free series of videos, which are both useful. One is based on Mike Gunderloy’s book ‘Coder to Developer’ and basically discussed how to move from a cowboy to a professional developer, making proper use of things like source control and project organisation tools. Not much new for a seasoned developer, but useful for many currently making the journey.
The other free series is called ‘Concepts‘, which (using C#) covers a lot of the things a growing developer needs to learn – IOC Containers, Unit Testing, Interfaces, and even Behaviour Driven Design (BDD).
And if you’re willing to fork out, there are tens if not hundreds of hours of content on subjects from ASP.Net MVC to iPhone development, jQuery, Git, Ruby, and many more.
So instead of turning on the TV tonight, get over to TekPub and learn something useful instead!