@ayende You ought to try Mercurial. in reply to ayende 1 week ago
07
Aug

PHP gets closures. Rejoice!

I just noticed the other day that PHP 5.3 (now in alpha) has closures and lambdas. This is excellent news — these are language features that can make for much more concise code. The syntax is a little bit more complex than in Ruby, JavaScript or C# thanks to the quirky way that PHP variables work, but it’s nothing drastic, and it’s a one-up on both Python and VB.NET, neither of which have multi-line lambdas.

The stable release of PHP 5.3 is due in September or October.

25
Jun

Less is more

Okay, folks, here’s a little exercise for those of you who think that closures are a pointless, computer-science-y concept of little or no relevance to real-world programming. This is a very practical snippet of code that I had to implement this afternoon, in PHP.

You have to write a function that takes two parameters: a template string containing placeholders such as [[foo]] and [[bar]], and a hashtable containing the values that are to be substituted into the placeholders, and returns a string carrying out the substitution. Your exercise is to write such a function in as few lines as possible.

In JavaScript, you can take advantage of the fact that anonymous functions have access to the arguments passed to the function in which they are declared, to produce a very elegant solution:

function do_template(template, values) {
    return template.replace(/[[(.*?)]]/g, 
        function(key) { return values[key.slice(2, -2)]; }
    );
}

In PHP, unfortunately, it is nowhere near as straightforward — while you can create functions on the fly using the create_function method, they don’t have access to the scope in which they were created, so I couldn’t use that particular trick here. The result? Twice as many lines of code to achieve the same result:

function do_template_substitute($part) {
    global $tmp_values;
    return $tmp_values[$part[1]];
}

function do_template($template, $values) {
    global $tmp_values;
    $tmp_values = $values;
    return preg_replace_callback('/[[(.*?)]]/',
        'do_template_substitute', $template);
}

Oh well, I guess PHP is a better language if you think that productivity can be measured in lines of code per day

12
Nov

Procedural programming != functional programming

One thing that irks me a bit is when developers deride “functional programming” as something for complete n00bs and script kiddies who haven’t a clue about writing software.

The most common offenders seem to be some advanced PHP developers who know something (perhaps quite a lot) about object oriented programming, think it’s the greatest thing since sliced bread, consider themselves smart (with some justification) because a lot of developers simply don’t “get” OO and they do, and look down on what they call “functional” programming.

Now they’re mostly right, but they’ve got their terminology wrong. What they actually mean is procedural programming.

There is a big difference.

Procedural programming is where you view your code linearly, as a set of instructions to be executed one after the other. You write a series of instructions outlining what you want to do, extracting commonly used bits of it into procedures and functions. You think in terms of do this, do that, if-then-else, and so on. It’s useful for small quick-and-dirty scripts, it’s very easy to learn, and it’s the way that most people start off programming. It’s software development at the level that trendy designers in Brighton who do beautiful stuff with Flash and Photoshop can understand.

However, it gets a rough press from OO geeks, since more often than not you end up with things like copy-and-paste code, global variables all over the place colliding with each other, and functions with parameter lists that reach into double figures. And when your app reaches the size and complexity of, say, WordPress, it becomes pretty unpleasant to maintain.

The Space Shuttle Functional programming, on the other hand, is a bit closer to rocket science. Joel Spolsky describes functional paradigms as considerably harder than OO, and considers them a good discriminator between really brilliant developers and the unwashed masses, along with concepts such as pointers and recursion. Most of the trendy designers in Brighton would struggle with many of the concepts, and the real experts in functional programming tend to congregate in places such as NASA, Google and MIT, writing massively scalable search algorithms and the code that keeps the Mars rovers entertaining us with panoramas of the Red Planet.

It’s where functions take on a different nature altogether: they are first class objects, and you can pass them as parameters to other functions, or have them as return values. Differential calculus is one such example: you pass a function, such as y=x3, into the “differentiate” function, and it returns another function, y=3x2.

It gives you useful and powerful features such as closures — where the function runs in the context of its scope as it was when it was created — or iterators (the yield statement) and it allows you to do very fancy things with very little code. Things that would require fancy design patterns such as Abstract Factory, Decorator and so on in classic OO, and even fancier hoops to jump through in merely procedural languages. It is used at a fairly basic but very effective level in jQuery, for example, which allows you to produce jaw-droppingly fancy Ajax-enabled websites with only a few lines of code. However, that is only scratching the surface: once you really get into it, you have to grapple with highfalutinalia such as fixed point computation, monads, and much more.

Perhaps I’m being a bit pedantic here — you tend to get that way a bit when you spend a lot of time coding — but the next time you are tempted to knock “functional programming” just bear in mind that by so doing, you are inadvertently dissing people who are a lot smarter than you.

13
Sep

Beginners’ languages can have advanced features too

C# introduced some very useful concepts in version 2: generics, the yield statement, and anonymous methods (which are similar to closures). However, VB.NET was largely left behind: it has generics, but it still misses out on both the yield statement and anonymous methods, and it had to wait until version 2 to get the simple but convenient and frequently used syntactic sugar of C#’s using statement.

C’mon, Microsoft, these are pretty useful language constructs. Sure, a lot of developers don’t know what they are or how to use them, but once you’ve seen how powerful they can be, you wonder how you managed to get by without them. It seems that in .NET land, VB is definitely a second class citizen, perhaps more comfortable for novices to use, but with some gaps in the feature set that will irritate more advanced developers.

PHP suffers the same dumbing-down problem. It has seen massive improvements in version 5 since version 4, but there are still some fairly major gaps that are not likely to be filled in the foreseeable future. For example, apparently Rasmus Lerdorf is of the opinion that PHP is not likely ever to get closures because most PHP developers would not have a clue what to do with them.

This kind of thinking seems flawed to me. There are some language features such as these, which more advanced developers can use to write code that is much more concise, clearer and easier to understand, while the less experienced can use the language without being aware of them, albeit perhaps not as idiomatically and concisely. JavaScript is a good example of this: despite the insanities of cross-browser quirks, it is easy enough for most novice developers to achieve some results, yet it has some powerful functional features that make it potentially very expressive and idiomatic — just look at what you can achieve with jQuery for instance.

Just because a language’s core constituency is dominated by beginners doesn’t mean you should leave out useful features that advanced developers can use. Don’t forget that experienced coders often have to use VB and PHP too.

22
May

The functional beauty of JavaScript

I’m the kind of developer who tends to sit on the “coding” side rather than the “design” side of the fence. I’m at my happiest when I’m designing web services, database access and application architecture, and although I do enjoy the odd creative spurt with Photoshop and the like, I don’t find it as interesting as the former. Consequently, until a couple of years or so ago, I only gave JavaScript and client-side development the bare minimum of attention that I needed to do my job. What with all the lunatic inconsistencies that you needed to handle in order to cope with Netscape 4 and Internet Explorer 4, I always perceived it as a monstrosity that needed a lot of ugly hacks to get it to do anything more compelling than bring up a dialog box saying “Hello world”, and was content to merely download whatever scripts I could find off the Internet to make it do whatever I needed it to do.

These days, of course, the story is quite different: you have some nifty tools such as Firebug, and despite the myriad rendering bugs in Internet Explorer, standards such as CSS and XHTML make browsers are a lot more compatible with each other than they used to be, plus of course there is all the cool stuff that you can do with Ajax. All this makes learning JavaScript a much more attractive prospect, and not surprisingly I’ve had to do a lot more of it in the past couple of years than ever before.

It’s been a real eye-opener. Far from being the ugly, kludge-ridden monstrosity that I’d always thought of it as being, JavaScript is actually a beautiful, well designed language with some very nice constructs. I always thought of it as one of those linear, procedural languages much like VBScript or Fortran with some vaguely object-oriented bits and pieces thrown in as an afterthought like PHP 4, but in actual fact it has much more in common with functional languages such as Scheme, OCaml or Haskell. It has closures and first-class functions, for example, which means that you can express some things in very clever, succinct and beautiful ways.

One particular JavaScript framework that has gotten my attention in the past few months is jQuery, and it’s become my library of choice for DHTML and Ajax gee-whiz. It’s an increasingly popular and fully featured toolkit that enables you to do some pretty clever stuff with only a handful of lines of code. For a simple example of what you can do with it, here is a code snippet that will highlight rows in a table when you mouse over it:

var highlightColour = "#ffff00";
var normalColour = "#ffffff";

$(document).ready(function() {
  $("#my-table tr").hover(
    function() {
      $(this).css("background-color", highlightColour);
    },
    function() {
      $(this).css("background-color", normalColour);
    }
  );
});

I love the simplicity of this. As the WordPress guys say, code is poetry.

(Update: Jeff Attwood has an interesting take on the subject where he describes JavaScript as “the lingua franca of the web” with the likes of Flash and Silverlight as merely pretenders to the throne.)