Yes. It’s 1:26 am, and I’m working on stuff. Really, I’d like to be in bed. Asleep. And I’d like to stay there for three days.

But alas, instead, if you are having problems with dropdown JavaScript menus appearing BEHIND a Flash object, try adding this to the parameters you’re passing to the Flash object:

wmode="transparent" 

Or if you’re using SWFObject, you can do something like this instead:

var so = new SWFObject("crappy.swf", "crappy_swf", "100%", "100%", "9", "#ffffff");
so.addParam("wmode", "transparent");
so.write("flash");

Maybe that will save you some headaches. It saved me some.

It’s a typical story. Dan on a rescue mission, fixing a mess that some clown(s) left behind. PHP. No framework to speak of, riddled with SQL injection holes, a TABLE-based layout – and it doesn’t get any better from there.

For the love of all things holy, why do people have to do stuff like this:

$sql = "SELECT user_id,user_status FROM users WHERE user_name='$username' AND user_password='$p'";
$r = mysql_fetch_assoc(mysql_query($sql));

For the record, $username and $p were just grabbed right out of $_POST.

If you spent 30 seconds to write even a crappy inefficient function to actually do something intelligent, not only would you not have code that’s riddled with SQL injection vulnerabilities (did I mention that this snippet of joy came out of a 3112 line file without a SINGLE comment?), but it might actually make your life easier because your code won’t suck so much – and you can stop repeating yourself.

I’m no 1337 PHP h4×0r, but how about – oh, I don’t know – something like this:

function fetch_associative_array_safely( $array ){
$sql = $array[0];
foreach ($array as $index => $value) {
$sql = str_replace( "?".$index, addslashes($value), $sql );
}
return mysql_fetch_assoc( mysql_query( $sql ) );
}

And just execute that bad boy like so:

$r = fetch_associative_array_safely( 
array( "SELECT user_id, user_status FROM users WHERE user_name='?1' AND user_password='?2'",
$username, $p) );

It’s not overly elegant, beautiful or efficient. But I don’t think that really matters. It helps me to not repeat myself, and by golly – at least someone can’t drop tables from my database anymore. It’s a bit Rails-esque, at least as far the the conditions portion of ActiveRecord::Base.find(...).

What do you think? I haven’t done any significant PHP coding in years.

Avdi Grim has begun a thought-provoking series surrounding the idea of sustainable software development – specifically targeting Ruby as an example.

With some of the recent discussion surrounding “monkey patching” in Ruby, I think that the timing seems about right, for some serious thought to be given about the long-term effects of maintaining Ruby-based code-bases, should prolific “monkey patching” continue to be used haphazardly by many of the libraries, plugins, gems and other code that makes (sometimes critical?) modifications to the underlying core language classes.

Nick Sieger has crafted a thoughtful response to Avdi, which includes the quote:

[Monkey patching is] still a basic part of the Ruby programming culture, like it or not.

While Nick is totally correct, and Ruby does give you the power to shoot, maim and otherwise pillage and murder yourself in a bazillion different ways – that doesn’t take away the fact that it is still an incredibly powerful, elegant and syntactically beautiful programming language.

At the risk of sounding like a trite broken record (for the 485,000 time), I think that once again it boils down to using and choosing the right tools for the job. If the consequences of Ruby’s dynamism (among whatever other consequences) outweigh the positive benefits that a Ruby solution provides – then choose a different tool.

You can complain about the verbosity of a language like Java all you want (heck, I know I do at times), but I come back to Java sometimes after working with Ruby for a few months, and I’m all of a sudden thankful for strict, static typing, always knowing what I’m gonna get.

What continues to irk me are the folks who seem completely hell-bent that their way is the only One True Way™.

I was in a job interview the other day (company name shall be kept confidential) at a place that does extensive software development in many languages including Java, C, C++, Perl and PHP (at the very least). Near the end of the interview, we were discussing different languages, and I mentioned how sometimes I really enjoy the dynamic typing facet of Ruby, as opposed to the statically typed facet of Java. At this statement, one of the interviewers piped up to tell me that the fact that I enjoyed dynamic typing at times was “the most brain-dead thing” he’d ever heard anyone say.

It seems so strange to me, to be on the receiving end of an insult like that, coming from a company that performs extensive development in PHP (which is not only dynamically typed, but also weakly typed, as opposed to Ruby which is strictly typed).

At any rate, all of that comes to some sort of summary that everyone should already know by now:

  1. there is no silver bullet
  2. think before you choose your tool/language/whatever
  3. don’t hate the unknown simply because it’s unknown
  4. don’t call someone brain-dead if they sometimes enjoy a programming language that is dynamically typed, it hurts their feelings
  5. read Avdi’s series on sustainable development in Ruby.

A couple weeks ago I ran into some horrible issues with Oracle and activerecord-jdbc. Inserts were failing with an “invalid column index” error.

It turns out this was reported as JRUBY-2018 and resolved, but there wasn’t a release of activerecord-jdbc that contained the fix.

Being impatient like I am, I grabbed the head from svn and built it myself. So if you ever find you need to build yourself an activerecord-jdbc gem from subversion, here you go:

First make sure you have hoe installed.

jruby -S gem install hoe

Grab the source from svn.

svn co http://jruby-extras.rubyforge.org/svn/trunk/activerecord-jdbc

Build the .gem

jruby -S rake package

Install the generated .gem file.

jruby -S gem install activerecord-jdbc-adapter-[version].gem

MAKE SURE YOU UNINSTALL YOUR PREVIOUS VERSION

The chances that you’ll have to do this are very slim. Nick Sieger is usually super-on-top of making sure things are up and working the way they should be, but just in case.

In the process of setting up my new dev machine, I decided I was going to try using MacPorts to install all of the dev-type-software instead of installing into /usr/local.

James Duncan Davidson has a great overview article (that needs no further explaining from myself), titled Sandboxing Rails With MacPorts. Another similar article can be found here.

My problem is that I work on a lot of projects that use ImageMagick / RMagick, and that’s not discussed here.

No worries, I’ll install ‘em and give it a go:

sudo port intall ImageMagick
sudo gem install rmagick

CRAP! I don’t know what happens for you, but ImageMagick installs perfectly for me, and then RMagick craps out and dies something like this:

/opt/local/lib/ruby/gems/1.8/gems/rmagick-1.15.9/./lib/rvg/misc.rb:321:in `get_type_metrics': 
unable to read font `(null)' (Magick::ImageMagickError)
from /opt/local/lib/ruby/gems/1.8/gems/rmagick-1.15.9/./lib/rvg/misc.rb:321:in `render'
from /opt/local/lib/ruby/gems/1.8/gems/rmagick-1.15.9/./lib/rvg/misc.rb:696:in `text'

Now, for the solution I am going to give all credit to Jakob Skjerning, because I found the solution on his site after doing some Googling.

Do this instead:

sudo port install ImageMagick
sudo port install rb-rmagick

Done. Works. Thank goodness.

Capistrano Upgrade Problem

August 31, 2007

A few days ago I ran a sudo gem update and unwittingly got a Capistrano 2.0.0 upgrade that broke my ability to deploy a bunch of existing Rails apps.

cap deploy
the task `deploy' does not exist

Hmm. That sucks. Nick to the rescue. Here’s the culprit:

gem list | egrep -v "^( |$)" 
...
...
capistrano (2.0.0, 1.4.1, 1.4.0)
...
...

Needed to uninstall all the Capistrano gem versions, and install the last working one (apparently 2.0.0 is not backwards compatible with 1.4.1 – which I didn’t know until today).

Here we go:

sudo gem uninstall capistrano -v 2.0.0
sudo gem uninstall capistrano -v 1.4.1
sudo gem uninstall capistrano -v 1.4.0

Say Yes when it asks you to uninstall the cap and capify binaries.

Now let’s install 1.4.1 again:

sudo gem install capistrano -v 1.4.1

Yay! It works! Time to fix those deploy scripts… when I have time.

I wrote this article for IBM developerWorks a while back, but never ended up blogging about it. So at any rate, here it is: Ruby on Rails and XML – for better or for worse.

Someone passed me an interesting link to a recent blog entry by Dave Thomas on what he dubs the RADAR Architecture. It’s a pretty interesting read, and I think that one thing I’d love to see is the browser to become a bit more of a smart client / application platform in the coming years.

One thing that he suggests architecturally in crafting applications is building web-based applications as essentially REST-based services, and separating out what he dubs an “HTML Presentation Server” in one form or another as a thin proxy in front of the actual application. It sounds great to me in theory, but I seriously wonder how much code duplication (logic-wise) would be necessary in order to facilitate that.

Some of the comments on the post seem to talk about how the presentation layer would then be confined to working with a data structure (probably XML) without any smarts in it, instead of having an actual object instance with which you can do some smarter things like validation and what have you.

Either way, it’s a really interesting read, and I’d be willing to bet that Dave’s onto something with the coming years hopefully seeing a transformation of the browser from a dumb recipient into a smarter application client.

Yes. More on testing, and probably nothing new or revolutionary either. As I’m attempting to write tests, fix stuff, and sort out some fun multi-byte character issues, I’ve realized again at how much better it is to be on a project once you reach the state of being proactive, instead of being reactive.

The problem with reactive bug-fixes/features/HOLYCRAPTHISNEEDSTOBEFIXEDRIGHTNOW/etc. is that if your codebase has any sort of, say, complex business logic – it’s likely that reactively doing updates in this fashion is going to come and bite you in the back side.

Being able to proactively perform these updates is a state that I think applies if you have enough unit tests, functional tests, integration tests, and maybe even regression tests in order to ascertain that the new code that you’ve written doesn’t wreck anything currently deployed, and with any luck, you’ve also written some new tests that test the new code that you’re deploying. Go figure (I told you that I didn’t have anything new or revolutionary that I wanted to say).

I spent a bit of time trying to elaborate this relationship in a pretty picture – and here it is:

Basically, the less tests you have, the more reactive you are, and the more screwed you are. The more tests you have, the more proactive you are and the less screwed you are. This is what I shall now refer to as the Triangle of Happiness (the green one).

It’s also worth noting that the # of tests (this doesn’t necessarily mean # of tests, but could be code coverage, whatever) – is decidedly NOT a linear relationship with proactivity. Writing tests definitely reaches a law of diminishing returns. As your screwed-factor (reactivity) approaches zero, and your proactivity-factor approaches infinity – the number of tests that you have to write in order to further increase your proactivity-factor is exponential (give or take).

So, tests are crucially important so you don’t get screwed, but 100% code coverage is absolutely not cost-effective and (in my opinion) not necessary (unless maybe you’re NASA, or people die when your software sends an order of Cookies to Canada instead of California).

Designing For Testability

March 16, 2007

Right now, I’m finding it quite ironic that I’d been thinking about this all day yesterday, after trying to retroactively write some tests for a project that I came into rather late in the lifecycle.

Cedric just posted an entry with the exact same title, almost as if to taunt me with his infinite testing wisdom.

At about 200 times during the day yesterday, I came across a piece of code and thought to myself:

“How in the &$^%#@! am I going to write a test for this?!?”

So with any luck, Cedric will be able to get Hani to stop biling and whining about XML – and finish their testing book so I can go buy a copy.

In the meantime, it seems like the new question I am going to ask myself when designing a piece of code is something along the lines of:

“Sure, this design is elegant, but is it testable?”.

And as Cedric mentions, writing testable code is not necessarily writing code that is better designed.

Programming and Philosophy

February 09, 2007

As one might already know, I read a lot of books. Two of the latest titles have been A Generous Orthodoxy and A New Kind Of Christian – both written by Brian McLaren.

These books discuss a lot about Christianity (and other religions) as they pertain to modernism and post-modernism (among other things).

This got me to thinking about the software development industry, and how the industry is reacting to an era in transition. We are transitioning from the modern era to the post-modern era (and probably have been for a while, whether or not we knew it) – and I’ve formed a bit of an opinion (hypothesis?) about programming languages, tools and frameworks as they relate to this post-modern transition.

It seems to me that the characteristics of dynamically typed languages are those that seem to embrace post-modern characteristics, whereas the characteristics of statically types languages seem to more tightly cling to the characteristics of modernism.

Some terms I’ve heard, used in characterizing post-modernism are things like transience, flux, pluralism, fragmentation. Modernism seems to try harder to rationalize everything, with concreteness – very ‘scientific method’ like.

Am I completely out to lunch, and off my rocker? Probably. But I see a lot of post-modern characteristics in tools like Python, Ruby and Rails. And I see a lot of modern characteristics in tools like Java, C#, etc.

If I wanted to start to talk really crazy, I might say that tools like ASM, BCEL and ideas like Aspect Oriented Programming attempt to take a modern paradigm (in this case Java related) – and, keeping the ‘safety’ and ‘concreteness’ offered by Java as a statically typed language, apply manipulations to byte code at compile or load time, in an attempt to provide some of the benefits that a language like Ruby provides out of the box (in these examples, the ability to dynamically modify and redefine code at run-time). One thing that’s great about tools like Spring is how it manages to take the best of what it can from both paradigms (given the limitation that it’s a framework written in Java for Java developers) – and bring all sorts of post-modern characteristics with it to the Java platform (load-time weaving, friendly AOP, etc.).

I’m probably blabbing about a whole lot of nothing, but no one said you had to read it. :)

Java Meetup With Ben Alex

February 06, 2007

Last night proved to be a great time, with a Java meetup here in Singapore once again brilliantly organized by Christopher Marsh-Bourdon. The event was held at Brewerkz and us Java geeks were on the receiving end of a great overview of the many facets of the Spring Framework from one Ben Alex, of Interface 21 and Acegi/Spring Security fame.

It was great to have a chance to chat with Ben a bit about Spring, open source companies, and different approaches that companies seem to take in building APIs and interacting with developers and users of said APIs.

My first experience with Spring was on a somewhat large personal project that I started working on about a year ago. Code that hasn’t seen the light of day in the real world, but has been a phenomenal learning experience as far as working with Spring, Acegi, as well as the Spring HibernateTemplate support, Spring MVC – and a bunch of other stuff that I just can’t remember.

If any of you out there have the attitude that I used to have, which was something like:

“Why do I need to use Spring, it’s just another framework, and all it does is manage other frameworks.”

I highly recommend that you download Spring right now, and use it. You won’t be disappointed. It’s worth the download and integration for the IoC and Dependency Injection alone.

Slowly...

February 02, 2007

New company with Nick Means (from Texas y’all) is slowly starting to take shape. Between getting paperwork sorted out, coding for clients and looking for new clients – it’s keeping us pretty busy.

So for all your Ruby, Rails, Java and PHP needs…click.

The Magic of Creation

January 30, 2007

I just finished reading a rather excellent interview that Jessica Livingston (of YCombinator fame) conducted with Joel Spolsky. The interview comes out of a book that recently went to press called Founders at Work.

Joel’s getting a little cheeky in his old age, but he still captivates when talking of technology, programming, and addressing issues near and dear to those with an entrepreneurial spirit. In this particular interview, a number of things stood out to me, but none as significant as this. Joel addresses a certain segment of software developers and says:

To them, it’s just kind of engineering step by step; it’s never the magic of creation.

That’s exactly what I don’t want for my ‘career’. To me, I want it to always be about the magic of creation. What code can we weave? What problems can be solved? What great hack can we write that reduces 2000 lines of code to 2 lines of code. Solve problems. Code for the end users. Code for the customers. Code with passion.

On Ignorance

January 22, 2007

My favorite podcast, hands down, is the JavaPosse. There’s nothing quite like sitting back with a cup of coffee and listening to Dick, Carl, Tor and Joe yammer about Java (and/or technology in general) – especially if they’ve been drinking.

A few months ago they launched a Google group in which I am an avid lurker, and very occasional poster. One of the more recent threads was surrounding third-party iPhone application development. I think that the winning comment in this thread was this one:

The simple question here is therefore “Is this phone of any further interest to the Java community/Java Posse?”.

He might as well have said:

If it’s in the world, and it has nothing to do with Java, we shouldn’t discuss it or have any interest, and said object might as well be used as toilet paper. If it’s not Java, it can kiss my bleeeeep.

Forget the fact that it’s a phone – and I could care less if it had anything to do with Java whatsoever. I don’t care if I can write or run 3rd party apps on my phone, or my iPod. I want a phone so I can (go figure) phone people. Of course, all the other iPhone stuff is awesome as well (calendaring, sms, voice mail, iPod, photos, videos, etc.). Why, for the love of all things good, would a community write off said device claiming it no longer deserves “any further interest [from] the Java community” – because it doesn’t have Java on it? Maybe the Java community should stop having interest in hard disks, or RAM, or digital cameras, or iPods for that matter – simply because they don’t allow for third party Java application development on them. I’m making a pact right now. I’m not going to purchase another stick of RAM until I can plug it into a USB port on my laptop, and write a third-party Java app for it that makes it light up, or sing, or something.

Unfortunately, this is the collective wisdom that (stereotypically speaking) the Java community now tends to bring to the table. Let us look at a fictitious (but not fictitious at the same time) example:

Jim: Hey there, have you played with Ruby at all?
Greg: Are you crazy, that stupid thing?
Jim: It’s got some really powerful syntax, and I can’t believe how fast you can prototype apps in it.
Greg: Nothing more than a stupid toy language.
Jim: Have you used it? Have you seen how powerful some of the APIs are?
Greg: No. I’m a Java developer.
Jim: Why don’t you just take a look, see what you think?
Greg: No. If it’s not Java, it’s stupid and useless.

Right. Thanks.

I found this new (to me) Ruby tidbit in a comment on a two year old blog post here.

Basically, in Ruby, you can initialize a new Hash so that any time you reference a given value, keyed by a given key, if that value is previously nil, it assigns a default value.

In “gooder” English, it basically just lets you assign a “default” value for items in a Hash.

Why is this useful? Well, let’s say for example that you are iterating over some array, building up a hash as you go. Maybe the key you are using for the hash is derived from a certain property of each of the objects in your array.

Concrete Example (Java)

We have an ArrayList of Product objects. Product has a “getCategory()” method, and we want to build up a HashMap whereby the key is the product category, and the value is an ArrayList of all Products that fall into a given category.

Map<String,List<Product>> map = new HashMap<String, List<Product>>();
for (Product product : products){
if ( map.get( product.getCategory() ) == null ){
map.put( product.getCategory(), new ArrayList<Product>() );
}
map.get( product.getCategory() ).add( product );
}

I still can’t get over how downright ugly Java code looks now if you want to get it to compile without warnings, thanks to generics. Just. Yuck.

Concrete Example (Ruby)

We have an Array of Product objects. Product has an attr_accessor for category. We want to build up a Hash object in the same manner as we did for the Java example above.

map = Hash.new { |h,k| h[k] = [] }
products.each { |product| map[product.category] << product }

You’ll note that I don’t have to do any check for null (or nil) because the initializer passed to Hash basically says “Any time someone grabs something from the hash, if it’s null, initialize it with a new Array”.

I totally love John Gruber (albeit in a very manly, platonic sort of way). After waking up to knowing you have a 90+ page API manual from UPS to go through to integrate some simple shipping costs, his Conjectural Transcript between Apple and Universal for the upcoming negotiations for iTunes pricing gunk had me in stitches.

Also, I’ve been working on some new marketing slogans for TextDrive. I’ve been so <gag>pleased</gag> with their service of late, that I thought I could spend some time on this. Pretty sure this is a winner:

TextDrive. We Go Down. A Lot.

The server that my site is on seems to have crashed twice in the past few days, requiring a hard reboot. If that weren’t enough, it would appear that ‘at boot’ cron jobs are a mere tease and fallacy, because I can tell you that mine sure don’t run.

I’m looking forward to getting away from this steaming pile of TextDrive crap as soon as I possibly can (I wonder if my slogging is against the Terms of Service?).

Charles Oliver Nutter (AKA “one of the JRuby guys” if you listen to the JavaPosse podcast) put up a post that has me salivating about the deployment of Rails apps on Java app servers that will be a part of our inevitable future.

Currently, my biggest gripe about Rails is deployment. To put it bluntly, Lighttpd is unstable, and Mongrel has a few weird quirks, FastCGI is dated, buggy and well, not very fast.

So at any rate, the very idea of deploying a Rails app on a “real” application server is very cool.

A Few "Special" Experiences

November 17, 2006

Last week I was booking ferry tickets for my wife to head off to Bintan for a weekend away. I happily provided my credit card information and sent it off, and after the transaction redirected – I got hit up with this (click image for a larger version):

You’re seeing it correctly – it looks like the SQL parameters that are going to be inserted into the database after I click on the wonderful “Continue” button that FireFox has presented me with. Frightening.

Also last week, I upgraded iTerm to the latest version (0.9.3) – and the first time I kicked it up I got this piece of joy:

I hope that clicking “Yes” was the right thing to do.

John Gruber has put up an interesting piece discussing the fact that releasing a piece of software as “Beta” is absolutely no excuse whatsoever for it to be full of bugs.

This has been addressed before by several other people much smarter than myself, including Joel Spolsky who, WAAAAYYYY back in the day (July 2001 – yes, I really have been reading his articles for that long) had this to say:

Anyway, getting good software over the course of 10 years assumes that for at least 8 of those years, you’re getting good feedback from your customers, and good innovations from your competitors that you can copy, and good ideas from all the people that come to work for you because they believe that your version 1.0 is promising. You have to release early, incomplete versions—but don’t overhype them or advertise them on the Super Bowl, because they’re just not that good, no matter how smart you are.

For the record, I’m not saying anything about Disco in particular (the particular app Gruber was commenting on), I’m talking about the broader world of software development in general. Although, I downloaded Disco to try the smoke feature, and was disappointed that it wouldn’t show smoke on my MacBook—so um, it got zapped.

At any rate, there is a fine line between releasing a quality product that still needs a bit of spit and polish, and releasing software that utterly disappoints the end user. Unfortunately, that fact can put a lot of developers / startups between what some might call, a rock and a hard place, the reason being that unreleased software that stays unreleased is essentially worthless, and released software that utterly disappoints end-users is essentially worthless. With the former, you have nothing, with the latter, you likely have a lot of frustrated end-users who have blogged about how bad your software sucks to the entire world, and even if you do get around to releasing a version that doesn’t suck – the damage is likely already done—and very difficult to recover from.

So the moral of the story is: Release early, release often – but not until it’s ready..

About a week ago I received an email from PayPal which contained the first donation I’ve ever received for JarIndexer. I immediately sent a thank you note to the donator, and received this response:

I really support people like you who share tools and things like that for the rest of us, especially when it removes pain. So, thanks for JarIndexer. It saved me so much time and it was very easy to use. So, keep up the good work.

That means a lot. JarIndexer is a super simple program, gets about 30-50 downloads a month, and was very easy to write, but I’m extremely pleased that it has been of use to someone, and managed to relieve a bit of pain.

I suppose this provides me an opportunity to say my thinks as well, to the open source community in general – and to all the folks out there who provide great software that make our lives easier as developers. I suppose I could specifically mention people like James Duncan Davidson (ANT), Rod Johnson (Spring), Gavin King (Hibernate), Yukihiro Matsumoto (Ruby), David Heinemeier Hansson (Rails), Thomas Fuchs (Scriptaculous) and Sam Stephenson (Prototype). In my day-to-day coding life, when thinking of people who freely give their software to the community – these guys have made me the happiest I’ve been in years.

Active Merchant

November 12, 2006

Next task on my list looks like a fun one, integrating payment into a custom e-comm site using Active Merchant.

Documentation seems severely lacking, which could be to the simple looking usage scheme. I might try to write some docs as I go, and if I do, I’ll post them somewhere or consider contributing them.

So far I managed to dig up how to install it – the easiest way seems to be as a plugin – from within your rails app:

ruby script/plugin install \
svn://vault.jadedpixel.com/active_merchant/trunk/active_merchant

User Expectations

November 12, 2006

It is quite possible that Kathy Sierra writes what is the best blog on the Internet. The relentless shift from developer-focus to user-focus is something that is becoming more important pretty much on an hourly basis.

One thing that really got me thinking about this was the recent video of 37 Signals (Jason and David) that’s been making the rounds, you know, the Mac one.

Albeit the video is a bit on the glam side (maybe I’m only saying that because I don’t have their stunning good looks?). At any rate, one of the things that David says in the video is:

“We’re trying to affect both our peers in the industry and also customers out there, just raise their level of expectation…”

This seems to go along with the whole theme of Creating Passionate Users – but why I bring it up here is for the following reason (Warning: Gross Stereotype Ahead):

People who write apps in Ruby on Rails care about user experience. People who write Java apps don’t give a rip.
-me

(Ok – I’ll make an exception for JIRA). I can feel the flames flying this way already, but this has been more often than not what I have observed in the past year or so. It’s not that Rails provides some sort of Magickal Code that isn’t possible to provide in a Java-based application – it’s that Rails makes it easy for the developer to integrate those features. I mean, forgive me if you like Java Server Faces – but the last time I looked at that code – I ended up in a psychiatric ward for a month before deciding that I’ll just stick with JSP, thanks.

After our Singapore Ruby meetup a couple weeks back, I was chilling with Herry and Choon Keat over a bite to eat – and the primary things that we seemed to be constantly coming back to when discussing Java vs. Ruby were along the lines of:

  1. It makes us more productive
  2. The code is cleaner, smaller, simpler, less bloated
  3. It’s easy to create rich, responsive and enjoyable user experiences
  4. We are a lot happier when we’re coding in Ruby.

Don’t get me wrong, I’m not saying that Ruby is now the de facto standard language and “you will be assimilated” all borg-style, I’m just saying that if it’s a feasible language to use for a given project, and Java is equally feasible – I’ll take Ruby in a heartbeat.

It’s about time that the end-users of software start raising their expectations, and time for developers to deliver software to their end-users that doesn’t suck. And one of the major driving forces of this in the past 12 months has been Ruby on Rails, along with some great JavaScript libraries like Prototype and Script.aculo.us. So thanks, guys.

One Week Later

November 12, 2006

At long last, after sucking most of my previous site content and blog entries from TextPattern, I’ve manage to finally deploy the new site to TextDrive now powered by SimpleLog and RoR.

I’ve previously found the documentation at TextDrive severely lacking, especially in the area of Rails application deployments, however this time around, I was pleasantly surprised by a series of articles that were a great help (along with scripts and config files) for deploying your Rails apps on Lighttpd.

Several other Rails folk I’ve spoken to have expressed concern over Lighttpd’s stability, many of whom have switched to Mongrel. I’m hoping that I don’t run into any stability issues.

Previously, I also had a nice site up for JarIndexer and XafeNotes, but alas, that is no more. I can’t bother to manage a separate site, so they’ve been included in this site for now. JarIndexer is still available for download, as it seems to be somewhat widely used, but I’ve temporarily yanked XafeNotes, as I have some intention of making it free (as in beer), and need to pull out the licensing stuff from the code base. Who knows when that will happen.

About three weeks ago, I started doing some work for Orangepath, a Texas-based company, that I’m hoping will turn into a great long-term relationship. It’s a breath of fresh air to find a company built on morally upstanding principals. I’ve actually had a ton of stuff to blog and yammer about these past weeks, but my time has been spent trying to get this site up and running, instead of writing content to bore people to death. I’ll apologize in advance if there seem to be more entries than usual in the coming days.

Although this topic is something that should be obvious to everyone by now, as it seems to be beaten to death on a regular basis (in a good way), I am still amazed at how many hiring companies still place stuff in their hiring ads like:

  • Must be able to juggle multiple projects simultaneously
  • Excellent multi-tasker
  • Ability to productively work on several projects concurrently

As a matter of fact, this jibberish nonsense used to be something that I put on my resume – until I realized that, well, it’s simply not true.

The latest tidbit I’ve read about this comes from a link to Coding Horrors that I noticed on Joel’s reddit site. The long and the short of it is that you effectively lose 20% of your time (due to context switching) by adding a a single project to your current workload. It only goes downhill from there (as additional projects are added). That 20% isn’t “lost” because that’s how much of your time you are now spending on the second project. That 20% is time that is flushed down the toilet, never to be recovered.

Let’s use a good concrete example. If you spent 4 hours in the morning working on Project A, and after that 4 hours your boss tells you that it’s time for you to start working on Project B, you can expect to flush the next 1 hour and 36 minutes (20% of an 8 hour day) down the toilet as your brain tries to forget the 600 things that you were remembering as you worked on Project A, and tries to lookup the 600 things you need to be remembering to work on Project B. This effectively leaves 2 hours and 24 minutes of productive time for Project B before you (hopefully) go home to watch Start Trek: The Next Generation re-runs (and/or an episode of 24).

He cites other great sources, more from Joel on programmers and quiet working conditions (see point 8). Not to mention this article and some great stuff from Kathy Sierra (who’s Creating Passionate User’s blog is nothing short of absolutely fantastic) stating that multi-tasking makes us stupid.

So, in summary:

  • Get quiet working conditions for your developers
  • Put them on one project
  • Give them a spec, and leave them alone. If they’re any good, they’ll come and ask you questions when they need to clarify something.

All I want is a free lunch

September 08, 2006

Joel Spolsky is at it again, writing recruiting ads disguised as articles on hiring the best programmers (well – ok, maybe they really are articles on hiring the best programmers, but I have to get my jabs in somehow).

I’ve worked for a few companies in my day, as an employee (three, I think – we won’t count the one that somehow I managed to go work for with the promise of bringing legacy systems into the new age, but ended up supporting people’s Outlook Express problems. Geez, what a mistake that was).

At any rate, one thing I’ve noticed about most software companies, is, to paraphrase Joel: they SUCK to work for.

Why is that? Every time I think to myself “maybe I’m getting tired of consulting, and I should go get a ‘real job’” – it doesn’t take long for me to think of all the reasons I wouldn’t:

  • I hate commuting, and I have to pay for it out of my pocket.
  • I hate packing a lunch, and I have a hard time paying to go out for lunch every day, and whoever hires me isn’t going to give me free lunches. If I work at home, I can easily make some yummy spaghetti or something, and don’t have to eat a stupid scrunched up sandwich every day.
  • I hate crappy computers
  • I hate CRT monitors
  • I hate cubicles
  • I hate timesheets and bureaucracy

The first “job” I had as a developer (was hired before I finished school) – was for a pretty cool company, at the peak of the ‘dot com’ era. I had a window office in Yaletown, overlooking YBC, coding cool Java projects, and it was stellar. But – no free lunch, crappy chair, hour long commute each way (which I had to pay for out of my pocket), I had to buy my own 64MB of RAM to upgrade my machine to 128MB (remember, this was over 6 years ago) and no free technical books anywhere to be found. I can’t even begin to count how many times I said to myself:

If only they would pay for a catered lunch, or lunch out, I wouldn’t be in such a crappy mood about my salary.

After I was told that I was going to be starting to program Oracle Forms and Reports (gag), I left for a startup. The startup paid more money, and I worked from home, in the peace and quiet of my fast machines, with a big monitor and comfortable chair. No free lunch, but at least I could make some spaghetti, instead of a stupid sandwich.

And now I sit here with 2GB of RAM in my MacBook, and 2GB of RAM in my Windows Workstation, with a nice big LCD, in the comfort of an office at home, with little monkeys that occasionally run around outside my window (not joking – lots of monkeys here in Singapore).

So tell me, why is it again, that I would go get a real job?

Stuart Robbins

August 25, 2006

As I’ve been working on fixing up a bunch of issues (read: cleaning up a mess someone else left behind) for a site that is doing streaming media / television, I came across a fascinating little interview with Stuart Robbins, discussing briefly some concepts from his book entitled Lessons in Grid Computing: The System Is a Mirror.

He discusses some very interesting things, including how human beings are an integral part of a given computer system, but also discusses an interesting concept of how the systems that we build are reflections of who we are.

The information systems we are building in our companies… are reflections of who we are… As a result, you can’t fix the problem in the mirror. It is our inclination in the industry, when you don’t like what you see, to get rid of the old mirror and put a new ERP mirror in, and it takes you 2 years, and then you realize, you still don’t like what you see, and it’s because you haven’t attended to the organization that keeps reflecting in the mirror.

And again:

Contrary to most of the pundits that say the network is the platform, I propose it’s just an enabling structure, and that we are the platform.

Looking forward to picking up a copy of that book, I think it’ll prove to be a very interesting read.

Agile / TDD

June 08, 2006

I want to give kudos to Cedric Beust for once again being able to eloquently state a lot of the issues that I have with some of the “hand-waving” thrown about by the promoters of Agile and Test-Driven methodologies.

You can read his blog entry here.

Don’t get me wrong, I think that being “agile” (in the Merriam-Webster sense of the word) is an extremely good thing. As a matter of fact, I think it’s probably even more important to have “agile” management, then it is to have “agile” development teams.

But even after 2.9 seconds of reading the simply untrue statements that often come out of this camp, I can think of several examples where you simply CAN NOT write an automated test for.

Tell me about my Swing GUI – how can I write an automated test to make sure that GridBag hasn’t bit me in the back-side, and that all my components and my frame resize properly. Maybe a silly and extreme example, so sue me :)

At any rate, it’s not being agile that I have a problem with, nor is it testing. Do I enjoy writing unit tests? Not really. Do I do it anyways? Yes. But more so it’s the extremist attitudes and a lot of the other practices surrounding these agile/TDD/XP methodologies that quickly become agitating. Instead of thinking “What is the best way to do this?” – you have people saying “What does my Agile / TDD manual say about how I have to do this?”.

Again, right tool for the job, right methodology for the job. I don’t care what you call it, but stop pigeon-holing yourself into “one methodology to rule them all”.

The code is not the spec. The tests are not the spec. The spec is the spec. If you have any problems with that statement, I suggest you go find some Spolsky to read.

From KL

May 27, 2006

In Kuala Lumpur right now. Carly had a conference to go to, so I’m tagging along for the ride. Unfortunately, there aren’t any JavaOne shows kicking around for me to attend, so I’m going to have to settle for food, coffee, shopping and sightseeing.

Stopped by the Crumpler store in Suria KLCC this morning and couldn’t decide whether or not I wanted to buy myself a fancy-shmansy bag, maybe tomorrow.

Tried out some shots with the new Camera which I’m looking forward to seeing in all their full-size glory once we get back to Singapore.

Other than that, I don’t really have anything of interest to say at all. I’ve read through Christopher Hawkins blog entry on ‘11 clients you need to fire right now’ a few more times, as I think that one of mine definitely falls into a number of those categories, and it doesn’t seem to be worth the high blood pressure to keep it going.

I’m much more interested in what the end-user really needs, than in what the person who ‘owns’ the project thinks that the end-user needs, and that seems to be another issue I’m having. When the project owner claims to understand everything about the ‘end-users day to day work’ without ever consulting the end-user about what they need (note that in this case, ‘end-user’ happens to be employed by aforementioned project owner, this isn’t some web-based service for any-old-user to sign up), something is terribly, terribly wrong.

At any rate, I’m done here. Til next time.

Interceptors in Spring...

March 06, 2006

...and (why || how) they can be your friend.

Useless Preamble

As previously mentioned, I’ve been using Spring a whole lot in the ‘latest project’, and in addition am using Acegi Security to provide authentication and authorization services.

Scenario

Now that all that is out of the way, I, like most other people who write webapps, wanted a way to display the currently logged in users information on the screen for them. You know, username, maybe a “Hello, $USERNAME! Thanks for coming out!” type nonsense. So in Acegi, the code used to get the currently logged in user looks like this:

Authentication auth = SecurityContextHolder.getContext().getAuthentication();

Once you’ve got the Authentication object, you need to get the Principal, which will at last be castable into whatever your User object implementation happens to be. So basically for me, I had a getUser() method that looks like this:

    protected User getUser(){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if ( auth != null && auth.getPrincipal() instanceof User ){
return (User) auth.getPrincipal();
} else {
return null;
}

The Problem

Now, this is all well and good, and in Spring, chances are you want to add this code to a Controller implementation somewhere. But which Controller? I’ve got a ton of them. I thought of extracting it to some superclass, but based on the Spring controller hierarchy, whereby sometimes you might extend AbstractController, or SimpleFormController, or implement the Controller interface directly, it didn’t seem like this was going to cut the cake, so to speak. We don’t have multiple inheritance in Java (duh!), so I couldn’t do that, and I certainly didn’t feel like putting the code in some separate bean that I would have to inject into every single one of my controllers. Oh what to do?

The Solution

Enter interceptors. Oh how we love thee (when they’re the appropriate tool for the job).

So, an interceptor basically does exactly what it says it does. It “intercepts” method calls to an object. For all the details, go read something about AOP, this is just going to be an example in somewhat plain English.

In my particular case, I wanted to “intercept” all calls to the handleRequest(...) methods of the org.springframework.web.servlet.mvc.Controller interface (which all Spring controllers implement). If I could do that, then any time a method was intercepted, I could simply call my neat little getUser() method and dump the user into the current HttpServletRequest as an attribute. Spot on!1

So um, how the heck to we actually do it? Ok, first of all, let’s write the actual interceptor class. This is the class that we want to be automagically called any time the handleRequest(...) method of a Controller is executed (I’ve gotten rid of comments and imports).

public class AddUserToModelInterceptor implements MethodInterceptor {    public Object invoke( MethodInvocation methodInvocation ) throws Throwable {
ModelAndView model = (ModelAndView) methodInvocation.proceed();
if ( model != null && getUser() != null ){
model.addObject( "user", getUser() );
}
return model;
} protected User getUser(){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if ( auth != null && auth.getPrincipal() instanceof User ){
return (User) auth.getPrincipal();
} else {
return null;
}
}
}

Note that the fully qualified class name (in case you’re curious) of MethodInterceptor is org.aopalliance.intercept.MethodInterceptor

Great, so we have an interceptor, now what? Lets go define some beans!

  <bean id="addUserToModelInterceptor" 
class="com.example.AddUserToModelInterceptor"/> <bean id="controllerClassFilter" class="com.example.ControllerClassFilter"/> <bean id="controllerPointCutAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<property name="classFilter" ref="controllerClassFilter"/>
<property name="advice" ref="addUserToModelInterceptor"/>
<property name="mappedName" value="handleRequest"/>
</bean> <bean id="autoProxyCreator" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>

Alright, the first bean definition is just an instance of the AddUserToModelInterceptor that we just finished showing in the above example. After that, we have a class filter (which we’ll look at in a second). Thirdly there is the bean controllerPointCutAdvisors. Joins, Pointcuts and Advice are fancy AOP terminology that you should really read about, but I won’t cover here. We pass three simple properties to this bean. The first is just the class filter, the second is the “Advice” which is a reference to our interceptor bean, and lastly, we pass “mappedName” – which is simply the method name that we would like to intercept calls to, in our case, “handleRequest”. Lastly, we define a proxy creator bean, which in this case is an instance of Spring’s DefaultAdvisorAutoProxyCreator. Basically, what this bean does is once all of the bean definitions have been loaded, it scours all loaded beans applying advice to matching pointcuts. In our case, it will apply our “addUserToModelInterceptor” advice to all bean instances that match our “classFilter” that have the method name “handleRequest”.

Briefly, the class filter is just a dead simple interface that Spring offers. In essence, we don’t want our advice to be applied to any classes that ‘accidentally’ define a method called handleRequest. We only want the advice applied to classes that implement Spring’s Controller interface. So here is what our ControllerClassFilter looks like:

public class ControllerClassFilter implements ClassFilter {
public boolean matches( Class aClass ) {
return Controller.class.isAssignableFrom( aClass );
}
}

Fewf! Something easy to end off with!

I hope that this has managed to help shed a little light on how interceptors can be useful, and hopefully some of it actually made sense.