Mechanical keyboard

A very brief guide to mechanical keyboards

With the advent of less expensive alternatives in the late ’80s and early ’90s, the once ubiquitous mechanical keyboard for a long time disappeared from the shelves. Since mid 2010 however,  interest for them has increased steadily:

mechanical-keyboard-search-trends

But why would an otherwise sane person purchase a mechanical keyboard when they can get a membrane one for $100 cheaper?

Some will say it’s a trend, that it’s just a niche market made up mostly by computer geeks and gamers. That’s probably not far from the truth, but mechanical keyboards have a better build quality overall and most importantly: they are a joy to type on!

You see, in contrast with other keyboard technologies (rubber dome, membrane, chiclet) mechanical keyboards have real mechanical switches under each key. Cherry MX switches, by far the most popular brand,  come in a variety of colours, mainly differing in the following properties:

  • tactile feedback — whether you can feel when a key is activated.
  • audio feedback — whether you hear a “click” when a key is activated.
  • actuation force — how hard the key needs to be pressed before it is activated.
Animation depicting a Cherry MX blue switch being activated

A Cherry MX blue switch being activated

And here are the switch varieties:

Colour Tactile feedback? Clicky? Actuation force
Blue Yes Yes Medium (50g)
Brown Yes No Low (45g)
Red No No Low (45g)
Black No No High (60g)
Green Yes Yes Very high (80g)

If you can’t decide which switch colour to pick, here’s the usual recommendation: if you are a typist, get blues or greens; if you are a gamer, reds or blacks; if you are both, browns.

Cherry MX Blue switch

Cherry MX Blue switch

As for the keyboard itself, if you are a newbie or on a tight budget (or both), I’d suggest anything from the Cooler Master Quickfire line, with prices ranging from $80 to $100. On the other hand, if you’re ready to become an enthusiast, get a board from the Filco Majestouch line, starting at $140. They are made in Japan and are considered one of the best.

Other known brands that are easy to find in North America:

  • Ducky
  • Steelseries
  • Das Keyboard
  • Razer BlackWidow

Why I enjoy working in a UNIX-like environment

Even after all these years, I am still amazed by how complete of a toolbox I have at my disposal when I’m working in UNIX-like (more specifically GNU/Linux) operating systems. This goes from powerful tools like grep and sed to simpler ones like the command I discovered yesterday.

I wanted to run a command infinitely at regular intervals (say 10 seconds) and watch its output.

I could have written a quick script in Bash, using a while loop and sleep but what if there was a even simpler solution? Yes, in fact there is!

$ watch -d -n 10 'find /tmp/inc -type f | wc -l'

With the -d option it even highlights output differences!

Here’s the man page for watch.

How to disable & enable a network adapter on Windows with PowerShell

Sometimes my USB wireless network adapter doesn’t work at all after Windows 7 recovers from sleep mode. I haven’t found the root cause of this problem but disabling & enabling the adapter works well as a workaround. Here is a PowerShell script to do so:

# Get the network adapter object
$adapter = Get-WmiObject -Class Win32_NetworkAdapter |
    Where-Object {$_.Name -eq "TP-LINK Wireless USB Adapter"}

# Disable it
Write-Host -nonew "Disabling $($adapter.Name)... ";
$result = $adapter.Disable()
if ($result.ReturnValue -eq -0) {
    Write-Host "Success.";
} else {
    Write-Host "Failed.";
}

# Wait 2 seconds
Start-Sleep -s 2

# Enable it
Write-Host -nonew "Enabling $($adapter.Name)... ";
$result = $adapter.Enable()
if ($result.ReturnValue -eq -0) {
    Write-Host "Success.";
} else {
    Write-Host "Failed.";
}

Make sure the adapter name on line 3 matches what you have in Control Panel > Network and Internet > Network Connections. Mine is called “TP-LINK Wireless USB Adapter”.

Since you will need to run that as an Administrator, create a shortcut to the PowerShell executable and pass the full path of the script above as an argument. Then, open the shortcut properties, click on “Advanced…” and check “Run as an administrator”.

Update: This method only works on Windows Vista and above.

Update 2: I have not encountered this issue since I’ve updated to Windows 8.

Object-oriented programming with JavaScript

A short introduction on how to achieve OOP concepts such as classes and inheritance in JavaScript

Classes in my JavaScript?

JavaScript does not have a built-in language construct for the definition of a class; however, we can achieve the same concept of an “object blueprint” via a function, to which attributes and methods can be attached dynamically. Let’s look at a practical example—let’s implement a simple Animal class:

function Animal(name) {
	// Attributes
	this.name = name;

	// Methods
	this.getName = function() {
		return this.name;
	}

	this.setName = function(name) {
		this.name = name;
		return this;
	}

	this.speak = function() {};
	this.toString = function() {};
}

So this class has a name which is encapsulated by a getter and a setter. It also has two undefined methods. Nothing extraordinary here.

Inheritance

Let’s implement a class Cat that extends Animal. This can be done by assigning an instance of Animal to  Cat.prototype:

Cat.prototype = new Animal(); // A Cat is an Animal
function Cat(name, favouriteFood) {
	// This is how we invoke the constructor of the parent class.
	// Not very nice; we will see a way around this.
	Animal.prototype.constructor.call(this, name);

	// Attributes
	this.favouriteFood = favouriteFood;

	// Methods
	this.speak = function() {
		return 'Meow';
	}

	this.toString = function() {
		return this.getName() + ' is a cat';
	}

	this.getFavouriteFood = function() {
		return this.favouriteFood;
	}
}

Instantiating objects and passing messages is straight forward to those who are familiar with C++/Java:

loup = new Cat("Loup", "tuna");

document.write(
	loup + ' who loves ' + loup.getFavouriteFood() + '.' +
	loup.getName() + ' says "' + loup.speak()+ '".'
);

And the output is:

Loup is a cat who loves tuna. Loup says “Meow”.

Notice the overriding of the methods speak() and toString() in the Cat class.

But wait! There’s more!

We can make the invocation of parent constructors a bit more elegant like this:

Cat.prototype = new Animal(); // A Cat is an Animal
Cat.prototype.parent = Animal.prototype;
function Cat(name, favouriteFood) {
	// This is how we invoke the constructor of the parent class.
	// See how this is much better?
	this.parent.constructor.call(this, name);
	…

But now for every inheritance we would need to copy and paste lines 2 and 3. We can reduce code repetition by creating a method as follows:

Function.prototype.extends = function(parentClass) {
	this.prototype = new parentClass();
	this.prototype.parent = parentClass.prototype;
}

Since our classes are actually JavaScript functions, we can add any method or attribute to Function and it will be available to any of our classes. Lines 2 and 3 above are almost exactly as we had before: “Cat” was replaced by “this” and “Animal” was replaced by the reference “parentClass”.

Here is how we would use it:

Cat.extends(Animal); // A Cat is an Animal
function Cat(name, favouriteFood) {
…

That’s it!

The final version of the code can be tested here.

If you don’t want to reinvent the wheel, there are a couple of powerful and robust frameworks out there that will achieve the same functionality and much more. Prototype JS is one of them.

So there you go, this should get you started with OOP in JavaScript!

References: Classical Inheritance in JavaScript by Douglas Crockford and OOP in JS, Part 2 : Inheritance by Gavin Kistner.

Aspect-oriented programming with AspectJ

In one of the courses I took this session I was introduced to aspect-oriented programming. For those who are not familiar with it, an aspect can be used to implement a concern that is crosscutting among different components.

There are a few such concerns that are commonly affected by crosscutting, namely: authentication, persistence, logging and contract checking.

It is argued that with object-oriented programming, even after proper refactoring, it is not always possible to map a requirement to a single component. When a requirement is implemented by more than one component, scattering occurs. AOP allows you to localize the scattered requirement into an aspect.

AspectJ is an extension to the Java language that adds support to AOP. An aspect in AspectJ is composed of pointcuts and advices. A pointcut defines the condition that needs to be met in order for the logic in an advice to be executed. A pointcut could be, for instance, the execution of a method in a particular class.

How AspectJ can be useful

Let’s look at an example. Say we want to log when horses drink water and when cows eat grass. Assume we have a class Logger with a static method log(). Here’s what the implementation could look like:

public class Horse {
	private int consumedWaterInLitres;

	public void drink() {
		consumedWaterInLitres++;
		Logger.log("A horse is drinking water.");
	}
}

public class Cow {
	private int consumedGrassInGrams;

	public void eat() {
		consumedGrassInGrams++;
		Logger.log("A cow is eating grass.");
	}
}

The argument is that the concern of logging is now crosscut among the Horse and Cow components. In addition, it can be said that Horse.drink() and Cow.eat() are responsible for more core logic (eating and drinking) than they should have been. Let’s try to fix this problem with an aspect:

public aspect Logging {
	pointcut logHorseDrinking() : call(public void Horse.drink());
	pointcut logCowEating() : call(public void Cow.eat());

	void after() : logHorseDrinking() {
		Logger.log("A horse is drinking water.");
	}

	void after() : logCowEating() {
		Logger.log("A cow is eating grass.");
	}
}

Here we defined two pointcuts that capture calls to Horse.drink() and to Cow.eat(). We’ve attached these pointcuts to two advices that will run after these methods are executed. With the Logging aspect in place, we can now remove all calls to Logger.log() from Horse and Cow. Isn’t that great?

How AspectJ can be dangerous

Dog before DogAspect

Aspects can also add state, behaviour and inheritance to a component. Privileged aspects have access to all features in a system, including private ones. Does that raise a red flag? Let’s look at the class Dog below.

public class Dog {
}

It has no features—no attributes nor methods—and doesn’t extend from any class, right? Wrong:

public aspect DogAspect {
	declare parents: Dog extends Animal;
	private String Dog.ownersName = "Bobert";

	public String Dog.getOwnwersName() {
		return ownersName;
	}
}

Dog after DogAspect

The aspect above has completely changed the class Dog. It has made it an Animal, it has added an attribute ownersName and a getter for it. The worst part is that Dog is completely oblivious to the aspect. In fact, unless you as a developer look at all aspects on the system, you will never know about it either.

That is not completely true because some IDEs will provide a visual clue whenever a class is affected by an aspect. The AspectJ Developement Tools add-on for Eclipse (a great IDE by the way) is supposed to show a marker on the editor margin whenever a component is being advised by an aspect. I have the latest version installed (ADJT 1.6.4) but for some reason the marker is not showing up, unfortunately.

There are also other issues one might encounter when using AspectJ. It is not an easy task to document the impact aspects have on a system—UML has no support for aspects at this moment—how are you going to show that on a sequence diagram? Also, the debugging and tracing of execution of a class that is being advised by an aspect can get pretty tricky.

In conclusion

I believe that the application of AOP could indeed improve the quality of a system through the localization of crosscutting concerns. However, its Java implementation—AspectJ—provides a level of control that is too risky to be used in industrial medium- to large-scale projects. Its supporting technologies and documenting tools have not yet reached the desired maturity level.

Should we use foreign-key constraints when persisting Domain Models?

Mediawiki Database Schema

Since last summer I’ve been working with three other Software Engineering undergraduates on a web enterprise application that will eventually replace a legacy ERP system. We used patterns from Martin Fowler’s Patterns of Enterprise Application Architecture (a great book, by the way), and the well-known three-layered architecture.

One day we had a discussion related to the persistence of Domain Models and whether we should enforce foreign-key constraints at the database level. My first reaction was that the very use of a relational database implied the enforcement of such constraints, but some of my colleagues argued that the database should be seen as nothing but a persistence mechanism and therefore we should avoid placing any business logic in it. We ended up by not using foreign-key constraints.

Would you have done otherwise? I would like to hear what other software engineers/developers have to say about this.