A TimePiece of C# and JavaScript

I put together a little project on Github, partially because I’ve been making headway learning the intricacies of JavaScript, and partly because I wanted something that would parse a string that represents a time value. So here’s the TDD I went through. In the process I pulled in QUnit and used that as my testing framework for the JavaScript example. I’d love input on either of these, so feel free to gimme some heat, tell me what I’ve done wrong, and especially how I ought to be doing this.  :)

The first thing I did was put together the C# Library. I started two projects, one for the tests and one for the actual library.  In the tests project I added a class file and removed the default using statements and replaced them with the following by way of Nuget:

using NUnit.Framework;
using Shouldly;

After adding these references I jumped right into setting up the test fixture. Since I know I want to have something to parse the hour for military time also I’ve setup two test variables.

[TestFixture]
public class with_static_parsing_of_time
{
    protected string sampleTimeOne = "10:12am";
    protected string sampleTimeTwo = "2:30pm";

The first test I then dived into was to test the hour.

[Test]
public void should_return_a_time_piece_with_correct_hour()
{
    var timePiece = TimePiece.Parse(sampleTimeOne);
    timePiece.Hour.ShouldBe(10);
}

I then fleshed out the object and implemented enough to get this test to pass.

namespace TimeSlicer
{
    public class TimePiece
    {
        public TimePiece(string time)
        {
            ParseTime(time);
        }

        private void ParseTime(string time)
        {
            SetHour(time);
        }

        private void SetHour(string time)
        {
            Hour = Convert.ToInt32(time.Split(Convert.ToChar(":"))[0]);
        }

        public int Hour { get; set; }

I then continued back and forth writing tests and implemented each. For the complete code check out the Github Repository. This example is really simple. I’d love any thoughts on adding to it or what you might think is a better way to test the object.

For the JavaScript I downloaded QUnit. Again I stepped into the testing, which is a whole different ballgame than in C#.

<link rel="stylesheet" href="qunit/qunit.css" type="text/css" media="screen"/>
<script type="text/javascript" src="jquery-1.6.2.js"></script>
<script type="text/javascript" src="qunit/qunit.js"></script>
<script type="text/javascript" src="TimeSlicer/TimePiece.js"></script>
<script type="text/javascript">

var timeValueOne = "1:30am";
var timeValueTwo = "8:15pm";

$(document).ready(function() {

module("Parse hour from value.");

test("Should parse hour from value.", function() {
    TimePiece(timeValueOne);
    equal(TimePiece.Hour(), 1, "The appropriate hour value is returned for AM meridian value.");
});

For the full test file with other JavaScript libraries and CSS check out the code file on github.

…and directly into implementation. With the caveat that I’m extremely unfamiliar with actual psuedo/pretend/faux object creation in JavaScript. In this realm I’m still reading up on best ways to do this.

TimePiece = function(time) {
    TimePiece.Hour = function () {
        return time.toString().split(":")[0];
    }
    return time;
};

I went on from here writing tests and implementing as I did with the C#. The JavaScript was interesting. I’ve also noticed that I get a lot of strings back versus the number values that I’d actually want, thus the addition of the “parseInt” in the final version.

Check out the overall project on Github at: https://github.com/Adron/Time-Slice

11 thoughts on “A TimePiece of C# and JavaScript

  1. DotNetShoutout

  2. A TimePiece of C# and JavaScript « Composite Code | .NET, C# and Javascript | Syngu

    • Good point Taswar. However I was trying to keep it focused on a TDD flow, so just core functionality and design first. I’ll make a second pass and put in some outliers to break up the flow a bit.

      Matter of fact I’ve actually gone back over the last few days and broken up the military time testing and implementation to actually be accurate. My implementation was a bit too simple. It left the 12 am hour and such not quit right. :)

  3. Looks pretty good. I suppose one of the things to look out for are the edge cases, like Taswar referred to.

    One thing I’m curious about is in terms of the requirements. Are the values you are expecting hand-coded or something like UNIX timestamps? Timestamps are uniform and easy to code for.

    • It’s handling input from some user controls that format it in a certain way – at least that’s where I got the idea from. I primarily put together the code just for fun. Kind of an evening exercise. :)

  4. Your javascript implementation is a little wonky in that it’s the equivalent of a static class.

    You’ve got a few options. If you want to create a TimeSlice ‘instance’, then your ‘class’ should look like:

    TimePiece = function(time) {
    this.hour = time.toString().split(“:”)[0];
    //this.minute =
    //etc…
    };

    And you can use it like:

    var timePiece = new TimePiece(timeValueOne);
    var hour = timePiece.hour;

    You might consider leveraging the Javascript Date which might suggest you just need a function, not a ‘class':

    function parseTimePiece(time) {
    var hour = time.toString().split(“:”)[0];
    var minute = …/

    return new Date(0, 0, 0, hour, minute);
    }

    This way, you can leverage all the functionality like adding and subtracting dates, toTimeString(), etc. (see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date).

    This would suggest that this makes a good ‘extension method’ for Date:

    Date.parseTimePiece = function(time) { …

    Beyond the exercise, you might check out http://www.datejs.com/ which has time parsing plus a whole lot more. I also use humane-dates (https://github.com/zachleat/Humane-Dates) which turns a Date into feed like ‘2 Days Ago’ output.

    • Awesome, thanks for the comment Marty. I kind of like the second option, not really feeling it necessary to instantiate an entire object. I was pondering making the C# one static too.

      I’ll definitely check out datejs (I had been looking at it some). However for this example I just wanted to create an exercise of sorts to go through. :)

  5. Good to see your using TDD :D. I’ve been falling in love more and more as I gradually grasps its concept and begin to grow more used to it. Automatically viewing my software from the “tester” perspective and not only from the developer perspective.

    I’m preparing some posts about this journey, specially the difficult parts and problems I’ve been bumping into. Some of them have solutions, some other I’ve implemented solutions and unfortunately some of them i think require some major shift at how programming languages are made (lets face it, they are not well prepared for tests) :D

    • Of course… I’m beyond sold on TDD/BDD styles. Anything else just seems slow, cumbersome, and not so ellegant by comparison. I’m sure there are some situations where it might not work, but I’d say those are rare situations. ;) I’m looking forward to your post – I’ll give it a read when you publish it.

      • Hello Adron. Here is the thing i was talking about. Hope you enjoy reading it and give your opinion. I would like that :D.

        codemadesimple.wordpress.com/2011/10/27/jnarcissus/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s