Simon Online

2013-03-08

FizzBizz with F#

A while back I blogged about how I thought having a FizzBizz like problem on a job interview was a good idea. In that post I mentioned that coming up with novel ways to do fizz bizz should be fun for more senior developers. I though perhaps it might be fun to try out this F# language I’ve been hearing so much about as of late. So I poped over to the Try F# site where they have a nifty online F# interpretor. A bit of paying resulted in

F# is a functional language which has really good support for lists or arrays. Here I used the | operator which is a forward-chaining operator to pass the results from one function to the next. It is reminiscent of shell scripting (incidentally doing fizz bizz in shell scripting would also be fun). As part of F# there is a concept called a filter which acts in sort of the same way as a switch statement. It allows you to match the elements of a list and perform different actions depending on the match. That’s what you see on lines 3-6.

Being pretty new at this F# stuff I went hunting for other people’s solutions online. No better way to learn a language than to see how other people use it. That’s why github is so awesome. Well it is one of the reasons. I found a swell answer on StackOverflow inTomas Petricek“˜s answer. The gist of it seems to be that this is a functional language and we should be attempting to use it functionally. To do that we can declare an active pattern and slot that in instead of the individual modulo checks. This allows us to remove the where from the filter

So there is an F# version of FizzBizz.

2013-03-07

Thoughts on Single Entry-Single Exit vs. Return Early

There are two schools of thought behind how to construct methods. The first says that your method has one entry point so it should have one exit point. A method like that would look like

With this it is easy to see where the value is returned to the caller. Other than that there is not much good about the structure of the code. There are a lot of brackets and you have to read the whole function to figure out what it is doing. As I understand it this particular structure of code is a throwback to the days of structured coding and was used to avoid the dreaded GOTO. The other method of designing a method is to return early. If we rebuild that last method it would look like

Here we can see that there are a bunch of places which return. As we read through it is easy to see where we return. There is no need to read the entire function as we trace through it. At the top is a guard clause which will return right away if the parameters to the function are incorrect.

Now to be fair I took returning early to an extreme in this example. Everywhere I could retur early I did. If I were to come across this function in a code review it would be questioned. I would probably rewrite it to use a number of functions, something like

It is still a bit messy but that is probably more a function of a poor API for the imaginary client I created.

So the conclusion is that single entry-single entry is an outdated concept which makes code difficult to read. At the same time leaning heavily of return early createsmessycode too. Mixing the two and makingintelligentdecisions on a per method basis is the optimal strategy.

2013-03-06

Creating DataBars in EPPlus

Irritatingly frequently I encounter a request which basically boils down to “I have this amazingly complicated excel spreadsheet I’m using to stop the company from going bankrupt, can you make yourapplicationproduce it?”. So I bravely dive into it and find 96 tabs and graphs and the what not. I am terrified that so much of the business world relies on spreadsheets of this sort but my nightmarish fears are not the subject of this blog. Well not today.

I make use of theabsolutelyfantastic excel library EPPlus. In today’s nightmare I was to create a databar. This is a special sort of conditional formatting which basically creates a bar inside a cell.Screen Shot 2013-03-06 at 8.52.25 PM

The length of the bar is calculated based on the range between the largest and smallest values in the range. Aren’t they pretty?

The latest version of EPPlus adds support for conditional formatting and you too can create these sorts of spreadsheets programatically.

Basically all you do is select the range you want and assign the conditional formatting of type databar to it. As far as I can tell there is no support yet for solid fill bars.

2013-03-05

Typescript - Creating large programs

Ten years ago when I wrote JavaScript I only ever had one function and the function was always called validate. The only function for which I used JavaScript was validating for entry. Somewhere along the line JavaScript became awesome and it was possible to build large applications using JavaScript. I personally think the watershed moment was when gmail burst onto the scene. I understand that the first version of gmail waswrittenin Java using aframeworkcalled GWT which transcompiles to JavaScript. However, the point remains that it is possible to build complex applications using JavaScript.

In object oriented languages code is arranged into functions, these functions are grouped together into classes and the classes are placed into namespaces. This hierarchical approach allows for thearrangementof large quantities of code into a logical structure. For the most part this method of arranging code has gone unchallenged for decades(with the exception of AOP, but that’s a whole other post). JavaScript was never envisioned as a language for building large applications so it lacks first class support both classes and namespaces. Just as with Perl it is possible to simulate objects using arrays and even namespaces.Unfortunately,the syntax is prettyarcane.

Typescript to the rescue!

First classes. The syntax is pretty easy

This short snipped of code shows off a lot of different features of the classes. First we see a class level property in the description. Next there is a constructor fo the class. You’ll notice that the propertypublicationDate is prefaced by the keyword public. This is a great little shortcut which turnspublicationDate into a public property on the class. It is the same as if we had created a property like description then assigned a value to it in the constructor. Finally we see the use of the this keyword to denote that we are accessing a class level variable.

Now if we wanted to move this class into a namespace we would use the module directive

Modules can be described in any number of files and the JavaScript engine will combine them together for you.

The beauty part of TypeScript and other languages which compile to JavaScript is that if you decide to abandon the technology and switch back to JavaScript then the exit cost iseffectivelyzero. TypeScript produces this, very readable, JavaScript from our module and class

2013-03-04

Typescript - Compiling your first program

I have been using typescript which is the newishMicrosoft language which compiles to JavaScript in a lot of my blog posts lately. It occurred to me that I haven’t actually written anything about typescript by itself. I’m really a big fan of many of the things typescript does so let’s dive right in.

The first thing to know is that typescript needs to be compiled by the typescript transcompiler. There are a number of ways to get the compiler. You can install it as part of a node.js install using npm, the node package manager. You can download the visual studio plugin or you can compile it from source. Compile it from source? What is this, linux? Actually the compiler is written in typescript. I guess that this is a pretty common thing to do when you build a compiler: build a minimal compiler and then use that to build a more fully featured compiler. It boggles my mind, to be perfectly honest.

Anyway, I installed the npm version because I’m doing most of my web development using the Sublime text editor. The command line is very easy, you can pretty much get away with knowing

./tsc blah.ts

This will produce a javascript file called blah.js. I recommend that you keep the default of naming the javascript files after the type script files, it will help you keep your sanity. If you really want to rename the output you can do it with the out flag

./tsc blah.ts -out thisisabadidea.js

There are a number of other flags you can use including a bunch of undocumented flags you’ll only find by reading the source. The most useful flag is -w which watches the .ts file and recompiles it when there are changes. This is useful if you’re developing you code and don’t want to have to keep dropping to the command line to recompile and then refresh in the browser.

The first thing about the typescript language itself you need to know is thatit has a hybrid type system. Typically javascript performs type checking only at runtime, by default this is the same thing that typescript does but typescript allows you to perform some type checking by annotating your variables with a type. To do this the syntax is to add : type to a variable declaration. These can be used in functions and in declarations. For instance:

If we change the call to this function to

Then try to compile it typescript will throw an error

Supplied parameters do not match any signature of call target

This is obviously a very simple example but I have found that typescript quickly pulls out silly typing errors which normally I would have to check with unit tests.

Tomorrow we’ll look into some more features of typescript.

2013-03-01

Force Directed Graph 2

Yesterday I showed creating a force directed graph with a dataset taken from wikipedia. As it stood it was pretty nifty but it needed some interaction. We’re going to add some very basic interaction. To do this we’ll use the data- attribute we added when building the graph. These attributes were added as part of HTML5 to allow attaching data to DOM elements. Any attributes which are prefixed with data- are ignored by the browser unless you specifically query for them.

I started by adding a set of buttons to the page, one for each show.

Then I added a simple jQuery function to hook up these buttons and filter the graph

First I reset the graph to is original color, then I select a collection of elements using the data-productions element. This is a stunningly inefficient way to select elements but we have a pretty small set of data with which we’re working so I’m not overly concerned about the efficiency. It could be improved by using a css class instead of a data-attribute as these selectors have been optimized.

The final product is up athttp://bl.ocks.org/stimms/5069532

There are a bunch of other fun customizations we could do to this visualization. Some of my ideas are:

  • Improve the display of name labels during hover
  • Highlight linksbetweenpeople when you hover over a node
  • Show the number of collaborations when somebody hovers over a link

That’s the best part of visualization: there is always some crazy new idea to try out. The trick is to know when to stop and what you can take away without ruining the message.

2013-02-28

Force Directed Graphs

In talking with a friend the other day he mentioned that everybody at his work was all agog about a TED talk which had a cool looking graph in it. He promised that he wouldabsolutely100% pinky swear send me a link to the talk so I could try to recreate it. He didn’t.

I had a pretty good idea what it was he was talking about though: a force directed graph. The idea behind a force directed graph is that you have a number of connected nodes which are attached using springs and attracted by gravity. These graphs can be used to show relationships between a number of items and they are interactive so that they can be dragged around to see what the data would look like from a different direction. The proximity of nodes to one another can denote the strength of the relationship.

Let’s try to recreate it using our good friend d3.js. The first thing we need is a set of related data. Wikipedia is a great source for data of this sort of data. A good data set for a demonstration will have nodes which are connected to more than one other node and may have another aspect to it like that some of the nodes share another property. This additional degree of relationship can be denoted with colour.

I took a look at a few pages of data but I’m a nerd so I chose the dataset of actors with whom Joss Whedon has collaborated. If you just clicked on the link to see who Joss Whedon is the you get off this blog, you get off and you never come back.

I started by pulling the table from wikipedia and then transforming it into JSON. I got some help in doing that fromhttp://jsonlint.com/which is a great tool for checking and formatting JSON. The file is pretty long but a chunk of it looks like

You may notice that I included the names of the productions and their medium. We’ll see more about this tomorrow when we add filtering to the graph.

Fortunately for us d3 provides some helpers to set up a force graph. I basically stole my entire graph code from Mike Bostock’s page. d3 requires that you set up a list of nodes and edges.

Nodes are quite easily set up and are just represented as circles. This is pretty much what we’ve seen before except that we call force.drag which, if you drill into the example you’ll see allows for moving the nodes

The edges have different strengths, the higher the value of the links the stronger the connection so the closer the nodes would be. I built the links based on the productions shared between the two people. The code for extracting the shared productions is”¦ umm”¦ not pretty. I really don’t know how you would make it prettier other than changing the underlying data structure. So I guess the lesson here is: pick data structures which work with your requirements.

The resulting graph looks like this:

GraphGraph

If you want to see the interactive version you should pop over to http://bl.ocks.org/stimms/raw/5061669/

2013-02-27

Search Everywhere is the Future

Today I was demoed an in house application. It was what I have come to think of as a typical in house application: that is say lacking some attention to usability. I see this all the time and I think that not spending time on good usability and attractive design serves to make people think less of the application. You hear “Oh that accounting software sucks, it is so hard to use” and eventually the software is replaced sooner than needed and at a higher cost. Anyway that’s not what this blog is about, it is about search and how it is the killer user interface.

In the application I was looking at, let’s give it a random 3 letter acronym as all with in house software: TYM, there was a form which required you to select an employee. The employee selection was a drop down box with 2600 entries in it. I asked why the usability on that drop down was so bad. Why weren’t there at least some filters? “Oh,” said the lady demoing it ,”you can use hyperscroll”. Hyperscroll?! I haven’t seen hyperscroll before so I had her demo it. Turns out it is just the search you get when you go into a drop down and type the first letters of the entry. In a list of 2600 entries that approach isn’t great. There is limited space in a drop down and the UI paradigm just doesn’t adapt well to that many entries. It also isn’t good if you’re looking for a last name and the list is sorted by first name.

This is a perfect place to use a search. Search doesn’t have to be big and involved it can be very simple and small, it can even be an autocomplete box. Heck, you don’t even need to make the search server side! I believe that in an era of lots of data the utility of the drop down, or combo box is limited. There are still some times when the entries in a drop down are fewer than, say, 10 that a drop down is the correct approach. Of course it is difficult to know when your data will exceed the number of entries so you might be better off building the search in right off the bat.

This wasn’t the only place in TYM which would havebenefitedfrom a search. There was another form which contained a wall of check boxes. I mocked up this example but TYM was far more extreme.

CheckboxtopiaCheckboxtopia

Again this is a place where search would have been a better solution. The typical approach I take in this situation is to provide a tagging mechanism like the one provided by TagIt. This approach it not asintuitiveto users but once they have the hang of it they will like it far more.

I really think that a few minutes of care and attention in user interface design will win your users over to you.

2013-02-26

AngelaSmith - Creating Test Data

Yesterday I blogged about a rapid data prototyping tool called AngelaSmith which permits building realistic test data. Today I’m going to show you how to make some use of it. The first thing we need is a model on which to operate. Ever since I read the license agreement for Java 1.1 which explicitly prohibited the development of software related to airplanes I’ve liked example code which references airplanes. I even had a text book at one point in which all the examples were related to the flying of planes. I can’t remember which book it was but it might have been an old Deitelbook.

Anyway let’s start with this model:

This can be filled with AngelaSmith

But if we print out the data we can see that Angela wasn’t quite smart enough to look at substrings of the field names to perform matches. That’s a shame and probably going to be a pull request.

Not great test dataNot great test data

I did have a good laugh at the idea of a pitchfork with a range of 58km. That’s a long pitchfork!

So we’re going to have to set up some custom rules for the data generation

For the most part we can lean on Jen(oh such witty and confusing naming) to do the population for us, but you can see that I used my own custom generation method for flight numbers because they’re not really standard.

Better generationBetter generation

Well that was pretty easy! Thanks, Angela, you’re the best.

2013-02-24

Using Realistic Data in Unit Testing

I was writing some unit tests the other day around some code what was missing them and I encountered a couple of field names which confused me. They were well named fields but within the domain I was working they could have a couple of different meanings. This isn’t the fault of the programmer and there are times when even the domain experts are a bit muddled about their terminology. Ideally we developers should work with the domain experts to sort out their language and ensure that everybody has a solid understanding of the domain. This isn’t always possible and you might end up with a field like PlantName which could be a couple of things.

I wasn’t keen on changing the field name as the code interfaced with other systems and I really didn’t want to coordinatesimultaneousreleases with our IT department. What I did, instead, was use the unit tests to clarify the content of the fields. The two meanings of theambiguouslynamed field had very different looking data in them. So I made sure that the data I put in corresponded with the right meaning for the field.

This isn’t what I typically do. I constantly use test data which is a random splat of letters or numbers without meaning. If, however, you take the extra few seconds needed to put in realistic data then you gain a couple of advantages:

  1. Thosereading your testsimmediatelygain a deeper understanding of what it is you’re testing.
  2. You may uncover subtile bugs which you would miss with random data. For instance consider an application which did word stemming: you’re likely to see a different result if you use the test data “running”(run) instead of “fkjdsklfjadsli”.

While I was thinking about this Istumbledon the blog of my Calgary .net hero David Paquette. Dave, in conjunction with James Chambers, announced tool called AngelaSmith named after the British Labour Party Politician who was instrumental in changing the law to afford those attacked by dogs better protections. Dave and James are real activists for the protection of those injured in dog attacks so I can see why they are using the name. Their tool allows for the creation of realistic test data using a variable name based strategy.

What’s that mean? It means that if you have common names in your code like “FirstName” or “LastName” then AngelaSmith will put in realistic values from its own database. AngelaSmith has built in values for a lot of common fields but if you have something weird, like I did you can put in a custom population strategy and have AngelaSmith generate values for you.

The project is pretty much brand new but it is a great idea and I hope it is something which James and Dave choose to continue.

I’ll post up some examples of how to use and extend AngelaSmith in a bit but for now the introduction on the github page is sufficient:https://github.com/MisterJames/AngelaSmith