Friday, December 3, 2010

IE Doesn't Support the trim() Method(!)

Here's yet another shocker from the half-baked world of Internet Explorer. Start up IE 8. Press F12 or start the Developer Tools. Then, click the Script tab and then the Console tab on the right pane. At the command line at the bottom, type
[sourcecode language="javascript"]
" this has padded whitespace ".trim();
[/sourcecode]
press Enter, and behold:



Insane! Thankfully, the folks at jQuery have taken care of this.

Thursday, December 2, 2010

Tuesday, November 30, 2010

Java as DSL

I love it:

http://twitter.com/#!/avalanche123/status/7062890318143488

Monday, November 22, 2010

Generate a Version 4 UUID With Javascript

[sourcecode language="javascript"]
function uuid4() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"
.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == "x" ? r : r & 0x3 | 0x8;
return v.toString(16);
});
}
[/sourcecode]

From Mvc2.TaskUI by Jonathan Oliver.

Thursday, November 18, 2010

Roll Your Own Map/Reduce in Javascript

I’ve been working on a very Javascript-heavy UI that allows the user to manipulate collections of objects. To ease the task of manipulation, I created a few methods on Array.prototype, which I rolled into a file I call iterable.js:

[sourcecode language="javascript"]
var Iterable = {
func: {
predicate: {
TRUE: function (x) { return true; }
}
}
};

Array.prototype.forEach = function (fn) {
for (var i = 0; i < this.length; i++)
fn(this[i]);
};

Array.prototype.filter = function (pred) {
var result = [];
this.forEach(function (x) {
if (pred(x))
result.push(x);
});

return result;
};

Array.prototype.distinct = function () {
var result = [];
this.forEach(function (x) {
if (!result.any(function (y) { return y == x; }))
result.push(x);
});

return result;
};

Array.prototype.any = function (pred) {
pred = pred || Iterable.func.predicate.TRUE;

for (var i = 0; i < this.length; i++)
if (pred(this[i]))
return true;

return false;
};

Array.prototype.indexOf = function (expr) {
if (!(expr instanceof Function))
expr = function (x) { return x == expr; };

for (var i = 0; i < this.length; i++)
if (expr(this[i]))
return i;

return -1;
};

Array.prototype.singleOrNull = function (pred) {
var filtered = this.filter(pred);
if (filtered.length == 0)
return null;
if (filtered.length > 1)
throw "More than one element returned.";

return filtered[0];
};

Array.prototype.map = function (fn) {
var mapped = [];
this.forEach(function (x) { mapped.push(fn(x)); });
return mapped;
};

Array.prototype.groupBy = function (sel) {
var groups = [];

this.forEach(function (x) {
var group = groups.singleOrNull(function (y) { return y.key == sel(x); });
if (!group)
groups.push({ key: sel(x), members: [x] });
else
group.members.push(x);
});

return groups;
};
[/sourcecode]

Note that this not particularly complete; for example, you’ll see that there is no implementation of a reduce function. It’s not here because I have not needed it in my project yet, nor am I likely to. But it would be easy to implement:

[sourcecode language="javascript"]
Array.prototype.reduce = function (fn) {
    if (this.length == 1)
        return this[0];
    return fn(this[0], this.slice(1).reduce(fn));
};
[/sourcecode]

Now, I’m aware of Underscore and others, so why did I do this? For two reasons, mainly: I only needed a subset of the functions that those libraries offer, and besides, it was fun.

Tuesday, June 8, 2010

The .Net HashSet

I’m relatively new to .Net, coming from the world of Java. Now, the documentation of the HashSet class says, “The HashSet(Of T) class provides high performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.” Fair enough, except that the HashSet class preserves insertion order. Furthermore, set1.Equals(set2) will return false even when the two sets contain the same elements but in a different insertion order.

This doesn’t sound like set semantics to me. Fortunately, you can remedy this with a simple extension method and LINQ:

[sourcecode language="csharp"]
public static bool SetEquals<T>(this HashSet<T> me, HashSet<T> other)
{
return me.All(other.Contains) && other.All(me.Contains);
}
[/sourcecode]

As you can see, the LINQ expression on line 3 is equivalent to the definition of set equality. Of course, the parameters to this method could be of type ICollection<T> or something for more genericity.

Monday, March 8, 2010

Endless Code




Bad Code from unclebob on Vimeo:

[vimeo 9981123]



FYI: The piece heard in this video is Atmosphères by György Sándor Ligeti, who intended the listener “to become lost in the depth of the texture and tone and become completely oblivious to the passage of time,” according to Wikipedia.

Friday, March 5, 2010

Feed Reader Problems

Garrett LeSage says that feed readers are not smart enough, and I agree. One of the problems I face is that not all feeds have the same "velocity," which I define as "number of posts per unit time." For example, I have a group of feeds in Google Reader that I read for work and professional development. However, I also read DZone.com and want to add its feeds to the group, but I don't, because its velocity is far greater than the velocities of any of the other feeds in the group. The result, of course, is that DZone dominates the group, and the posts from the other feeds get "crowded out." A feed reader should take into account how often I read the posts of a given feed, determine what those posts I read are about, and then filter accordingly (while offering me the opportunity to see the whole, unfiltered feed if I so choose). It should also offer suggestions of new feeds that I may find interesting.

No feed reader currently meets my needs---and it's not because there is a dearth of feed readers out there. Some come somewhat close, but none have yet done it right.

Tuesday, January 19, 2010

Sapir-Whorf in Software Engineering

What follows is a short essay I wrote for my software engineering class last semester.
I have many interests; one of them is linguistics. I first heard of the Sapir-Whorf hypothesis, also called the linguistic relativity principle, some years ago and it caught my interest. Despite the many objections and resistance brought against it, I have always found it to be rather compelling.

It seems obvious to me that the language we use to describe and interface with the world should shape our cognition about the world. Many studies have been done which show this in natural languages. But it seems that there have been fewer studies about this principle in programming languages, especially in software engineering.

I remember when I took CS 330 about a year ago. CS 330 is a course on programming languages, and the language of the class is Scheme, a cousin of Lisp. Scheme is a functional programming language, which is to say that, in Scheme, functions are first-class objects, just like any other data type. This was the first time I was ever really exposed to the functional paradigm (although I saw a little of it before in Javascript), and it had a rather profound effect on my skills as a software developer. For when we studied Scheme and used it to investigate the principles of programming languages, my thinking about programming changed; it expanded into new realms, and I could see things that I had never really seen before.

One of the things studying Scheme did for me was to get me interested in programming languages and related concepts. But more immediately, it added to my cognitive landscape the idea of functional programming. Not long after I began to learn Scheme did I come to see the benefits of functional programming in other languages, like Python, which I learned has a "lambda" keyword like Scheme. Soon I began to incorporate functional principles in my work outside that class, in  other classes, and so on. I was writing software in a way that I would not have done before without having been exposed to this new paradigm.

And thus it is with software engineering. The long use of the same tools, practices, patterns, languages, etc. often constrain our thinking and deprive us from creating elegant, simple solutions to problems. While I am a firm believer in process---process in the sense that there must be some means by which a software development organization develops its software, and that it should be at least somewhat structured, I also acknowledge the fact that adhering too rigidly to process and procedure can stifle creativity and ossify the mentality of an organization. This is to be avoided, since software development is a creative enterprise; it is by no means formulaic.

We software engineers, programmers, or whatever we like to be called, are, in a sense, linguists. We learn and use languages all the time. As such, we are subject to linguistic principles. Despite the objections of Chomsky and others, I have always found Sapir-Whorf to be true---so true, in fact, that it's a self-evident proposition.