Please join me at my new location bryankyle.com

Friday, December 26, 2008

Keyboards, the Neverending Saga

If you're anything like me, you're very specific about your requirements for a keyboard. I've been searching for a keyboard for about a year and a half, and so far I haven't been able to find anything that fits the requirements. Maybe I'm just sentimental, but I really like the Logitech Elite keyboard that is no longer being made. I bought one years ago and it's perfect for me. One of the things I really like about it, and what I haven't been able to find in any other keyboard is the scroll wheel. A keyboard with a scroll wheel? Yeah, it may seem odd, but considering that I use a trackball that doesn't have one it works really well.

So what am I looking for in a keyboard? Well, I'd like a keyboard, preferably black with a scroll wheel. It has to be really comfortable but it doesn't have to be ergonomic. It absolutely must have good, solid feedback. I find it really awkward to type on something that's too spongey, and it hurts to wrists to use something that too stiff. As much as I love the feel of the Das Keyboard it's too loud, so another requirement is that it has to be pretty quiet. Lastly, the layout of the 6-pack (home, end ...) has to be just that: a 6 pack. I'm really getting sick of seeing all these otherwise decent keyboards having a really screwy layout for the keys that as a programmer I use all the time.

In short:

  • Scroll wheel
  • Comfortable
  • Quiet
  • Good Feedback
  • Non-screwy 6-pack
  • Mac compatible

I almost forgot, as I use a Mac it needs to be Mac compatible.

As I mentioned earlier, I've not been able to find a keyboard that fits these requirements other than the Logitech Elite. So where does that leave me? Well, certainly without a keyboard that meets my requirements without looking on ebay. I guess I'll have to relax my requirements a bit, the only problem is that my search for keyboards hasn't been very fruitful. Maybe that's because I only have 3 objective requirements, and I've only seen an answer to 2. The others, I can only determine by using it.

The only keyboard that comes close is the Logitech Wave keyboard. Granted it only meets one of my objective requirements, but my hope is that its answer to the subjective ones will far make up for the what it's missing. I think I'll pick it up and see what happens.

Sunday, December 14, 2008

Javascript Development Tip #1: no-cache

When doing javascript development that requires files to be loaded from an HTTP server, caching can be a real pain. Turning off browser caching is one solution, but I've always had mixed results. The real solution is to turn off caching on the server side. In order to prevent well behaved browsers from caching your files you simply need to add a header to every response.

The HTTP specification has a list of headers that user-agents and servers should understand, however I've always found the headers around caching to be a bit of a black art. However, for our purposes, there's no magic necessary. To tell the browser not to cache resources, the cache-control header must be set to no-cache. This tells the browser not to cache the resource, not in memory, not in disk, just take the response entity, use it and forget you ever received it.

So, how do you go about adding this header to each response? If you're serving your files from Apache, you can use mod_headers. mod_header allows you to add arbitrary headers to responses. The module has a lot of capabilities, but only the basics are required for our purposes.

The first step is to enable the module by adding a line similar to the following to your httpd.conf. Most installations of Apache have this line conmmented out. If that's the case, just uncomment it.

LoadModule headers_module modules/mod_headers.so

With the module enabled, you can have to modify the headers of outgoing responses. If can be configured server-wide, within a virtual host, a directory using .htaccess. You can also enable it in <Directory>, <Location>, and <Files> sections. Whichever you choose, just add the following line, save your changes and restart the server.

Header set cache-control "no-cache"

This tells mod_headers to set the cache-control header to no-cache for all responses within its configured scope. If the cache-control header has already been set, it will be overriden by the value you've specified.

To verify that the configuration worked, clear your browsers cache and make a request to one of the resources covered by the configuration of mod_headers. If you're using Firefox and have Firebug installed, you can switch to the Net tab and look at the response headers.

So there you have it, an easy way to speed up development and reduce your stress by simply removing caching, the real way.

Monday, August 4, 2008

del.icio.us Passwords

Does anyone else think it's odd that del.icio.us has strict password requirements? Given that it's a social bookmarking site, 99% of the user's data is public. It's not as though anyone is trying to hide what they're bookmarking.

Surely I'm missing something, there must be a sane and logical reason for all this.  Can anyone tell me what it is?

Thursday, July 3, 2008

On Emacs

I've been using Emacs for a few months now and after the initial steep learning curve I'm really enjoying it. It's great for all of my text editing and coding needs, although I don't think it will ever replace Eclipse as my editor of choice for Java. Since I'm so enamored with it, I figured I'd spend some time explaining why I came to Emacs instead of the zillion other editors out there.

I used to be a huge fan of TextPad on Windows, it worked well for every situation that ever came up, I've hammered out a few projects using it and not much else. The main problem with it is that it wasn't very extensible. Sure you could add tools, but what you could do was really quite limited. At the time, I just accepted it for what it was and didn't look much further, but things changed when I bought a Mac.

When I bought a Mac, I had a hard time finding an editor I liked. I tried the reigning king of editors BBedit and its free sibling TextWrangler, but I didn't find them to be terribly usable. At the time I was looking for TextPad for OS X, which neither of these were. Eventually I found TextMate, which was exactly what I was looking for. I liked it so much that I bought a license for it, which says a lot given that in all the years of using TextPad I couldn't be bothered to fork out the cash for it, which at the time was about half the price of TextMate.

TextMate did have one major problem though, it only ran on OS X. I do development on Windows and OS X, so I really needed something that was cross platform. I'd given jEdit a try before, but I wasn't that impressed with it, so that wasn't going to work. On Linux I'd always used vim, which worked in a console environment but for some reason it didn't translate well to a windowed environment, so vim was going to work either. When I started looking around, I had kinda-sorta been interested in Lisp. I'd played briefly with Lisp-in-a-box on Windows (Emacs+SLIME+SBCL), and while my initial experience with Emacs wasn't great, it was better than my experience with vim in a windowed environment.

After a few days of using it for simple text editing, I found it to be really productive. Hidden behind a wall of weirdo key bindings was a fantastic editor. As I used it more and more I found myself reading through the documentation learning that Emacs has an insane number of features that I'd always wanted in other text editors. As I became more comfortable, I started to script it. It's really quite amazing all the things you can do when your editor is designed from the ground up to be extensible. None of the editors I'd tried before even came close to being as extensible, or if they were I never knew about it.

In the end, I think I've found the editor that best fits my needs.

Friday, May 23, 2008

Unit Testing Graphics Code

I was reading reddit today when I came across a post about the popularity of unit tests waning. After reading a few of the comments I came across an interesting one:

How do you assert that this image draws centered in this button? Writing an automated test for that is fiendishly hard. The few automated tests I attempted to write for graphical components were fragile, produced lots of failures-that-weren't, and became a maintenance headache. Meanwhile, testing the button by just-looking-at-the-damn-thing was trivial, and what I should have been doing all along.

I've recently had to write unit tests for graphics code so I thought I'd share my experience testing that code.

One of the benefits of unit testing is that it forces you to think about your structure. Typically if you can't unit test something then it isn't factored properly, and drawing routines are no different. In the cited example, the developer needs to test to ensure that an image is displayed in the center of the components canvas. Let's assume that the code that needs to be tested looks something like the following.

public class Button {

   private Image image = null;

   public Button(Image image) {
      this.image = image;
   }

   ...

   public void paint(Graphics g) {
      super.paint(g);

      int x = (this.getWidth() / 2) - (this.image.getWidth() / 2);
      int y = (this.getHeight() / 2) - (this.image.getHeight() / 2);

      g.drawImage(this.image, x, y);
   }
}

How can we test this? Well, looking at the code I see a few approaches to testing this. One way is to stub out the Image and Graphics classes and test to make sure that methods are called with the arguments we expect. Another is to factor out the logic inside the paint method.

Stubbing out the classes is you're best bet here if you can. Given that you will probably need to test other code that uses these classes I think it'd be a wise investment of your time.But what if you can't stub out the classes? What if the classes don't implement any interfaces, or the classes are declared as final?

But what if you can't stub out the classes? What if the classes don't implement any interfaces, or the classes are declared as final? If you find yourself in this situation, you can break the logic of the paint method out into smaller utility methods. From there you can call those methods directly and assert that the results they give are what you expect.

public class Button {

   private Image image = null;

   public Button(Image image) {
      this.image = image;
   }

   ...

   public void paint(Graphics g) {
      super.paint(g);
      g.drawImage(this.image, calculateImagePositionX(), calculateImagePositionY());
   }

   private Point calculateImagePositionX() {
      return (this.getWidth() / 2) - (this.image.getWidth() / 2);
   }

   private int calculateImagePositionY() {
      return (this.getHeight() / 2) - (this.image.getHeight() / 2);
   }
}

Granted this example is a bit trivial, but I think it goes to show that it is possible to write unit tests for graphics code. That being said, without physically looking at the canvas there's no way of being 100% sure, but at least you have tests that can run as part of any build.

Thursday, April 10, 2008

Two Functions Enter. One Function Leaves.

What happens when two applications declare a function with the same name in the same namespace? A huge headache.

A big problem with Javascript as it is today is that there is no insulation between your application and someone else's. When two functions are declared with the same name in the same scope, the last declaration "wins". Given this sad state of affairs, how can you work around this problem?

Code Defensively.

There's simple pattern for insulating your application. It involves two things I've talked about before: closures and anonymous functions. Consider the following code:

(function(scope) {

   function doStuff() {
      ...
      doSomethingElse();
      ...
   }

   function doSomethingElse() {
      ...
   }

   scope.doStuff = doStuff;

})(this);

When run, the above code will expose doStuff by adding it to the passed object. If that code is run in the global scope then this refers to the global object. Everything that doesn't need to be exposed stays neatly hidden inside the closure. Congratulations, you've just reduced the surface area of your application to the bare minimum you'll be less susceptible to someone else's application trampling all over yours.

Combining this pattern with the unobtrusive Javascript methodology will effectively reduce your application's surface area to 0. Short of another application overwriting event handlers and data on shared DOM elements you've insulated yourself. What's even better is that if you don't need to expose anything a build script can bundle your sources files into one file wrapped it in an anonymous function and obfuscate it without you having to think.

Sunday, February 17, 2008

Curried Functions

So, currying, what's that all about?

Currying is a technique of transforming a function that takes multiple arguments into a function that takes one argument. In short, it's a way of defaulting parameters of a function call.

In a language like Java, you could accomplish the same thing by delegating method calls. For example:

int add(int a, int b) {
   return a + b;
}
int add_one(int b) { return add(1, b) }

However, since functions aren't first class citizens in Java you're limited in what you can do. In a functional language, the possibilities are a more open. You can make use of currying to reduce the size of your code base and reduce the amount of boilerplate code you'd otherwise have to write.

An example of this is a set of accessor methods where the code is boilerplate. Modern IDEs will generate these for you, but wouldn't it be nice if you didn't have to see the code for them all the time? What happens if some of your setters need to manipulate the value being set? I suppose you could find all of the setters and update them manually...or if you're working in a functional language, you could just leverage the features of the language to make your job easier.

Take a look at the following code:

function set(attribute_name, value) {
   this[attribute_name] = value;
}
function get(attribute_name) { return this[attribute_name]; }
function attr_reader(attribute_name) { return function() { return get.call(this, attribute_name); } }
function attr_writer(attribute_name) { return function(value) { set.call(this, attribute_name, value) }; }
function MyClass() {} MyClass.prototype.setName = attr_writer('name'); MyClass.prototype.getName = attr_reader('name');
var o = new MyClass() o.setName('Bryan'); o.getName(); // Bryan

In this example, we have two methods: set and get which are the most simplistic and generic setter and getter functions one could write. We've also added a currying function for each of them. We then call through the currying functions to create a curried call to getter and setters on the prototype of the constructor for MyClass.

While this example is not the best possible code for currying getters and setters I believe it illustrates the concept of currying.

If you can tell me why attr_reader and atter_writer return the functions curried using their call method you get bonus points. If you can't, I'll explain later.

Tuesday, February 12, 2008

Closures and Javascript

Ah Closures, one of the must misunderstood and accidentally used features of javascript. But why is this the case? Well, because it's so easy to accidentally use them few understand the mechanics behind them. In this post I hope I can clear up the confusion and explain how they work.

In computer science, a closure is a function that is evaluated in an environment containing one or more bound variables.

Or, in normal people terms, a closure is a function that can access variables from the same scope that it was declared in. You can think of it as a natural extension of the standard scoping rules where functions declared in the global scope can access global variables.

var my_global = "hello, world";

function printGlobal() {
   print(my_global);
}

In the above code the function printGlobal can access a global variable. As an extension of the same principle, in the following code the function printLocal can access a local variable in its declaring scope.

function main() {
   var my_local = "hello, world";

   function printLocal() {
      print(my_local); 
   }
}

So that's all well and good, but why on earth would you ever want to use it? All your life you've been told that global variables are evil (which they are), so surely closures must also be evil. Well, if used incorrectly of course they're evil, but with great power comes great responsibility.

Here's quick example of a function that returns a function to increment a value by another fixed value.

function incr(start, delta) {
   return function() {
      start = start + delta;
      return  start;
   }
}

var i = incr(10, 1);
i(); // 11
i(); // 12
i(); // 13

Pretty freakin' wild isn't it? But how does that work? When a call is made to the incr function start and delta are bound to its scope. The function it returns simply holds onto these variables. Since it has a reference to the variables (not just their values, but a place to store them) they can be freely modified.

The next question you might be asking is, "So that's all well and good, but what if I call incr twice and hold on to both of the returned functions? Won't the second call clobber the first?". The answer is: NO! Each call to the method creates a new local scope just for that invocation. Exactly the same as how two calls to the same function at the same time won't interfere with each other.

But by far, the most classic use of closures is to enable Currying, and I'm not talking about the delicious spice blend. No no, I'm talking about higher-order functions. Functions that work with functions. Functions that return functions that call other functions. Functions that I'll explain in another post.