Javascript does not have classes in the traditional sense, but we can achieve something similar in a number of ways. C# and Ruby both have standard class syntax.
This post is part of a series comparing the language features of the C#, Javascript and Ruby programming languages.
C#
public class Vehicle
{
protected string Make { get; private set; }
protected string Model { get; private set; }
public Vehicle(string make, string model)
{
Make = make;
Model = model;
}
public virtual void Print()
{
Console.WriteLine(GetDescription());
}
protected string GetDescription()
{
// string formatting syntax
return string.Format("Make: {0} Model: {1}", Make, Model);
}
}
public class Helicopter : Vehicle // inheritance syntax
{
public int NumberOfRotorBlades { get; private set; }
public Helicopter(int numberOfRotorBlades, string make, string model)
: base(make, model)
{
NumberOfRotorBlades = numberOfRotorBlades;
}
public override void Print()
{
// string concatenation syntax
Console.WriteLine(GetDescription() + " Number of Rotor Blades:" + NumberOfRotorBlades);
}
}
Javascript
Class:
// declare vehicle 'class'
var vehicle = function(seed) {
var that = {};
// private method
var getDescription = function() {
return "Make: " + seed.make + " Model: " + seed.model;
};
// public method
that.print = function() {
alert(getDescription());
};
return that;
};
// instantiate a vehicle
var magna = vehicle({
make: 'Mitsubishi',
model: 'Magna'
});
magna.print();
Derived class:
// declare helicopter 'class'
var helicopter = function(seed) {
var that = {};
that.prototype = vehicle(seed);
var getDescription = function() {
return "Make: " + seed.make + " Model: " + seed.model;
};
that.print = function() {
alert(getDescription() + " Number of Rotor Blades:" + seed.numberOfRotorBlades);
};
return that;
};
// instantiate a helicopter
var ah64 = helicopter({
make: 'Hughes Helicopters',
model: 'AH-64',
numberOfRotorBlades: 4
});
ah64.print();
Ruby
class Vehicle
def initialize(make, model)
@make = make;
@model = model;
end
def print
puts get_description
end
private
def get_description
return "Make: #{@make} Model: #{@model}"
end
end
magna = Vehicle.new('Mitsubishi', 'Magna')
magna.print
class Helicopter < Vehicle
def initialize(make, model, number_of_rotors)
super(make, model)
@number_of_rotors = number_of_rotors
end
def print
puts get_description + " Number of Rotors: #{@number_of_rotors}"
end
end
ah64 = Helicopter.new("Hughes Helicopters", "AH-64", 4)
ah64.print
This post is part of a series comparing the language features of the C#, Javascript and Ruby programming languages.
Variables
C# requires that variables be declared with a specific type. Javascript and Ruby determine the type of variables at runtime. Here is the syntax:
C#
public string publicMessage = "Hello World";
private string privateMessage = "Hello World";
static string PRIVATE_MESSAGE = "Hello World";
Javascript
var message = "Hello World";
Javascript does not have a syntax for making variables public or private, instead it is achieved by a clever usage of closure (discussed later). Javascript does not have block scope, which means that variables defined within a block can be accessed from outside the block (a block is anything in {} such as and if statement or a loop). In Javascript variables are scoped to the function in which they are declared and are visible anywhere within that function, including within inner functions.
// this function will alert "Hello World" twice.
function showMessage() {
if (true) {
var message = "Hello World";
}
alert(message);
var innerFunction = function() {
alert(message);
};
innerFunction();
}
Ruby
A ruby variable is declared by assigning to the variable name. Ruby uses prefixes to indicate the variable scope.
# local variable
message = "Hello World"
# instance variable
@message = "Hello World"
# static variable
@@message = "Hello World"
# global variable
$message = "Hello World"
I’m going to be looking at a few different languages and blogging my thoughts. I am not a language dork so it will probably be mostly wrong. The languages I care about are c# (which is what I mostly use), javascript (which I love) and ruby (which everyone else loves).
This post is part of a series comparing the language features of the C#, Javascript and Ruby programming languages.
Installation
C# is installed by installing visual studio, Javascript is included in all the popular browsers and Ruby can be installed (at least on Windows) using the Windows one-click installer.
Scripting-ness
Javascript and ruby are scripting languages, meaning that they are interpreted and dynamically typed. C# is strongly typed and compiled. In practice, this means that C# executes faster and is better at detecting errors at compile time. Javascript and Ruby support a faster development cycle, since there is no compile step, and provide more flexibility.
hello world
Here are the canonical hello world applications in each language.
C#:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World");
}
}
Javascript:
Ruby:
To execute a ruby program open a command prompt and run: ruby [ruby file name]
Note that the scripting languages require less ceremony to get something to run. You can drop commands in a text file, hand it to the interpreter, and it will run. This simple example also demonstrates the differences in line endings – Javascript and C# terminate lines with a semicolon, Ruby uses the new line character.
Most of 2009 I have been working from home. This is a workforce revolution, made possible by technology advances and attitude changes. Here is my list of simple rules for working from home:
- don’t do it all the time. It is important to have some face-to-face interaction with your team.
- even when working from home stay in touch. Call your client or team at least once a day.
- working from home can be isolating. I make sure that I get out of the house every day so that I don’t end up like Edward Scissorhands.
- have quality gear. Working from home means that your home office is now your working environment. You should have a good workspace and sufficient redundancy. My home office has UPS, two internet connections, two printers and at least two computers.
- have a separate workspace so that you are able to clearly differentiate between work, and non-work time.
- Be fastidious with your timesheet. Trust does not come easily, so you need to do everything you can to help your employer understand that you don’t need to be supervised to work well.
Working from home is not for everyone, but there are some great benefits such as reduced travel time and working flexibility (such as the choice to wear pants).
This is my outdoor office:

Sometimes you have a t-shirt idea, but there is no way to try it out – until now. Introducing OnAShirt.net. It is a simple app I coded in a couple of hours today that allows the user to place text over a picture of a t-shirt, or even to conduct t-shirt conversations with themself.
Thanks to jQuery for making this sort of thing so easy.
In a little over 5 weeks Dr Nic and the Fair-brothers will begin their Homeric rickshaw running adventure from the Himalayas to the south of India. Their adventure is raising money for some worthy causes so please give generously.
As you can see, Greg was kind enough to send me a mocra off railers t-shirt. It is very comfortable. Thanks Greg and good luck!
Today I had a twittersation about build servers, and how closely they should match the development and production environments. Damian’s position was that the build server should match the development environment, while I held that the build environment should be as close to production as possible. Martin Fowler’s Continuous Integration article says:
Test in a Clone of the Production Environment
The point of testing is to flush out, under controlled conditions, any problem that the system will have in production. A significant part of this is the environment within which the production system will run. If you test in a different environment, every difference results in a risk that what happens under test won't happen in production.
As a result you want to set up your test environment to be as exact a mimic of your production environment as possible.
I can provide an example of why this is a good idea. I am currently working on a project that is using Asp.Net MVC 2, which is installed on developer’s machines as a standalone MSI. The same article I mentioned before also says, “everything you need to do a build should be in there [repository] including: test scripts, properties files, database schema, install scripts, and third party libraries”. Being fallible, I made a mistake and failed to include one of the required MVC DLLs in the source repository. Because the build environment matched production we quickly detected the error because the build broke. If the build server was similar to the development environments then it would have had the required DLL in the GAC and the bug would have gone undetected.
Here are the things that I consider to be important for a build environment:
- The build server should, as close as possible, match the production environment
- The build server should be fast. Rapid feedback is important
- The same build that runs on the build server should also be runnable on the developer’s machines
- When a build fails, everyone should know
I have written about about WebAii before. It is functional but the API sucks. I have written about NGourd too.
I am currently working on a project that is using the combination of NGourd and WebAiii for automated acceptance testing. We start with a story:
Feature: Search
As a user
I want to search for items
so that I can find data that I am interested in
and then write some scenarios like:
Scenario: Search for a compensation agreement
Given I am at the home page
When I select the Agreements perspective
And I search for 'agreement 1'
Then the search results should be displayed
Within the test project we have the following directory structure:
Search.feature is a text file containing the previously listed feature and scenario definitions. For each scenario step we must have a corresponding step definition. For example the step ‘When I select the Agreements perspective’ matches the following step definition:
[Step(@"select the ([\w\s]+) perspective")]
public void select_perspective(string perspective)
{
CurrentBrowser.Click(CurrentBrowser.Find.PerspectiveButton(perspective));
}
Note the use of regular expressions to parameterise the step. Because this step is an action we put it in the ActionSteps file. Everything that we need to do for our tests falls into one of the three categories: Action, ContentAssertion or Navigation. The goal is to avoid defining the same step twice so that the set of steps form a domain specific language that can be used by business analysts and the like.
NGourd is a Cucumber knockoff, but without many of the features. However, it is surprising how far you can get with just the basics. So far it is working nicely.
Atlassian is the company that I wish was mine. They make cool web products, they have a unique voice and they are successful. But recently they lost their minds, and starting giving their software away (almost).
If you are a small organisation like me you can buy the main atlassian products (jira, confluence, greenhopper, bamboo, fisheye & crowd) for US $10.00 each. User limits apply.
We are using Jira + Greenhopper for agile project management, and confluence for our project wiki. Confluence is VERY nice. It is the best wiki I have worked with. Simple, powerful and it works. It also is very good at converting word documents to wiki pages which is something that our BA has appreciated. JIRA + Greenhopper is a workable solution for agile project management if you don’t want to go with walls and post-it notes. At times it can be a bit confusing because Greenhopper is a JIRA plugin that adds mingle-like functionality to a bug tracking application. Jumping between JIRA and Greenhopper is not entirely smooth, however, it is still one of the better solutions I have tried, and I have tried them all. This is the first project I have been on that has had a burn down chart, and I am finding Green Hopper’s burn down to be an excellent big visible chart / information radiator. JIRA reminds me of Gemini, and Greenhopper reminds me of Mingle. Not sure who copied who. The good news is that unlike Mingle, JIRA does not require a dedicated super computer.
The only disappointed I have is that Atlassian’s code review tool, Crucible, was not included in the deal.
Dictionary<TKey, TValue> is a generic type that stores collections of KeyValuePair<TKey, TValue>. It is used heavily (actually the IDictionary<TKey, TValue> interface) in Asp.Net Mvc as a parameter to view helper methods.
I am writing this post because I have a tendency to forget the collection initializer syntax for this type of collection, so here it is:
IDictionary<string, int> collection = new Dictionary<string, int>()
{
{ "rows", 7 },
{ "columns", 2}
}
The nice part is that it supports specifying the collection members as anonymous types, instead of having to instantiate new instances of KeyValuePair<TKey, TValue>.
Brisbane ALT.NET beers is happening Thursday 5th November from 6pm. The venue will be the riverside pig 'n' whistle, same as last time.
If you have not been before, ALT.NET beers is an informal pub-based meeting of ALT.Neters. Beer and wedges are likely.
Please RSVP at the new EventBrite page: http://altdotnetbrisbane.eventbrite.com
This is part 2 of my series on the jQuery UI Dialog. Part 1 – The Default Dialog covered the most basic usage of the dialog widget. In this second part I will demonstrate a simple modal dialog.
A modal dialog is a dialog that takes focus, and disables the rest of the application until it is closed. They are used to force the user to acknowledge something, or to gather some input. It is worth pointing out that modal dialogs can be annoying for users so you should consider carefully if it is absolutely necessary. User Account Control (UAC) in Windows Vista and Windows 7 is an example of an annoying usage of modal dialogs.
The dialog widget is usually configured by passing the dialog() method an anonymous object containing a set of key value pairs that describe the options required. The anonymous object is created using javascript’s object literal notation. My favourite javascript author, Douglas Crockford, describes the notation:
In the object literal notation, an object description is a set of comma-separated name/value pairs inside curly braces. The names can be identifiers or strings followed by a colon.
A simple code example is:
var myObject = {
firstProperty: 'value 1',
secondProperty: 2
};
The options I will use to create a modal dialog are:
| height |
The height of the dialog |
| modal |
Boolean indicating if the dialog should be modal |
| overlay |
Creates a partially transparent modal overlay layer. Very web 2.0. |
View a Demo
And here is the code:
<!-- See part 1 for html preamble -->
<body>
<p>Some text on the page.</p>
<div class="make_me_a_dialog">Content of div</div>
<script type="text/javascript">
$(document).ready(function() {
$('.make_me_a_dialog').dialog({ bgiframe: true,
height: 200,
modal: true,
overlay: {
backgroundColor: '#000',
opacity: 0.5
}
});
});
</script>
</body>
</html>
This series is going to document increasingly complex usages of the jQuery UI Dialog widget. This first part of the series will demonstrate how to display the default dialog.
Other series members:
jQuery UI Dialog: Part 2 – The Modal Dialog
The jQuery UI Dialog is a powerful client-side dialog control. It is bundled as part of the jQuery UI suite and as such it is available on the Google CDN. Some of its more interesting features are:
- Modal / non-modal dialogs
- Support for resizing and dragging
- Support for buttons
- Support for Theming
- Stacking
- Partially transparent modal overlay layer
The simplest usage of the dialog control is to select a div, and call the dialog() function.
View a Demo
Here is the complete code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Default dialog</title>
<link href="ui-darkness/jquery-ui-1.7.2.custom.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
</head>
<body>
<p>Some text on the page.</p>
<div class="make_me_a_dialog">Content of div</div>
<script type="text/javascript">
$(document).ready(function() {
$('.make_me_a_dialog').dialog();
});
</script>
</body>
</html>
Maybe you are like me and regularly work on multiple projects. If not, please send me a cheque for the $0.00001 worth of bandwidth you have wasted.
Sometimes a week or two can pass between looking at a project and I find when I go back to it I lose a couple of hours just trying to work out where I was up to. To solve this problem I have started a development journal for my more neglected projects. At the end of every coding session I record a few key pieces of information to help orientate me the next time I come back to it. Here is an example entry:
----------
2009-08-19
----------
WORKING ON:
Testing the graph navigator code that produces cycles. Discovered and addressed a few edge cases such as non-cyclic journeys where the shortest spanning tree visits every node.
NEXT THING TO DO:
Complete the scenarios in BuildingCyclesTests using the style of the first two already completed scenarios.
TESTS:
63 passed, 0 failed, 1 skipped, took 13.21 seconds
It is just a plain text file that I have added to my visual studio solution items so that I can edit it in visual studio.
The traditional, Paul Graham style of technology start-up is:
- Someone has an idea
- They try to validate their idea
- The idea is implemented
- The idea is communicated to the market
While the importance of step 2 has always been emphasized the weakness of the above remains that the product may not gain significant visibility to the market. The products never reach critical mass and so they fade gradually into obscurity.
Recently I have noticed a new model emerging that promises far less risk at the tail end of the product cycle:
- Build a personal brand. This is usually done by making open-source contributions.
- Develop a product that is related to your brand.
- Use your brand to reach a market
The advantage here is that the market is ready and waiting and has a degree of trust in the entrepreneur. Here are some examples of development tool isvs that are using this strategy:
I am sure there are others but that is all I can think of right now. Personally, I think it is great that these people are able to leverage their excellent contributions to produce a viable business.