Monday, 4 May 2015

Kata - Part 2: In which speed becomes the primary focus

Pursuant to part 1, this is the story of how the speed-run kind of got out of hand.

So I was chasing this time: 12:44. It was faster than I'd ever been, and... there was that damn smiley-face mocking me.

I sat down and thought about it for a while. The first step of optimising for speed is simply this:

Do less.

So I did -- using the tooling at my fingertips, learning more about what I could get it to do, trusting in the R# completion a bit more (which I used to trust only when I couldn't be bothered to type something out in full or when I wanted to take advantage of the automatic library inclusions) and figuring out how I could write my code with the least keystrokes -- with the proviso that the code still had to be something I liked. That means no single-character variable names or stupid test names. My tests must still describe what they do -- they still have to follow the template

{MethodName}_Given{Input}_Should{ReturnSomething or HaveSomeEffect}

My implementation should still be pleasurable to read. I'm an advocate of the idea that good code doesn't need comments because it already reads like a story, conveying the author's intents to the reader whilst simultaneously allowing the compiler to convey the author's intents to the host machine.

I also still had to follow TDD: write a test, test must fail for the correct reasons, write simplest implementation, test should pass, optionally refactor if I can think of a better way to write it. It's important to note the "optionally" part of this last step: when optimising for speed, I don't want to compromise code quality, so I try to write the "best" code first. I do think that I can write prettier code (and I have, for the same kata), but I have allowed simpler code where that would shave seconds off of the final time.

Of course, the next place you get to after "do less" is quite simply "get faster". Whilst engaging in that cycle though, being aware of ways you could "do less" whilst still maintaining the parameters of the assignment becomes vital: sometimes getting faster at a particular unit of work uncovers how you could do less there (or elsewhere). It's quite a lot like optimising code for execution times.

My speed-run implementations centered around an extension-method approach, which I think provides a level of readability to the final result. Extension methods are, IMO, one of the best features of .NET and I use them in production to make code read better -- code which reads better is easier to maintain and has less ramp-up time for the new developer who invariably is saddled with the troubles of coders past.

I slowly whittled away at my 13:48:
10:42...
09:16...
08:48...
and, this morning:
07:35.

Now bear in mind that Katarai does give me a little time boost here: the system bootstraps a solution with a shell test fixture and a shell implementation which has the Add method throwing NotImplementedException. So if I were to do this bare-bones, I'd expect probably another 30 seconds for creation of those files. In other words, I'd like to recognise that this isn't the time required to write every character of code in the outcome. On the other hand, I also make mistakes in this run, so I could theoretically go faster -- though I'm not sure if there's any point in trying to do so (and I also said that when I did 10:42, so... yeah...).

You can view the kata here: StringKata 2015-05-04, completed in 07:35 if you'd like.

I had to tweak my whole way of doing things to get down to this time, including
  • moving my taskbar to the right so that Katarai wouldn't overlay the area I was working on
  • learning to trust in R#'s code completion more
  • using R#'s CamelCase feature
  • learning the requirements for the kata so intrinsically that, in this particular run, I actually "forgot" where I was in the whole process, but somehow continued to write the next correct test. Weird.
The question, of course, is what the value is of completing a kata in this kind of time. I'd argue that a lot of the value of the kata is lost once you've got to the point of knowing the steps and your counter-argument implementation iterations so well. I'm not thinking about a new way to complete the problem. I'm not critically analysing my thought processes around the problem or TDD. I'm blindly banging it out... Write test!... Run all!... Write code!... Run all!... Write test!... Run all!... Write code...! Lather! Rinse! Repeat!.

I had actually argued that I thought I wasn't gaining anything once I got past around 12 minutes, until a conversation with Chris Ainslie this morning. He raised the same question: "Once you're going that fast, is there anything to gain from the kata?". In talking it out though, I can attest that there is something to gain in a pure speed-run, much like there might be something to gain through placing another arbitrary constraint on the problem, a practice which is sometimes used to stretch the kata or make the process a little more mindful. Constraints that I have tried for a kata include:

  • No mouse (this will get you familiar with your keyboard shortcuts, for sure)
  • Implementation has no variables or state or loops. LINQ is allowed. Logic is allowed, through the terniary operator only. All member methods start with the return keyword (I find the result from this constraint set particularly pleasing and it's the basis for my speed-run result, though being pure on this does take a little longer).
  • Implementation makes use of no LINQ or inbuilt string functions (yes, write your own Split! Just like grandpa used to! *ahem* I mean, just I like I used to, back in the days of C)
By making the constraint the rather open-ended "shortest time possible", I have gleaned the following:
  • Learned more about my tooling (I've mentioned R# and code completion, for example)
  • Practice typing for speed and practice reducing typos when typing at speed!
  • Learn to evaluate a prior test as a possible candidate for a shell for a new test which can be modified and used in a shorter time than writing the test from scratch
  • Enforcing a strict adherence to readable code, even when time is tight
  • Enforcing a strict adherence to TDD, even when time is tight
  • You can always get a little better; always go a little faster. Translated to production code, this makes me more critical of the code that I am writing -- could I have done it more succinctly (but still make it read like a story)? Have I done the smallest thing possible or am I gold-plating? Am I implementing features which aren't (at least not yet) actually required? This last one trips us all up: we all too easily get into a mindset of trying to produce perfect code instead of great code which can be extended on requirement.
At the very least, this video should suppress the argument that I have heard that doing a String Kata in 20 minutes is a ridiculous requirement. If I can do it in 07:35, so can you -- indeed, I bet this is still far from the floor of times that are possible for this kata.

Kata - Part 1: The gauntlet is thrown.

Kata are, according to Wikipedia, foundry of all knowledge (and often of factually correct knowledge) "the detailed choreographed patterns of movements practised either solo or in pairs".

In software circles, there's a similar concept, embodied by the practice of test-driven code exercises, often with the premise of a rather synthetic problem which the user (or pair) is left to solve in the strictest sense of TDD that she/he/they can muster. The point is to provide a problem which isn't necessarily new or tricky, leaving the body of the exercise to the players to practice their TDD cadence:
  • Red: write one test and one test only, which tests a very specific requirement of the specification. Running all tests should give one "Red" result (one test fails, on purpose, for the intended reason).
  • Green: implement the bare minimum code to get the last test to pass. Running all tests should give all "Green" results (all tests pass).
  • Refactor: step in which the practitioner evaluates the code which was implemented to make the test pass and optionally renames, refactors or tidies up. If the code is deemed to be in a good state, the process is repeated.
Performing code katas provides the practitioner the opportunity to practice the strictest sense of TDD as well as examine programming, testing and style habits. The main idea is that the perfection which is sought during the kata will seep into production code. Some supplementary goals are to strengthen the practitioner's familiarity with her tools, hone her skills and encourage thought of alternative paths to the solution which still adhere to the TDD cadence. In addition, a kata can be used as a "jump-start" for the code "juices" as it were: an exercise where the output will be discarded (and hence isn't completely material), but where the practitioner's thought patterns can be aligned with the environment of programming towards a goal in preparation for production work.

At least, I've found it can be a good way to get the coding started.

I work at Chillisoft where one of the products in development at the moment is a kata assistant: Katarai. (Full disclosure: much of the gruesome innards of Katarai are the result of a fevered few tinkering sessions with a colleague, Mark Whitfield, so I kind of have a dog in this race, though I'm not part of the active development team for it).

Katarai aims to address a few issues with the code kata concept:
  • Seasoned developers often can't wrap their heads around the concept of writing code you know you're about to throw away, or the concept of practicing TDD cadence simply for the practice. Katarai provides feedback of your progress through a kata as well as providing (in the future), feedback about your improvements / changes over time (and potentially a competitive flavour in that you could compare times or other metrics you derive from katas with those of your friends).
  • Juniors may find it difficult to get into katas -- the code requirements can be a little esoteric and the TDD cadence hasn't taken hold yet.
  • Code katas aren't necessarily fun by nature -- Katarai tries to change this perception a little.
  • Katarai also times your attempts -- which leads us to where we are with this article. More on that later. 
(and probably others).

I gladly postulate the code katas are beneficial for programmers of any level. You could use them to familiarise yourself with a new language, you can use them just as part of the rhythm of your coding day, you can use them to keep your keyboard and tooling skills tip-top... Basically, you can use them for the same reasons martial artists do:  

"The basic goal of kata is to preserve and transmit proven techniques and to practice self-defence. By practicing in a repetitive manner the learner develops the ability to execute those techniques and movements in a natural, reflex-like manner."

Replace "self-defence" with "the skill you aim to master" and you can see how the concept applies to code (:

Recently, there was a challenge at work to complete the String Kata (yes, I really did just push you off to Google there -- there are too many great links to follow!) in under 17 minutes. The challenge isn't all that foreign to us: a few months back, a requirement was put forth that all developers should be able to complete the String Kata in 20 minutes or less to demonstrate proficiency in their programming environment. The original "20 minutes" requirement could be met in any language and environment of choice. The 17-minute challenge was done as part of internal testing for Katarai, so had to be in C#, using Visual Studio, though addons and extensions which facilitate production are also allowed.

I had already been testing out Katarai (that whole "dog in the race" thing), so I ran a quickie and submitted my time for the competition: 13:48. I thought that was a reasonable time; it was certainly well under the required 17 minutes and one of the fastest times I had recorded. I was quite pleased with myself.

It wasn't long until Peter Wiles replied to the mail thread to the effect that he had completed in 12:44.

The time was a challenge. The little smiley-face at the end of the email was just plain infuriating.

Read more in part 2

Tuesday, 14 April 2015

RequireJS + AngularJS + A different spin

I keep on meaning to post this tutorial here -- it's been on github for a while and I somehow didn't manage to add it here...
Anyways, this was part of a discovery mission for using RequireJS and Angular to build a simple app. Angular because I like it as an MVC framework for Javascript and RequireJS because, really, who wants to maintain script tag spam in your SPA? Not me, not after I had a page with 20 inclusions and realised it was indicative of something horribly wrong.
The method I chose also makes this code easier (for me) to test: Angular has some great mocking and testing functionality, but in the face of Karma+Jasmine, it just seems like far too much effort to figure out another mocking framework -- not to mention that I find the concept of having to $apply to get Angular to run its magic a little counter-intuitive and a little out-of-place in a test (imo).
So I flipped this a little on it's head: the controller module in this project doesn't actually register a controller -- it returns the configuration which can be used to register a controller -- which is consumed by app.js so that routing can work with the configured controller. This frees me up to test the controller in a simpler way: test that the array has the correct dependencies, in the correct order (typically, just '$scope') and then test that the scope passed in is modified in the expected way (properties and methods added and the methods work as expected). I must point out the obvious here: that I'm not inclined to use Angular factories and services -- but who needs them if you have RequireJS and go the prototypical route?
But enough blah-blah. If nothing else, this tutorial can demonstrate one way to do it. I've also made JQuery private so that the only library in the global scope is Angular -- and this was mainly so that angular-route would load up correctly. There's probably a better way do to this too (I've read about AngularAMD and some others; just haven't play-tested them), but I was satisfied enough with the final result -- and it might prove at least a little interesting for some (:

Tuesday, 31 March 2015

Update to promises tutorial

For anyone who is interested, my promises tutorial has been updated to include info and examples about the native ES6 Promise prototype. You can get some goodness here: http://davydm.blogspot.com/2014/10/javascript-and-promises.html

Wednesday, 21 January 2015

EntityFramework: getting to the bottom of a murky error

In doing some work using EF which talks to existing databases on MSSQL in production and SQLCE for testing (check out https://github.com/fluffynuts/OrmNomNom.git for an example of using SQLCE and a transient database to do Entity testing -- there's also a bit in there about using NHibernate too), I used the Entity POCO generation tools to quickly spew out the classes that should work when talking to the existing database. I also wrote some FluentMigrator migrations so I could get a temporary database up to speed and set off to use that method to test some database interaction, when:
Boom! InvalidOperationException ("Sequence contains no elements").
Now the befuddling aspect of this exception is where it was thrown. I basically have some code like:
using (var ctx = new DragonContext(db.CreateConnection()))
{
    var unit = new SupplierPriceList() 
    { 
        SupplierPriceListID = "test", 
        SupplierID = "foo", 
        MaterialID = "foo", 
        CompanyCode = "foo", 
        Date = DateTime.Now, 
        SupplierPrice = 1.23
    };
    ctx.SupplierPriceLists.Add(unit);
    ctx.SaveChanges();
}
And the exception is thrown at the point of the call to Add(). Which doesn't seem to make a lot of sense as the temp database being used has no rows in any tables, so of course SupplierPriceLists is empty and one might expect that to be the source of the exception, considering the text, but it really shouldn't matter. Tables are empty all the time and we can add rows to them. Still, the error befuddles...
Looking at the stack trace, I see the last two frames are:
   at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
   at System.Data.Entity.Utilities.DbProviderManifestExtensions.GetStoreTypeFromName(DbProviderManifest providerManifest, String name)
Ok, so the last frame explains the raw reason for the exception: something is doing a Single() call on an empty collection. But what? The call one up looks interesting: GetStoreTypeFromName seems to suggest that Entity is doing a lookup to find out how it should store the data for that property. So, on a hunch, comment out all properties except the implied key field (SupplierPriceListID) and the Add() call works. Hm. Perhaps SQLCE doesn't like the
double?
fields? Nope -- uncomment them and things still work.
Then the culprit leaps out. The generator tool has annotated a DateTime? field with:
[Column(TypeName = "date")]
Removing the annotation causes the error to subside -- and the SaveChanges() call on the context passes, on both MSSQL and SQLCE
I thought I'd just make a record of this here as I found nothing particularly useful through much googling and eventually found and resolved the problem based on a hunch. Perhaps this post can save someone else a little mission. Of course the DateTime? value is truncated for the Date field, but hey, that's what the client originally intended...

Wednesday, 10 December 2014

Let reason prevail

Hark! 'Tis the call of a higher-order language. It beckons with sweet words of reduced time solving ancient, low-level problems! The siren speaks true!

Seriously though...

Higher-order programming languages afford the competent programmer a method for solving more higher-level problems in the same timeframe than she could in with a lower-order language. Simply put, high-order languages (like C++, C#, Python, Ruby, PHP, etc) afford the programmer the ability to skip over the low-level "move this byte to this address" kind of programming so that she can solve more interesting and/or more lucrative problems.

There is a cost though: iron. These higher-order languages require smarter compilers and, typically, more RAM and CPU. It's a cost we're happy to pay though -- iron is cheaper than development.

But when someone starts making outlandish claims that a higher-order language is more proficient than a lower-order one (https://isocpp.org/blog/2014/12/myths-1, see the string concatenation example in the first section), the reasonable programmer doesn't just gulp that down, even if it does come from the father of C++. Actually, especially if it does come from the father of a higher-order language, since he would have reason to pad out his results (or pretend to be lazy) to make his prodigy all the more appealing.

Aside: before we go any further, a disclaimer: I like C++. I like C. That's OK to like both and recognise their strengths. What's NOT ok (imo), is to spread misinformation to highlight the language of your preference. Have honest reasons for preference -- by all means! -- and be objective about comparisions. And the discourse continues!

So let me make a really bold statement:

Any proficient code in a higher-order language can only hope to be (at best) as proficient as proficient code in a language of lower-order for solving the same problem.

Why?

Let's take the string vs char* example from above:

std::string has to be implemented (at some point) around a buffer of memory. I don't care if it's char*, wchar* or whatever. It's a buffer which, at some point, was obtained via malloc() (even if you want to say it was obtained by new char[], that still boils down to essentially a malloc, so let's stop arguing semantics). The C++ compiler affords us the ability to overload operators, such that we can do:
string1 + string2
and get another string. Under the hood, this is allocating a third string object and the associated memory and doing some memory copying. One way might be to malloc() on strlen(string1) + strlen(string2) + 1 char for the null terminator, then strcpy() and strcat() in the parts. There are quite a few ways this could be done, but this is one.

Now the problem lies here: in an opaque, higher-order implementation of string concatenation (for example), the best outcome we could hope for is the one which is fastest in C, ie which we discovered by trying all paths including strcat, memcpy, strcpy, etc. So let's assume that the best path was chosen for std::string's + operator overload. That still makes it only as fast as the best implementation in C. Take a step back and realise that the + operator may also do clever things like allocate more memory than required to save on a realloc() later as well as rudimentary bounds-checking or what-have-you, and it's easy to see why the string variant is 10-20x slower (https://github.com/fluffynuts/cpp_vs_c.git -- oddly enough, the disparity was greater on a win32 version I did earlier today where the sprintf() version took only 48ms for 32768 iterations vs over 600ms for the string version. The code linked here reports the following results on my Linux machine:

C++ function: 32768 runs took 5827 ms
C function: 32768 runs took 706 ms
C function (sprintf): 32768 runs took 4826 ms


Which still shows that the C++ version is nearly 10x slower. Some of the difference I've experienced between platforms may be to Microsoft optimisations as well as stdlib being (in my experience) much slower on Windows than Linux (not counting boost, which I haven't used, but which benchmarks well). The C++ version may optimise for frequent use better than the quoted C version -- but the C programmer is free to update her code accordingly, as required. Again, remember, we're talking about proficient code solutions, so when you change the parameters of the argument, the code is free to change too.

This shouldn't be surprising. The C++ code has to deal with the generic case (and provides a lot of extra functionality which is probably worth the cost) than the C version. But let me re-iterate:

Any proficient code in a higher-order language can only hope to be (at best) as proficient as proficient code in a language of lower-order for solving the same problem.

Note the use of the word "proficient". If I write shitty C code, I bet you can write good C++ that is faster. Same goes for any other pairing: if I write shitty low-order code, I'm sure you can write good high-order code which out-performs my shitty code.

The request I have to the programming community is this:

Please be honest and stop trying to win a "my language is better than yours" with pure lies and FUD. When speaking of well-written, proficient code, Ruby/Python/.NET IL/PHP/C++/whatever is NOT faster than C or assembly. The lower you go, the more specific your instructions can be and the more efficient the overall run can be.

We all accept the costs of higher-order languages because of what they offer us:
  • Quicker to code solutions to the problems which are interesting and/or lucrative, therefore cheaper (overall) than the iron required to run the output
  • Safe memory handling
  • Rich libraries
  • Abstraction from the iron
  • Easier-to-read (and therefore maintain) code
  • And a host of other benefits


I'm open for challenges on this though. Provide a problem which is relatively small to solve in a lower-order language which you think is faster (not smaller or more elegant) in a higher-order language and I'll see what I can do prove my point. Remember: a small problem, like something mathematical or string manipulation.

What's new in PeanutButter?

Retrieving the post... Please hold. If the post doesn't load properly, you can check it out here: https://github.com/fluffynuts/blog/...