dagfinn | 07 November, 2008 20:34
I got some interesting comments to my previous post on "beautiful code". Some were pretty strong disagreements.
So am I wrong? Did I get carried away? Did my critical faculty go on vacation somewhere nice and sunny? I admit that sometimes I deliberately look at the positive and ignore the negative. (And sometimes I do the opposite; It's a good exercise if you're careful.)
I wasn't drunk, anyway. But let me take a closer look at the particular line of code I was praising:
$this->assertThat($form->hasSelect(withName('statusConfirm'))->hasValues(), array('Yes','No'));
My main point is that it's close to plain English. Not everyone agrees that that's a good thing, but I argue that we're built (genetically wired, in fact) to understand natural languages, not program code. Therefore code should be easier to understand when it approximates natural language and expression. And we're trying to create or approximate a Domain Specific Language (DSL), which should express exactly what's required for the domain and not the demands of the technical implementation.
So for this experiment, let's translate this one into a (plain English sentence:
Assert that Form (this particular one) has a select menu with the name "statusConfirm" and values "yes" and "no"
Translating back into code, it might look more like this:
$this->assertThat($form)->hasSelect()->withName('statusConfirm')->andValues('yes','no');
To me, this is even more natural than the other one. I think we've gotten rid of some syntax that has to do with implementation details rather than making the API simple to use.
It also seems clear to me how this could be implemented. All of the method calls could be to an assertion object that would take all these various inputs and always return itself at the end of the method so you can chain the calls in what's known as a fluent interface.
| « | November 2008 | » | ||||
|---|---|---|---|---|---|---|
| Su | Mo | Tu | We | Th | Fr | Sa |
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 | ||||||