Categories
programming

(Again) Why Test?

When whipping out the Josephus game, I used Jasmine to write the tests… er.. spec for anticipating the behaviour of the code. Among the many reasons I use a “test-driven methodology” (even in the smallest of projects) is that I like to (nay, NEED to) keep a close eye on the strategic direction of the code while I’m minutely engaged in the technical direction. And a picture like this is so easy to read:

Strategy

Categories
programming

Jospehus Interactive

If you’re into math puzzles, you have probably come across the Josephus Problem at some point or another. If you enjoyed testing your ability at finding the right spot, there’s an interactive version (the theme slightly mangled with creative licence). Enjoy!

Categories
programming Technology

Javascript Jasmine

If you know me (or have worked with me) then there’s one thing you’ll be quickly become aware of with regards my coding behaviour: tests. I love tests. More importantly, I love meaningful, passing tests that validate my sanity and check my logic in critical areas.

And Javascript is no exception. I’ve run with jsUnit for quite some time now (because it just worked). Subsequently though, I got my hands dirty with it’s upgraded re-written cousin: Jasmine. There’s not much I can say about getting going with Jasmine since, to be fair, it really is so simple and well documented on the site already, needless to say:

1. Don’t Panic
This useful bit of instruction should be mandatory on every new piece of technology and before you take on any new learning. Don’t you feel better already?

2. Download the archive for standalone javascript projects
The primary folder of interest is the aptly-named lib folder which is, well, the core library.

3. Prepare a test runner
You need a test runner (test harness, if you like) for actually running the tests and a demo has been provided for you in the form of the included SpecRunner.html

4. Write tests
The included ‘src’ folder is the sample functionality under test. This is usually your own code. The ‘spec’ folder contains sample test code. I say -test- but when you start moving into proving behaviours, -test- seems such a dry word, and so the word -specification- is born, but that may sound too technical and daunting (until you become used to it). The two are, for all intensive purposes the same to the newly initiated, but quite different once you start grokking the subtle differences.

5. Have fun
Now go get on with doing something awesome.

Categories
Business Technology

iTrainedToday Tech

The technology behind iTrainedToday is a nice mix. In fact, the chosen technology has enabled it to finally come to life.

For a web application with persistence, you need basic moving parts: UI, backend persistence (ie. database), server-side middleware to translate the communication between the UI and the persistence. Straightforward for the most part except that things are really straightforward once you dive into the belly- except of course if you live in belly in which case everything’s straightforward but just takes time.

UI: html standards, css standards, javascript and all the various frameworks available and then there’s browser issues. iTrainedToday chose jQuery with jQueryUI as much as possible to lift all the UI interaction. Simile is the only other major JavaScript component but a crucial one. It’s what displays your recent data in one consolidated view.

Server: this is where things can get expensive. ASP.NET, Rails, Django, PHP and more all need to be hosted *somewhere*. And hosting costs money. In addition to the hosting costs there are bandwidth limitations/costs involved. A minefield (unless of course, you play in minefields all day long in which case it’s just a field). Hello, Google AppEngine. Love it or hate it; it’s still pretty sweet to get going with. And whenever someone says “it’s pretty sweet to get going with” they mean “it’s great for prototyping”. I don’t mean that. It’s serving athletes nicely (and simply) and ticking along… prime-time? I’ll let you know when it starts paying for itself in a big way.

Persistence: Google AppEngine handles that for me too. I don’t really need to grok the ins and outs of what that tech is in the tiniest detail. It’s interesting to know, but it’s more important for me to know that: a) it works and b) how to work with it. Storage techies get their hands dirty in the detail ‘cos well, that’s what they do. It’s not really what I do (most of the time).

And then beyond all the moving parts is the brain behind it. Can the brain handle mixing strongly typed dynamic scripting languages with the weakly typed variety and hurdle UI intricacies with usability issues while keeping an eye on security, optimizing the bottleneck (database calls) all the while focusing on the problem domain at hand? Mostly 🙂

Categories
perspective

Relaxing on The Couch

the last few days i’ve been looking at couchdb and started building my first app on it.
Coming from a primarily “backend coder” perspective (complete with domain modeling, object-mapping, type-safety and so on…), it’s been challenging getting to grips with JavaScript on steroids, plain HTML and jQuery along with couchapp all at the same time.
Sometimes my brain’s wires short-circuited but i’ve loved the journey so far. Very reminiscent of my experiences when i made the switch to doing cool stuff from “just doing stuff” for other people.
Lovin’ it.

Categories
Technology

Invalid State Crashes Client?

It’s the infamous view state again. My my my. I knew there were reasons I really didn’t dig the complexity ASP.NET were trying to cover up. This time though, my sense of amazement reached new heights when the client browser crashed (yip-crashed) because the server picked up some dodgy view state. Read that again. Carefully.
Oh. And you probably might have already guessed which browser does the crashing. No prizes for getting it right, sorry. The correct and predictable, even appropriate response is: “The view state is invalid for this page and might be corrupted” which is what all the other browsers I’ve tested on so far show. On with the experiment…

We’ll start off with a simple ASPX page. Nothing complicated.

<html>
	<script language="C#" runat="server">
  public void Page_Load(Object sender, EventArgs E)
  {
  }

  public void Submit_Click(Object sender, EventArgs E)
  {
  }
	</script>
	<body>
		<form id="Form1" runat="server">
			<asp:Button ID="Submit" OnClick="Submit_Click" Text="Submit" Runat="server"></asp:Button>
		</form>
	</body>
</html>

Click on the button and woohoo- no surprises. But now we add a little extra something. We modify the contents of the page after it’s loaded. Nothing special here either really. Standard AJAX behaviour.

<asp:Button ID="Submit" OnClick="Submit_Click" Text="Submit" Runat="server"></asp:Button>
<div id="dynamic_content"></div>
<script type="text/javascript">
//<![CDATA[
  window.onload = get_dynamic_content;
  function get_dynamic_content() {
    //....
  }
//]]>
</script>

The JavaScript function get_dynamic_content() will make a request and then proceed to populate the div dynamic_content with some more HTML. The obvious solution is to do something along the lines of:

function get_dynamic_content() {
  document.getElementById('dynamic_content').innerHTML = '...some html...';
}

Incidentally, therein lies another rub in that div.innerHTML behaves differently for IE. Take a peek for yourself. And within all those comments, of this article, there lies a hack solution. You can read more about that debate there. Moving along.

So having hacked the little piece of innerHTML magic, you start populating your element with all sorts of dynamic content. Wonderful. Then during a series of development efforts, you get a buggy piece of HTML tagging along for the ride. A second form element- don’t worry, not a server-side form. More about why and why not here if you not too sure about how that fits into the scheme of things. Anyway, so you get an erroneous piece of HTML coming through- a valid bug in the development effort- and your second form contains an extra view state element. By now, you’ve also probably deciphered the design and architecture of this piece of handy work.

And i’ll recount here- this may be a valid bug, but it’s not about the bug. It’s the way the client browser handles a server-side bug.

So let’s assume that part of the payload (simplified) includes the following:

<form>
...
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEWAgL9hvuOBAK8w4S2BGRm0HOf1YSq2O4B5nwrlp8eUNwR" />
...
</form>

You click on Submit. Is this what you would be expecting?

Familiar Browser Crash
Familiar Browser Crash

It’s not even bad HTML. In fact, if the dynamic payload didn’t include the extra form element, just the viewstate ala

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEWAgL9hvuOBAK8w4S2BGRm0HOf1YSq2O4B5nwrlp8eUNwR" />

You get the reasonable and correct behaviour. ASP.NET complains about the view state being fudged. Good. But wrap that extra view state input element in a form tag and IE client blows up. WTF? Incidentally, the form wrapper is arguably more correct.

Here’s the full code for your enjoyment. Modify the content variable and element type of dynamic_content and test across all your browsers.

<html>
	<script language="C#" runat="server">
  public void Page_Load(Object sender, EventArgs E)
  {
  }

  public void Submit_Click(Object sender, EventArgs E)
  {
  }
	</script>
	<body>
		<form id="Form1" runat="server">
			<asp:Button ID="Submit" OnClick="Submit_Click" Text="Submit" Runat="server"></asp:Button>
			<div id="dynamic_content"></div>
      <script type="text/javascript">
      //<![CDATA[
        window.onload = get_dynamic_content;
        function get_dynamic_content() {
          var content = '<form><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEWAgL9hvuOBAK8w4S2BGRm0HOf1YSq2O4B5nwrlp8eUNwR" /></form>';
          //document.getElementById('dynamic_content').innerHTML = content;
          swap_content_div(document.getElementById('dynamic_content'), content);
        } 
        function swap_content_div(old_div, content) {
          someHtml = content;
          var newDiv = document.createElement(old_div.tagName);
          newDiv.id = old_div.id;
          newDiv.className = old_div.className;
          newDiv.innerHTML = someHtml;
          old_div.parentNode.replaceChild(newDiv, old_div);
        }
      //]]>
      </script>
		</form>
	</body>
</html>
Categories
Technology

Classical, Functional or Prototypal?

I have updated the maths playground on this site as part of an ongoing adoption and learning of new languages and in particular, programming approaches. The language itself is not really the issue when you’re tackling a task. In fact, learning a ‘programming language’ itself (the syntax that is) is a non-issue. What you do come up against is, is a mindset.

Taking the “classical” languages like C, C++, C# and Java as examples, the way you code in each is roughly the same. Different semantics, but a lot of variable commonality. (Of course, you can get frameworks, like the Symbian SDK, which obsfucate things enough for you to appear as another language). Then you take something like Ruby, and the way you think _has_ to change, or you’re just going to hit your head against the proverbial. And then still, something quite different like Javascript (in it’s more modern form).

Having been schooled in more classical approaches (C, C++), the jump to functional programming was an interesting curve. And now, another shift to prototypal programming has been as interesting. Still some concepts make me ponder though. Nonetheless, i’ve documented the differences, in the form of code, between the pseudo-classical and prototypal approaches in using Javascript.

Any pointers welcome, thanks 🙂

Fractions and Foating-Points

Floating-point arithmetic on a computer is hazardous, at best. This post is not a detail description of the problem. Varied descriptions of the problem already abound, like this one, for example. There’s also documented pain out there to understand that it’s not just your computer 🙂 No, this post is just one way of getting around the problem in a particular context.

The environment: JavaScript. The problem: convert decimals to fractions and fractions to decimals. Getting a decimal is straightforward:

function fractiontodecimal( wholenumber, numerator, denominator ) {
wholenumber = parseFloat(wholenumber);
numerator = parseFloat(numerator);
denominator = parseFloat(denominator);
return ( ( ( wholenumber * denominator ) + numerator) / denominator );
}

Obtaining a fraction was slightly more insane since in JavaScript
23.8 * 10 = 238
but
23.88 * 10 = 238.79999999999998

Not exactly what you need to work with. As you can imagine, inside a loop of sorts, and if the number becomes very small and you divide by it, you start getting bigger errors. Anyways, that’s a digression in itself. What i needed was a reliable way to multiple by a float by an integer, 10, and get a predictable response. In other words, i just needed to keep shifting the decimal point. Most immediate response might be: string manipulation. Isn’t that what JavaScript is for? :p

Another way was using e-notation. 23.88 being represented as 23.88e0. Multiply by 10: 23.88e1, and so on. The good news is you still get to do a little string manipulation, but not nearly as hectic as finding and moving a “.”

The particularly heavy looking string manipulation looking like:

newDecimal = mantissa + “e” + exponent;
That wasn’t so hard, now was it? 😀

Browse through the code for decimal.htm (HTLM page with JavaScript)

Timeline + Blog = Blogline

:all that playing around has paid off nicely for some useful code of high geek value 😀

welcome, Blogline

u can plug just about any rss feed into it.. at least, that is, i have been playing with implementations for Rss2 and Atom.