Wednesday, August 29, 2007

Handy IRB Trick: grep_classes Method

Just before New Year's 2006, James Gray and Pat Maddox both showed me how to create a Scriptaculous autocomplete dropdown with real-time contents from Ruby's ObjectSpace, which you could use to create a Rails app which performed reflection via Ajax.

The other day, I realized the code is a lot more useful if you put it in your .irbrc file. Here's the version I use in mine (behind the link). I repurposed it into a method called grep_classes. It does exactly what it says on the tin - greps existing classes for whatever string you pass it. Very handy when you're interacting with a controller in IRB and can't remember the exact name of the mock request class used in functional tests (for example).

Getting Legacy Code Under Test

There's a good book on this subject by Michael Feathers, but the single best trick I've ever read for getting control of a legacy code base comes from Jim Weirich's blog:

...dealing with legacy code means that the code is already written and the test-first approach won’t work. That’s ok, I have a little trick that I use. Just comment out the bodies of all the methods in the class you are about to test. Then write the tests that force you to uncomment the code. Just uncomment only enought to get the tests to pass, don’t uncomment anything you don’t have to. You have enough tests when all the code has been uncommented. The technique is almost as good as doing real test-first.

Obviously this technique can also have the side effect of uncovering code which does nothing, which, in my experience, is a very common problem with legacy code. There's frequently code in there which simply does nothing at all. If you comment everything out, and only uncomment as you write tests, and find yourself back to full functionality with everything under test, and there are still lines of code that no test ever forced you to uncomment, you can very safely throw that extra code away like the garbage it is.

This is an essential technique for legacy code.

Monday, August 27, 2007

ActiveResource: A Rails Scalability Solution

ActiveResource looks very much like ActiveRecord, but appearances can be deceiving. It's not supposed to be a distinct object brokering system, just a client API for REST web services. ActiveResource's gem_server blurb says "think ActiveRecord for web services." That's very, very different from "a plug-and-play replacement for the pivotal role that ActiveRecord plays in Rails". The logical conclusion is that you shouldn't use ActiveResource as a distributed network version of ActiveRecord. Resources are different from objects, after all. But what the hell. Let's be bad guys.



The killer app for ActiveResource isn't Amazon S3 clients. We already have an Amazon S3 library. It isn't Flickr mashups either. The killer app for ActiveResource is scalability - the major bugbear of Rails apps, or at least, the major flaw in Rails' reputation.

ActiveResource gives you a kick-ass scalability solution. Consider that with Rails, Web apps are now as cheap and easy to create as shell scripts. As anyone with a background in economics will grasp immediately, it's inevitable that this low cost means people will start to throw Web apps at problems as casually as they currently throw shell scripts at problems, and this is exactly what's starting to happen. Certainly, with Rails, a Web architecture which requires two Web apps is no big deal.

An emerging strategy for Rails scalability is to pair ActiveRecord server apps on the back end with ActiveResource client apps on the front end. Your ActiveResource app sees the public Web. Your ActiveRecord app serves no HTML at all. Instead, it simply supplies its client app with data via REST. It's almost like an exponential version of MVC. Your MVC database app acts as a model, and your MVC customer-facing app serves as both controller and view. MVC to the second power.

You can add new servers for the customer-facing side without scaling the database side - or vice versa. It's also easy to independently load-balance the front and back end apps. Decoupling makes your deployment more flexible.

I'm not a deployment expert, but I have this architecture from people who are. This may become a dominant use case for ActiveResource in the future. Not just because it gives you a powerful way to address Rails' scaling problems, but also because the only people using ActiveResource are Rails developers. DHH is an amazing evangelist, but he's a terrible ambassador. ActiveResource will probably only get users from within the Rails community for the time being. This makes it even more likely that people will want to use it as a transparent network proxy to ActiveRecord. It's just what most ActiveResource users will expect.

With that in mind, I might as well say here what I said at the Rails Edge mini-conference and in blog posts the other day. At my current project we have a small but useful extension to ARes. We've implemented an ActiveRecord-style find(:include), so you can do ARes finds with association classes included. It was actually very easy to code. The tricky part is packaging it. It may have to become two plugins, one for the client side and one for the server side. It mostly uses code from Edge Rails which makes #to_xml more robust on the server side, but it also patches ARes on the client side slightly too.

Be warned, this architecture has a downside. It's not just that ActiveResource doesn't work with form handlers or validation or anything else with the same ease and grace of ActiveRecord. If you've ever heard war stories (or horror stories) from EJB developers, you know that duplicating model code for two sides of a network is always a pain in the ass. Fortunately, the best practice strategy for EJB development is to write Ruby code to auto-generate your EJB files. I use best practice in the sense that it's a practice, and the best one, not in the usual "nobody ever got fired for choosing IBM" sense of the term. I'm not trying to suggest, for instance, that EJB developers have ever actually heard of it. This obscure best practice was defined in a book called Code Generation In Action. The author, Jack Herrington, included EJB examples because he had to. He wanted to make it a Ruby book, but his publishers wouldn't let him, because at the time, the market didn't exist. So it's a Ruby book disguised as a general programming book which just happens to have Ruby in it. And it has the best solution for EJB ever written.



As one of the first Ruby books available which didn't require learning Japanese, I suspect Code Generation In Action had a major influence on the design of Rails. I found out about it from DHH's blog, and certainly code generation is one of Rails' core strategies. Ruby makes code generation so easy that duplicating model code for two sides of a network doesn't have to be any kind of inconvenience at all. Although I currently don't have any code to address this, we may need it at my current project sooner or later, and if I were to lay out any kind of ActiveResource roadmap to make the framework more useful for people who want to use it this way, automating duplicate model generation would be a major milestone.




Update: in practice there are very serious roadblocks inherent to this architecture. You lose so much by replacing ActiveRecord with ActiveResource that it's almost like coding Web apps without a framework at all. The architecture's very handy, but it doesn't come for free.

ActiveResource Won't Always Play Nice With Form Handlers

One thing to watch out for developing a Rails app with ActiveResource is that all the form handlers on the front end assume ActiveRecord objects, and the mismatch there can seriously kill your productivity. If you want a return to the past - or an idea of what PHP and Java developers still tolerate every day - try to use standard ActionPack form handlers with ActiveResource. form_for is particularly painful, and date_select nearly has to be done entirely by hand. Validations, as Chad Fowler noted at Rails Edge, are also pretty painful.

The problem, basically, is that the attr_accessor-like methods you can expect on an ActiveRecord object won't be there for an ActiveResource object until HTTP response time (I think), while they're there on ActiveRecord objects from the moment you attempt to use them. Currently I'm dealing with this with a lot of painful, manual hacking, but the correct response is probably a method_missing on ActiveResource::Base that looks like the one in ActiveRecord.

An even better approach might be to make both ActiveRecord and ActiveResource subclasses of some object which represents an active record with no assumptions about its data store. The flaw here, of course, is that using ActiveResource as if it were ActiveRecord is not generally recommended. There's at least one good reason to do it anyway, though. (That'll be the subject of an upcoming post, I think.)

Sunday, August 26, 2007

The Rails Edge Mini-Conference Was Great

Just got back from this late-ish last night. I enjoyed this more than I enjoyed RailsConf. Highly recommend it.

By the way, Jason from Rails Envy is one of those people who are just naturally funny. I guarantee you if he was out here in Los Angeles he'd be doing standup or something.

Saturday, August 25, 2007

Edge Rails May Provide find(:include) for ActiveResource

At Rails Edge yesterday I said that my new project has a patch that gives ActiveResource find(:include) functionality. I was planning to set that up as a plugin - but the other developer has checked in some code that obviates my patch and it looks as if that code comes from Edge Rails. So it might not be coming out as a plugin after all - we might all be getting it for free as part of ActiveResource. I don't know yet. Could be cool, though.

Semantics Aren't Just For HTML

How do you tell if your code needs to be refactored?

If it looks like code, it needs to be refactored. You want code so clean and simple that anyone could understand it.



Successful refactoring and eloquent DSLs lead to the same place: your code becomes semantically valid. As your code achieves semantic validity, it becomes both easier to maintain and more powerful. People often emphasize the connection between maintenance and successful refactoring, but it's also very important to realize that precise expressiveness and power go hand in hand. Rails provides a very precise, expressive DSL for building web sites, and in doing so, gives you so much power that where people used to throw shell scripts at problems casually, because shell scripts are so easy to make, today people in the Rails community throw Web apps at problems casually.

Semantic validity matters so much that you should take it as a serious sign of success if your code stops looking like code. Conversely, if you can only show your code to other programmers, you've got some refactoring to do. Languages like Ruby and JavaScript make DSLs so easy that there's really no good reason for writing code that only programmers can understand.

Obviously at some level code will always be something only programmers can understand. However, doing high-level things in a low-level way is like going to Spain and speaking Chinese. The language you choose (or define) should match the context you're in. It doesn't even have to apply to totally green newbies - if you just write code that less-skilled programmers can understand, you end up with better code. You also find yourself using it. At that point, you'll find that some bits of your semantic mapping work better than others. When you make your code semantic, you find out how much you do - or don't - understand your problem domain. If you can just look at it and grok it instantly, you got it.



If not, fix it up!

Rails Edge Notes: Chad Fowler & Marcel Molina: Live Code Review

First thing, rcov
compare controller size, model size, look for largest files
then wc -l on app/models

Biggest files are most important and/or biggest messes

Observer functionality with any kind of external resource go in sweepers often

observe ActiveRecord::Base

uber-sweeper
weird
not necessarily bad, certainly unusual

before_create - initializes magic number for global config - needs description, and probably relocation - no intention revealed - should be described for what it is

assigning id directly -> "major leaky abstraction"

Chad dissed some of his own code from Rails Recipes - live and learn

set associations through the association code - the value of semantic code

use Symbol#to_proc

"never make an action have more than five lines."
"whenever it's more than five lines, it's bad."

Eric Evans - Domain-Driven Design - huge recommendation
(And Kent Beck Smalltalk Best Practice Patterns)

def fullname, def reversed_fullname, no, set a :reverse keyword or even a reverse method on the attribute itself (not even the class)

Friday, August 24, 2007

Dave Thomas: Rails Treasures Notes

with_scope:

merges conditions
can apply differently to :find and :create clauses
:readonly
cool thing about using hashes as if they were keyword parameters is that keyword parameters become mergeable - a benefit of a hack around a limitation in the language
with_scope being deprecated by core, made private to models

with_options:

merges options, makes it less repetitive
any Ruby object can do this - they put it on Object!
(madness! but cool)
either adds a hash as last parameter or adds values into an existing hash parameter - not necessarily one named options, just whichever one's last in the args.

returning:

awesome!
factors out megadooky "temp var with temp var on last line" pattern

&:xx -> The Blockinator
(aka Symbol#to_proc)

Lookup Constants for caching

now.to_s(:db) # mysql format
now.to_s(:short)
now.to_s(:long)
now.to_s(:rfc822)

merge new strftime strings into the conversions array and you can do
now.to_s(:any_name_you_like)

Range#to_s also extended, (some..range).to_s(:db) becomes BETWEEN clause.

Enumerable#sum
Enumerable#index_by
Enumerable#group_by

Array#in_groups_of

script/generate model wombat --svn

Automatically adds new models to Subversion.

Generic to all generators, so if you write your own, you get it for free.

In console, ActionController::Routing::Routes, no, just irb object and then object is the default object for your entire subsession.

TextMate: Footnotes

Thursday, August 23, 2007

URL Gotcha in S├ębastien Gruhier's Prototype Carousel

This is a neat little widget.



According to various blogs it gives you the same functionality as a similar YUI widget but weighs in almost 200KB smaller (counting YUI overhead).

However, its documentation is pretty sparse. So, I'm providing one quick note. Otherwise you might end up taking out your frustrations on an innocent flatscreen monitor.



The url parameter in Carousel's initialization function does not precisely correspond to the URL the widget will actually call during the course of its Ajaxy goodness. Watch out for that one. The url parameter actually defines a base URL to which Carousel will then append two parameters (in the CGI sense). Those parameters are start and nb. So whatever base url you give it, it will then call

base_url?start=something&nb=something_else

Rails Edge Liveblogging

Dave Thomas & Jim Weirich: Metaprogramming

Class methods in Ruby are not class methods; they're singleton methods on class objects.

It's not syntax that defines the class method, it's execution.

Jim Weirich: "I avoid the @@ variables."
Lot of pressure to put it in
Hated it all along
For very good reasons
Ugly semantics
Every subclass gets their own copy
No real inheritance per se - copies, not navigating the tree (?)
Taking it out?

Key to metaprogramming: track the value of self
Know thyself

JW: When confused, treat classes as objects.
e.g.: module A # etc ; class Dave ; end ; Dave.extend A

There's an included, similar to extended

Xyz.send :include, Class == module Xyz ; include Class ; end
That send fails in 1.9!

Why? -> Code closer to domain
Coding close to the application domain = good

Show tests to client -> get buy-in -> "major loophole in testing philosophy"

...

Chad Fowler & Marcel Molina: Well-factored Rails

Quick & Dirty vs. Slow & Clean
not any more!

Making the same comments frequently

Leaky Abstractions everywhere

TCP/IP -> leaks because TCP enables guaranteed connectivity, but unplugging computer violates abstraction, so high-level code needs to address failures of the low-level code to genuinely represent its problem space

Unless you understand the SQL which Rails generates, your application will suck. Guaranteed.

Keep tail -f log open all the time; understand the SQL underneath; watch it happening.

Dave Thomas: h method is leakiest, most dangerous abstraction

Use Jamis Buck's ActiveRecord Logger trick - Rails core was toying with making it the default for Rails console

Chad mentions the problem of Rails n00bs who see the abstractions and don't realize there's anything underneath. They can build stuff very quickly but it invariably falls apart. I worked for a large, respectable company where this happened quite disastrously. A very smart MBA who wasn't a programmer but could code did exactly this, wrote something which used the abstractions well but without thinking about the underlying system, and the whole thing went kaboom.

Quick and Clean requires Zealotry

Constraints Are Liberating

MVC as a constraint
Over-do MVC
Don't put any code in the views; don't put any DB code in the controllers
Ruthlessly Kill Duplication

Marcel Molina: Thomas Aquinas' definition of beauty
Clarity
Integrity (Form -> Function (crystal hammer not beautiful))
Proportion
Simple template

magazines/readers -> join table: subscription
"Everything you need to do to connect two objects is a CRUD operation."
"That might not pop out unless you were thinking in terms of resources."

"In the context of the controller, order and limit are leaky abstractions."

When adding DSLs or similar abstractions, package them as plugins, even when you have no plans to distribute them at all. Very preferable to /lib due to presence of testing. (Also I think this gets you past explicit requires in the environment file for free.)

with_scope nesting
implictly merges options hashes
allows you to expressively declare the semantics of SQL conditions without using SQL
imparts significance of a find to that find
nesting with_scope in a model gives you named keyword finds very easily
very cool

put SQL fragments in constants and then with_scope(Constant)
Mike Clark wrote that
it kicks ass

conditions gets merged seamlessly
(thanks to ugly stuff hidden deep inside Rails)

that's awesome

You can do the same thing with methods instead of Constants

Views can and will get bad - battling against the framework in Chad's opinion
Biggest failing of Rails (Chad says) is ERB
Ruby with embedded JavaScript embedded in HTML
Use helpers to hide that stuff away
Hide the ugly stuff by pushing it down a level - at the end you find none of it is ugly

Additional benefit - recontextualizing the code during refactoring shows you your code from a new perspective - this makes you see improvements you can make

Alternatives to ERB: Seaside views!
"Talk to Giles Bowkett if you want to know more about this" - wait a minute, that's me!

Blocks make helpers more powerful

Finally, the best way to get good at programming Rails is to master Ruby. Forget about Rails, master Ruby.

...

Marcel Molina & Stuart Halloway: Presenters

Basecamp had a 500-line helper file

Helpers have no structure or organizing principles

Difficult to apply OO principles to helpers because it basically turns into PHP - just a crapload of functions in a big bag

Helpers are hard to test; creating presenters means you have objects, and it's easy to test an object.

I have a decent example of this, I should post it.

Oooh, this is cool. A method_missing on a presenter which checks if the template responds_to a given method.

Reference to Smalltalk Best Practice Patterns - Method Object pattern similar

Marcel presenting a nice abstract super class for presenters
It automatically links the view and model and has access to methods in each

Dave Thomas: "personal crusade against instance_eval."

...

BEST FOOD AT A CONFERENCE EVAR.

Seriously. Sushi. Mountains of vegetables. Bacon and eggs at breakfast. I avoid bacon and eggs (although I admit I had some bacon) but that's a huge win. Clobbers the 10.30am sugar crash of most conference breakfasts.

...

Ezra Zygmuntowicz (& Mike Clark) - Xen & Rails Deployment

I've read the slides for this presentation before. Very good stuff.

Zed Shaw turned over Mongrel dev to a team including Ezra.

Upcoming Mongrel changes will be opt-in. Essentially Mongrel development is stable.

Mutex lock in Rails is for thread safety.

Apache - kind of a resource hog.

Nginx. "Some of the best C code I've ever seen."
Apache 100MB RAM -> Nginx 6MB RAM
Lighttpd similar, but leaks memory under high load.
Nginx -> author very approachable, growing community, most stable part of the whole stack.
Good wiki.
Comes with geographic load-balancing.
"You can slow down the robots."

Food coma. Food coma. Food coma. Liveblog activities ceasing. tail log/food.coma for more detail.

Wednesday, August 22, 2007

Ara T. Howard's DRYer Acts As Taggable

On the original blog, Ara introduces it with a question mark, the question being whether or not a replacement for acts_as_taggable is really needed.

I would say it is. First, there's two acts_as_taggables out there - only one is a plugin. Only one's by DHH. However, if you google it a little bit, you'll find that the one by DHH was really only intended as demo code for polymorphic associations. 37 Signals initially used it in Highline and then threw it away because it was too big to be useful. Koz from Rails core has stated in a forum that it shouldn't be used in production code at all - and yet it's the de facto standard for tagging in the Rails community. Maybe due to hero worship, maybe due to tangled lines of communication, but it's out there in production code all over the place, and it shouldn't be.

Anyway, I haven't played with this new, improved alternative yet, but I think it's definitely worth a close look if you need tagging for your Rails app. Check it out here.

Tuesday, August 21, 2007

ActiveResource Monkey-Patch: Create ARes Models From Vanilla Gets

I don't buy the REST dogma. I don't know why not, it just doesn't fly with me. However, many times when I've decided DHH was wrong, he's turned out to be right. So it's entirely possible he could turn out to be right here as well.

However, in the meantime, between now and the moment when I see the light, I've got a lot to do, and sometimes the steps you have to take to make your Rails apps conform to "pure" REST feel like a serious waste of time to me. There are some times when you just want to be able to call a get() on an ARes model as if it was a find(). Assuming you're hitting an API which sends ActiveRecord models back using to_xml, all you have to do to enable that is break the privacy on instantiate_collection.

You then call it like this:

Model.build_from_hash(Model.get(:method_name))

Caveats! I've just started hacking with ActiveResource, and I haven't started drinking the REST Kool-Aid. I'm probably doing it wrong. But it gets the job done.



Also, you can still run into trouble on included objects from association classes.

Update: I'm totally doing it wrong. My build_from_hash method takes an array. Please consider this post nothing more than notes on a work in progress.

Update 2: here's a substantially less dumb version. Needs refactoring though - the code is pretty heinous. It's mostly based on working around Rails' assumptions, when it should be working with them. However, the cool thing is that this version is almost entirely portable for plural association classes. That being said, it's currently only useful for plural classes. The exception to "entirely portable" is the ActiveResource get, which needs to be a find(:include) (which is coming).

Monday, August 20, 2007

Random Gratuitous Images Are Awesome

Jeff Atwood's blog is one of the best out there. But he says you don't need random gratuitous images, and they're actively counterproductive. I absolutely disagree.



Jeff's a smart guy, but he also uses Windows. You can respect his intelligence and still disagree with his conclusions from time to time.



First of all, what random images do in a blog is the same thing "random" facial expressions and gestures do in a conversation - they contextualize what the person is saying.



Context matters. Context matters immensely.



The idea that technical materials should be dry and devoid of personality is old-school bullshit.



Read up on Kathy Sierra's Head First series and you'll discover that actively engaging the part of the brain which recognizes facial expressions is the easiest and most powerful way to accelerate learning.



Do you want to learn fast? I do.

Sunday, August 19, 2007

Evil Rails Console Gotcha: reload!

Rails' console has a great feature: reload!. Introduced in Rails 1.1, it allows you to update your console's Rails app with any changes you've made on the filesystem.

However, if you create an object, like an ActiveRecord model, and then return to your Rails console to type reload!, it'll only reload the code. It won't reinstantiate any existing objects. And because of the dynamic way that methods get attached to ActiveRecord models, the instantiation process is an important step. So you can make a change in an ActiveRecord model, switch back to the console, hit reload!, and get nothing new at all.

It's probably possible to write some Ruby which queries ObjectSpace for ActiveRecord models, loads their attributes off into a hash, and then reinstantiates them - but making something like that portable could take some serious wizardry. I leave it as an exercise for the reader who is smarter than me. It's a lot easier to just remember, after you hit reload!, you may in some cases have to reinstantiate some of your objects.

It's not perfect, but it still beats starting over entirely from scratch.

Saturday, August 18, 2007

Three Foibles in Rails' MVC

There are three things I've run into which are kind of nagging at me in Rails, three flaws in the logical purity of Rails' MVC implementation.

1. The Presenter pattern
2. Ajax MVC
3. ActiveResource model/controller confusion

Presenters

Presenters are pretty much necessary in Rails apps of a certain level of complexity, and that level doesn't even necessarily have to be very high. I'm using a presenter in an app I'm working on now. I created a Struct, added HTML-generating methods to it, and got a ton of flexibility that I really would have had to otherwise use Seaside to get. But it's living in the /models dir, when it should really be under /presenters - or possibly /components, if /components wasn't already used for something else - and to bring it under test, I had to manually load its "fixtures" from the YAML file directly, since Rails' fixtures assume your fixture objects are ActiveRecord objects. (This raises questions about unit testing ActiveResource models, but that's a whole 'nother ball of wax.)

Ajax

MVC was originally created to handle GUIs. A sufficiently complex Ajax GUI justifies MVC, even if it's just a tiny implementation. Sometimes a nanoframework is better than a framework; design patterns don't have to be complicated in their implementation to be useful. They just have to be clean and powerful. But I had one project which not only justified an Ajax MVC implementation in JavaScript, in addition to the back-end Web MVC implementation in Rails, it also absolutely needed an ActionScript MVC implementation as well, to support a complex set of options in a Flash component of the UI, which needed to interact both with the browser's Ajax and DOM, and with Rails. Coordinating two distinct simultaneous MVC implementations challenges you; coordinating three gets really hard.

ActiveResource

Concerning ActiveResource, you define all your API methods in the controller, not the model. But insofar as ActiveResource seems like a networked version of ActiveRecord, putting the definition for something like Widget.get(:stuff) in the controller instead of on the model really breaks my habits and assumptions. I know it matches official REST dogma, but personally, it drives me fucking nuts. It just seems so counter-intuitive. I don't know if other developers expect to be able to simply substitute ActiveResource for ActiveRecord without thinking about it any further than that. That's certainly what I want to do, but maybe that's just me. Certainly Rails is still a long way from enabling that, and may never go in that direction, but from the standpoint of ease of development and simplicity of migration, it would be really cool if it did.

So what?

Obviously, the goal of Rails isn't to reflect the magical purity of a holy logical thought-form. The goal of Rails is to get stuff done. But the clarity of its original MVC model is a big part of its success and its elegance.

Even given the powerful personality of its chief kahuna, Rails is a community project, and the community's both huge and enthusiastic. Rails' adoption curve is crazy. As people are using Rails in all kinds of contexts beyond the one it was originally designed for, it's taking on all kinds of alternative dimensions. The bigger and more ambitious Rails gets, the more valuable its simplicity and elegance will become. That's the whole point of elegance: you reduce unmanageably complex detail to a few simple ideas.

Anyway, these are really just some things bugging me slightly, things you might have to work around in certain situations, potential pitfalls and gratuitous gotchas of the most abstract, theoretical kind.

My bash Profile

Here it is (with some client-relevant stuff deleted).

Far and away the handiest customizations are the short question-mark aliases for history | grep and ps ax | grep.

Update: here's a Pastie where I use both the ? aliases. I try to start Mongrel, but it won't start. I can't remember if I left it running, so I do a ps? mongrel and find out no, it's not running. Then I do a ? mongrel to see what I've done with Mongrel recently.

Obviously this is easy stuff, but compacting it down makes it really quick and fun to use. Also, since it becomes a habit to just hit ? when you want the system to tell you something - which is very intuitive - you have that option even in situations when you're tired from overwork and wouldn't naturally remember something that clever. It kind of turns the clever part invisible.

Friday, August 17, 2007

One-Line Code Snippets Allow You To Avoid Useless Knowledge

Why the Lucky Stiff made an interesting post about the value of code one-liners in learning a new language. I'd take it one step further, and add that one-liners and similar tiny snippets are valuable because they allow you to skip learning parts of a language.

At one company where I worked many years ago, everybody referred to me as a Perl guru. The irony was, I also got a personal e-mail at the same time from Rex Swain, the guy who maintained the Perl 5 reference page, asking me to stop leaning on it so much. I was loading the page so frequently that I was individually responsible for some huge percentage of his monthly bandwidth bill. Of course I saved a local copy to my desktop - and of course Rex today has Google ads on the page - but the lesson is that people were calling me a guru, and yet I went to reference material so frequently that I single-handedly constituted a bandwidth issue for the reference maintainer.

I wasn't really a guru, but I was good enough at Perl to believe it when people said it about me, and obviously good enough that they had a reason to say it in the first place. (It also helped that I was young and hadn't yet encountered any real gurus.)

But it isn't necessarily a paradox. It demonstrates the foolishness of job interviews which test on language syntax; I made all my business users very happy, much happier than they'd expected to be, and never even bothered to remember many core elements of the language. I checked the reference page twenty times a day for the same tidbit because it was never worth memorizing - or even remembering at all.

I made my business users happier than they'd expected to be because I redefined the problem I was working on, and the way you do that is you choose the right issues to think about. Language syntax is not a useful issue to think about. Except for language designers, anybody who puts a lot of energy into remembering language syntax is an idiot. That's what Google is for.

The valuable thing to learn when you learn a programming language is the set of core principles behind it. It's much more valuable to be able to discern idiomatic Ruby vs. Ruby that looks like PHP than it is to know a given method name off the top of your head, for exactly the same reason that programmer discipline is more valuable than a version control repository. The productivity boosts associated with using excellent languages come from the good programming habits which good languages encourage, and they have nothing to do with rote memorization. One-liners are useful in this context because a good one-liner compresses syntax down to idiom, and favors idiom over syntax.

Think about it another way: would you learn more about Perl by memorizing its keywords, or playing Perl golf? Memorizing keywords in a programming language is like memorizing vocabulary in a spoken language; it's only useful if the language uses exactly the same grammatical structures as a language you already speak fluently. But the act of compressing code into a one-liner is like the act of creating slang, and if you understand how slang comes into being, you understand how to make new words.

Wednesday, August 15, 2007

Ruby East Conference Registration Open

Registration's now open for the Ruby East conference in Philadelphia on September 28th. This is a one-day event. I'll be speaking, as will David Black, Amy Hoy, Ezra Zygmuntowicz, Obie Fernandez, Hal Fulton, Desi McAdam, Jeremy McAnally, and others.

I've never been to Philadelphia before, so it should be lots of fun.

New Blog: Eye Heart Los Angeles

Photos of the city of Angels. LA looks different than you'd expect, or at least, when I first came here, I was very surprised. I thought I'd hate it, but I love it. Everyone's seen movies and TV shot in LA. The real Los Angeles looks quite different.

Without further ado:

http://eyeheartlosangeles.blogspot.com/

By the way, if you're a graphic designer, contact me, I have need of your services. :-)

Saturday, August 11, 2007

JRuby and Rubinius Under Gemstone

Neat news from InfoQ. I got to visit Gemstone when I was in Portland for OSCON. Long story short, if you want object databases for your Rails apps, it'll be easy very soon. This is vitally necessary for complex problem spaces such as international shipping and warehousing.

It may also represent a much better model for Web application persistence in general. I've blogged about this, Evan Weaver spoke about it at RailsConf 07, and DHH once commented also that he doesn't like databases and essentially uses them as hashes. It's entirely possible that the OODB model could be much better.

Friday, August 10, 2007

Haskell Video: Simon Peyton-Jones' Tutorial at OSCON

I was lucky enough to attend this. It was great. Simon Peyton-Jones is one of the best presenters I've ever seen, and I think it's just because he's just really into what he talks about. I haven't watched the footage itself, but given what I remember of the actual event in real life, it should be very entertaining and informative.

Friday, August 3, 2007

Giving A Talk @ Ruby East

w00t! Just got the word that I'll be giving a talk at Ruby East in Philadelphia called "How To Kick Ass With IRB." Should be lots of fun.

Thursday, August 2, 2007

Have I Become A Micropundit?

I get a lot of mileage out of my blog. Free food, free beer, speaking at conferences, invitations to contribute to books - the freebies rock. You might not be able to make much money blogging, but you can definitely get a lot of mileage out of it.

But in the wake of Jeff Atwood's recent post about punditry on the Web, I have to wonder - have I become a micropundit?

I think I have.

The shame! Oh how the mighty have fallen! Once so proud, so filled with hope and dreams and vigor - and now, today, a micropundit. My grandfather would be so ashamed to hear it, or at least, he might be ashamed to hear it, if he had any fucking idea what it meant. But yes. A micropundit. That is me.

I have opinions, cleverly phrased, concerning an incredibly narrow range of topics. I have a tiny crowd of fans, foes, friends, and people who remember me because they heard me talking. You could simplify it and call me a blogger, but that doesn't quite cut it. A blogger doesn't necessarily have readers, and if he or she does, their blog might still have useful content. We don't mess around with that stuff round here! Not in these parts. This here's micropundit country. No content, only opinions. We got an opinion about Rails, an opinion about Seaside, and over there in the corner, a rusty kind of thing that was once an opinion about Python. We had an opinion about Lisp in the back of the store, but that opinion done ran away and joined the circus. Yee haw!



Always be sure to get enough sleep before posting in your blog.