Saturday, January 05, 2008

Reflection on Everything

Smalltalk allows you to reflect on everything. You can not reflect on objects to find their instance variables and methods. But, you can also reflect on code running and on the stack. It's powerful stuff. Why would you need this extra power? You might be a lazy developer. You might constantly remind yourself, "I work in a dynamic language and it should work for me!" Let's go digging shall we?

One thing you have to be careful in dynamic languages are message not understood or method missing errors. One easy mistake to make is to do the following:
[someObject doSomething] 
on: MessageNotUnderstood
do: [:ex |
"log something"
^self]

What's wrong with the above code? Well, are you trying to catch if doSomething is not understood by someObject? If so, the call can still succeed and there could be a nasty bug further down in the code. The handler will be giving misinformation on the true problem. Frustrating to say the least. It's better to do something like this:
[someObject doSomething]
on: MessageNotUnderstood
do: [:ex |
(ex message selector == #doSomething and: [ex receiver == someObject])
ifTrue: ["log"
^self]
ifFalse: [ex pass]]

Yuck. But, it does check the receiver and selector to make sure we captured the right exception. Lots of typing for something simple. Granted you shouldn't be doing a lot of guarding against MessageNotUnderstoods (polymorphism anyone?). But, sometimes it is necessary. Besides, we wouldn't have this fun little blog post would we. Basically, the above method checks for the right selector and receiver that we expected to have a MessageNotUnderstood and if it did we do our logging code. If not, it's something we didn't account for and is a bug, thus we "pass" the exception to the next handler. But, how can we prevent ourselves from all of this typing?

Squeak has this method implemented:
BlockConext>>onDNU: selector do: handleBlock
"Catch MessageNotUnderstood exceptions but only those of the given selector (DNU stands for doesNotUnderstand:)"

^ self on: MessageNotUnderstood do: [:exception |
exception message selector = selector
ifTrue: [handleBlock valueWithPossibleArgs: {exception}]
ifFalse: [exception pass]
]

It does not check the receiver, but that's OK. It turns our code into this:
[someObject doSomething] onDNU: #doSomething do: ["log something" ^self]

Nice. It's much more succinct, but I don't like the duplication of "doSomething". What are we to do? I came up with this method:
BlockConext>>onImmediateNotUnderstoodDo: anExceptionBlock 
^ self
on: MessageNotUnderstood
do: [:problem |
| myContext problemContext |
myContext := thisContext home.
problemContext := problem signalerContext sender sender sender.
(problemContext == myContext
and: [self method messages includes: problem message selector])
ifTrue: [anExceptionBlock
valueWithPossibleArgs: (Array with: problem)]
ifFalse: [problem pass]]

Here's what it makes our code look like now:
[anObject doSomething] onImmediateNotUnderstoodDo: ["log something" ^self]

It looks like what we started with, but this version is safe. It will pass the MessageNotUnderstood exception if the send did not happen directly from the block we defined.

What is the method above doing? The method I wrote reflects on the stack and the compiled code. I use the stack to find the receiver that should be in the block. The compiled code is needed to find all of the selectors that are called directly from the block. Pretty cool, huh?

Smalltalk is one of the few languages where you can reflect on everything on the stack. Stack frames are objects too. It makes doing difficult things possible.

Favorites of 2007

1. No World For Tomorrow - Coheed and Cambria
More hooks and punches than a lightweight boxing match make this my favorite of the year. I simply can not get enough of this band. The groove, vocals, harmonies, and everything is perfection. Roll down the windows and sing loudly.

2. Act II - The Dear Hunter
I loved the previous disc and this one continues down that path. Clever lyrics with instrumentation that puts me in an 1800's brothel. Indie rock with unique instrumentation. This band has its own identity. I can't wait to hear more.

3. From Beale St. To Oblivion - Clutch
One of my favorite rock bands. The go-go influence takes a bit of backseat in this one, but they still rock and roll better than anyone. Their groove is just unbeatable. These guys should be in the upper ranks with rock's other elite. Not a disappointment yet with their enjoyable old school rock with funk, blues, and hardcore blended in the right doses. This is unpretentious rock that is catchy, fun, and smart.

4. Strum Sum Up - Dug Pinnick
I loved the last King's X and have always enjoyed Doug's output. He is one of my favorite vocalists of all time. But, nothing set me up for this. Wow. Doug takes all of his influences and gives us a ride through them all without losing sight of hooks or groove. Doug proves he is a jack of all trades and gives me an album that makes me want to hit repeat.

5. Killing Peace - Onslaught
OK, I wasn't a big fan of their 80's output until Steve Grimmitt sang for them. I wasn't expecting much out of this at all, but thought what the hell. It was getting good reviews and who can't live without another thrash record right? This blew me away. In a day when retro-thrash bands are a dime a dozen, it takes the old guys to show them how to do it with PASSION. Sure, the lyrics are cheesy, but when sung with such conviction. It reminds me of the good ole days.

6. Rhythms From a Cosmic Sky - Earthless
I got this late and this is simply great space rock. It ebbs and flows yet never bores. 70's rock that takes you on a journey that you never want to end. It's only 3 songs clocking in other 45 minutes. Turn it up.

7. Ocean's Thirteen Soundtrack - David Holmes
I love all of the Ocean's movies. Sure, they've gone down in quality ever since the first one, but the one constant has been the great soundtracks for each of them. I think this is the best of the soundtracks though. It adds something special to the ambience of the movie. Creative sampling make this just a jaw dropping electronic music experience. None of the spices overbear the others.

8. Tervaskanto - Korpiklaani
I've never been big into folk metal because most of it has been depressing. Not this band. Accordians and violins mixed with heavy metal guitars makes for a rollicking good time. The songs are catchy and fun to drink a pint to. Upbeat and always puts me in a good mood. One of my favorite finds for this year.

9. "V" is for Vagina - Puscifer
Tool's singer tries to pull a Mike Patton and do his own Peeping Tom. Silly, catchy as all hell, and different. I like it. It's not exactly like Peeping Tom, but the mood is similiar. Pop music with electronic flourishes and Maynard's distinctive croon over it. A lot of people hated this, but I think it was because they were expecting Tool. Tool this is not. It's dark pop with lyrics that make you chuckle. It's refreshing to finally hear a side project from a member of a band that sounds nothing like their main band. Kudos for taking a risk and doing something different.

10. Hangman's Hymn - Sigh
Eccentric. I've loved Sigh for a long time and they never seem to suprise me even though I know what I'm getting into with each album. Everything but the kitchen sink instrumentation, but this time the songs flow. It's not as much of a bumpy ride as before and that's a good thing.

11. Mythmaker - Skinny Puppy
This is the second album since their return and they are a different beast now. The songs are now melodic and catchy. It's dark pop electronic music. It's nothing like the bleakness of their previous output and that's OK. I love this version of the Pup too. They did incorporate a little bit of their darkness from "Last Rights" and it made me smile. Still the best industrial band in the world.

12. Cortical Tectonics - Canvas Solaris
Instrumental progressive metal that has to be heard to be believed. They keep things moving along and never have a boring moment. A musical maze that excites and breathes. They even manage to keep things from sounding too much a like. One fun ride.

13. In These Veins - Hearse
Surprise of the year for me right here. Melodic death metal with Johan Liiva (former singer of Arch Enemy). The songs are all memorable with a few twists and turns to keep things fresh. Melodic death metal has been getting stale for a while. Arsis was the last to breath new life into it. Hearse is the next. No other melodic death metal release came close to this.

14. Fear of a Blank Planet - Porcupine Tree
Another album that I'm shocked more people didn't love. I'll admit I've always like Tree's previous output, but this one just clicked with me. Maybe it was time, because I have revisted their previous output and now love it. The laidback prog with a little kick of metal and melodic vocals just get me.

15. The Mix-Up - Beastie Boys
I'm a sucker for lounge and electronic music. I'll admit that I hate the Beastie Boys' rap output (not because I hate rap, I hate the whiny rap vocals). I picked this up because I've always loved the music, but thought the nasally rapping killed otherwise cool songs. So, I figured I would get some cool instrumental dance music with heavy beats. What I got was a through back to the 60's. This is lounge music with light electronic flourishes. This is the stuff to sip martinis to and relax.

16. Open Fire - Alabama Thunderpussy
Kyle Thomas is one of my favorite vocalists and I was so pumped when I found out that he would be in front of Thunderpussy. This is turn the amps to 11 and forget the neighbors. Unpretentious and loud rock with heart and soul. This is the way metal used to be in the 70's and early 80's. Thunderpussy reminds us how good those times were. A time where a good song was the most important thing.

17. City of Echoes - Pelican
This was a love or hate album apparently. Instrumental rock that took me on a great journey. I need to check this band's previous output. This was the year for great instrumental albums. I would love to hear this album played live. If you're bored with paint by the numbers rock, then you need this.

18. The Machinations of Dementia - Blotted Science
Instrumental progressive death metal that knows not to bludgeon you all of the time. Heavy one moment, somber the next, and then all out wackiness. But, again, never going into wanking territory and keeping the melody in mind at all times.

19. Foley Room - Amon Tobin
Dark electronic music with loads of samples. Amon Tobin is one of my favorite electronic artists with inventive sampling that sets a tone. This one is a bit more ambient and darker than previous releases, but just as good. No one has been able to touch Amon yet.

20. Hardworlder - Slough Feg
Do you love 70's/early 80's metal? You know before hair spray and image took over the music? Back when bands had their own sound and were'nt cut from the same cloth. Slough Feg takes us back to that time. They have their own sound that calls back to that era, but you will be hard pressed to say they are a retro-band. A great set of songs that I can't stop listening to!

Thursday, January 03, 2008

Omaha Dynamic Language User's Group

Fingers tired from typing in all of those Emacs commands from trying out new Ruby and Lisp code from the books you got for Christmas? Why don't you take a small break and join your fellow comrades. Trust me your mind and fingers will thank you. This month we have a very special guest from Microsoft, Bob McCoy. He'll be demonstrating all of the cool things that you can do with PowerShell. It just might make Mac users envious. Here's the full abstract:
PowerShell is Microsoft’s next generation scripting language and environment. It will be the native shell environment for Windows Server 2008 and is at the heart of every administration task in Exchange 2007. It is extremely powerful and at the same time very simple to use. It is aimed at system administrators and scripters.

This will be about 40% slides and about 60% demonstration. I try to keep it highly interactive so it ends up answering a lot of questions along the way.

But, that's not all! You not only get Bob McCoy, but we're also bringing the brightest fellows in Omaha. But, wait that's not all! We'll throw in sponsorship from TekSystems which means free food and more pop than you can drink. All for the incredible low price of FREE! Why delay? Come to the meeting!

On a side note, a little bird told me that TekSystems has some Ruby openings right now! Get in contact with Heather Blockovich or better yet come to the meeting to find out more.





TopicPowerShell
SpeakerBob McCoy
TimeJanuary 8, 7-9pm
LocationUNO's Peter Kiewit Institute (PKI) building
1110 South 67th Street
Omaha, NE

Sunday, December 02, 2007

Omaha Dynamic Language User's Group

Still eating leftovers from Thanksgiving? Had your fill of Christmas shopping? Sounds like you need a break. Why not head on down to the local Omaha Dynamic Language User's Group and meeting the best and brightest that Omaha has to offer? This month we are honored to have world famous "No Fluff" wowie zowie speaker, Matt Secoske presenting. He will be showing us the ins and outs of a framework called "Processing". It's a graphical canvas with a programming interface. Simple to use and the results are jaw dropping. Spice up your Christmas cards this year.

There will be pizza and drinks provided. Free food, drink, great conversation, an exciting presentation, and an amazing new technique to make cards. What do you have to lose? Christmas shopping can wait. It's time to have some fun.





TopicProcessing: Cool Graphics Now
SpeakerMatt Secoske
TimeDecember 4, 7-9pm
LocationUNO's Peter Kiewit Institute (PKI) building
1110 South 67th Street
Omaha, NE

Wednesday, November 28, 2007

Some Metrics






LanguageAvg Methods/ClassMax Methods/ClassAvg Params/MethodMax Params/MethodAvg Fields/ClassMax Fields/Class
Squeak9.397800.64161.02100
Ruby12.696830.4270.7631
Java8.671810.91122.42343

I ran the metrics, that I talked about in my last post, in three environments and the results are above. Nothing really shocking, but the maxes did surprise me. I was mainly interested in the averages and the maxes were there just to see how huge the big boys really are.

I wonder what developers would think of a language that restricted the number of things that they could define. What if by looking at the numbers of above, I designed a language that didn't allow more than 256 methods/class, 8 parameters/method, and 16 fields/class. It would force the developer to write smaller entities, but would it annoy more than help?

Where I'm going with this is simply, what if the language enforced certain hard restrictions instead of allowing any incredibly large number of possibilties? If elements were kept to a certain size, would it make programming in the system more pleasurable since it would be difficult to create a god object? Objects would not get out of hand before refactoring thus making maintenance easier.

My gut instinct is that constraints would annoy and ugly code would still live. Developers would just figure out ways around them. I would love to think that by adding constraints, we could get better code. But, no matter what you measure quality by, there will be developers that will figure out how to get around it. Pessimistic, I know. But, it's simply human nature.

Still, I wouldn't mind if the language did have some limits, so that individual items stayed small. If the constraints were not dogmatic, it would make the need to get around them less attractive. Of course, with smaller things comes naming them and that would still be a problem. But, that's a problem with mammoth sized objects as well. I'll keep thinking on this. There's got to be a way to have flexibility to dream the impossible and yet gently nudge us into more maintainable programs at the same time. The problem with balls of glue is that slowly become that way. It would be nice to not allow them to become Godzilla.

Tuesday, November 27, 2007

Limitations Of The JVM


  • The maximum number of local variables in a method is limited to 65,535.

  • The maximum number of fields in a class or interface is limited to 65,535.

  • The maximum number of methods in a class or interface is limited to 65,535.

  • The maximum number of direct superinterfaces of a class or interface is limited to 65,535.

  • The maximum number of method parameters is limited to 255.


What's the point of the list above? Sure, those numbers are reduced by various factors (like this reduces the number of method parameters by 1). But, that is not the point, my friends. The point is all of the above numbers are HUGE! I was reading my trusty copy of "The Java Virtual Machine Specification Second Edition" when I got to Section 4.10 and read some of the above bullet points. In Java, I live in the land of the plenty.

I know it's all two byte boundaries and all, but what if they left some of these at one byte or 4 bits? I can hear it now: "But, we have all the space in the world! Why constrain ourselves in such a way!" True. But, when was the last time you looked at a method with 80 parameters and thought: "DAMN! Now, that's some beautiful code." Exactly. You never have and you never will. The point is not to constrain on a byte boundary, but on a good coding boundary.

Arbitrary numbers are awful to use as metrics (like you must have less than 3 arguments to each method and so on). Metrics are useful in relation to something else. You pick what seems reasonable to you (which might not be reasonable for someone else). There is a boundary where any reasonable programmer starts to hurl at bad code though. Metrics are set below that for each team. I hope I never see the interface with 16,000 superinterfaces. I really do. The cool thing is we have a huge library in Java to look at to see what is reasonable. We have tons of open source projects to feed our reason as well. What if...What if we picked what was reasonable from these code bases by using averages and everything else in our numerical power? Then, we doubled it to make it unreasonable. I wonder what the numbers would look like?

My next experiment is to run some code reflecting over both Java, Ruby, and Smalltalk code. I wonder what the averages for each would be (number of method parameters, number of methods per class, number of fields, and number of local variables). I'm curious. I have a guess at what the numbers will be. But, the raw numbers could be telling. I would like to see them for all three of the above languages. It should be interesting. I know there's probably someone out there that has done the same thing, but I want to run the tests on my own. For now, I will do it with the base libraries of all three. My guess is that they will be roughly around the same for each of the metrics that are comparable in each of the languages.

What's the point? By reading and then thinking of the worst, it got me thinking. Our languages constrain us in ways that they shouldn't, but don't in what would make our code better. Would it be such a bad thing having to split a method up because you ran over a rather large (let's say 256) number of local variables? I want to find the number where it seems unreasonable and grotesque and make that my limit. I know 65,535 is absurd for the number of local variables, but so is 256. What about 16? My answer is "HELL YES IT IS!", but there are those that would argue that sometime you need that many. 16 is not hideous, but is still in poor taste.

I'm off to see the wizard. I'll let you know what he says.

Sunday, November 11, 2007

A Happy Diversion

I was smitten with my quick snippet of code for my Monticello window in a flap. As with all little things in Squeak, it's hard to just stop. You're always thinking of little things or tools that would be nice. Everything in Squeak is easily explorable and changeable. It's too much fun to search and see the results of your labor instantly. Addictions are not pretty.

Another idea came to me. The tab for my Monticello flap was boringly called "Monticello". What a waste of real estate. My second problem was that I'm always getting confused at which project I'm in. I normally use different background colors to make it easy. But, I still get confused. I was blessed with a small brain. I curse it everyday. What is a poor little Squeaker to do? I thought I could put the name of the current project on the Monticello tab instead of the one it has. I wondered how hard would that be? And off I went...

How can I do that? I could change the tab name when the project changes. Eureka! That's what I will do. I remembered I wrote a little utility to change background images and I had to know when the current project changed. I started my hunt there and event handlers are available via the morphic world to know when a project is entered or exited. We only care about when a world is left. Why? The event handlers has to be registered on the world itself and we don't want to have to keep track of every project and world. It's easier to put a handler on the current project and know when it is left.

Let's start with this method for setting the world we're currently in:
world: aMorph 
world == aMorph ifTrue: [^ self].
world ifNotNil: [world removeActionsWithReceiver: self].
world := aMorph.
world ifNotNil:
[self changeTextOnTab.
world
when: #aboutToLeaveWorld
send: #leavingWorld
to: self]

Basically, this method removes all events from the old world since we will not care about it any longer. Then, we change the text on our tab and add our event handler. Next, how do we change the text on the tab? In the menu for a tab, is an item to change the name of the tab. Using the handy morphic handles, I inspect the menu item itself and find the method it will call when it is invoked. Here's the code I came up with:
changeTextOnTab
self monticelloFlapTab ifNotNilDo: [:tab | tab changeTabText: Project current name]

The simple method changeTabText: does all of the magic. We just get the name of the current project. I haven't showed you how to get the tab itself. I look through the methods on the class side of Flaps to reveal its magic:
monticelloFlapTab

^Flaps globalFlapTab: 'Monticello'

The good news is that it will always find the flap this way no matter the name. The only thing left is to what to do during the handling of leaving the current world. The dilemma now is how do we know the next world? Some more digging and we can be ask ed to be called later. Perfect. Here's the code for the handler:
leavingWorld
WorldState addDeferredUIMessage: [self world: Project current world]

And that's it! The same method can be called to seed our initial world as well. Now, a quick glimpse to the bottom of the screen gives my project name. Easy. Now, I can get back to updating my Seaside presentation.

Why I Love Squeak


addMonticelloFlap
| newTab monticelloBrowser |
newTab := Flaps newFlapTitled: 'Monticello' onEdge: #bottom.
self currentWorld addMorphFront: newTab.
newTab adaptToWorld: self currentWorld.
Flaps addGlobalFlap: newTab.
newTab showFlap.
monticelloBrowser := MCWorkingCopyBrowser new.
(monticelloBrowser window)
openInWorld: newTab referent extent: monticelloBrowser defaultExtent;
topLeft: newTab referent topLeft + (10 @ 10).
newTab referent height: monticelloBrowser window height + 20.
newTab hideFlap

The above code snippet adds a new global flap to the Squeak environment. Inside the flap is the Monticello browser. I've been doing this in my Squeak images for a long time, but doing the above by hand for each image. I went into the system and figured out what each of the menu items did to create the above. This is simple in Squeak because everything in Morphic is inspectable. It allowed me to create the script you see.

The reason for having a Monticello browser in a global flap is so that you can always have it open in every project and easily accessible. I like to have a Squeak project for everything I do and like having one Monticello browser.

The above was not much effort and took little time to figure out. Love is.

Saturday, November 10, 2007

Seaside Presentation

I updated my Seaside Presentation available on SqueakMap to Seaside version 2.8. Make sure you update your SqueakMap. The new version is 1.70. I plan on reworking it completely soon. As I upgraded the code, I was unhappy with what I saw. It needs to be refactored heavily. I want to add more code that shows off the cool new add-ons for Seaside as well. Enjoy!

Thursday, November 08, 2007

Bug Finder

Two of my favorite tools to use in coding are: a code checker and a code beautifier. The first points to sloppy and rushed code. I find sloppy code to be a vital protein for bugs to grow. The second shows me a consistent view of the code. It's amazing how many bugs you can pick out by just running a code beautifier and glancing over the code. I'm always amazed what I find with a code beautifier. What's even more shocking to me is that a lot of developers hate them. Even if the formatting is less than to my liking, I still use it. Why? It catches so many moments of unclarity. It also points to code that should be broken up into smaller bits. If the code beautifier formats my code to be ugly, then I need to refactor. It's a rule of thumb that has served me well.

Of course, I usually run the code beautifier to get a lay of the land on new code and roll back when I'm done. Why? There's nothing more annoying than searching through tons of code changes to find out that the code was only reformatted. Now, if it's my code, I don't check it in until a code beautifier has been ran on it. I find studying my code after running it is just a good habit to get into before check-in. Reading code that's normalized makes it easier to spot patterns of inelegance.

I'll write more about the code checker, also known as Lint in some circles, in another post.

Friday, November 02, 2007

Omaha Dynamic Language Group

You wanted the best. You got the best. The hottest presenter in the land...Ben Heath! What could be better than a Kiss concert, a talk on PHP of course. This month Ben has offered to show us what we have been missing in PHP. The language itself is loved by web programmers all over. If you have ever been curious, now's the time to find what the fuss about PHP is all about.

ProKarma is sponsoring this presentation. They will be providing the food and drinks. So, what do you have to lose? You get to learn something new, hang with the smartest people in Omaha, and free food. My friends, it just doesn't get any better!






TopicPHP: Practical Web Programming
SpeakerBen Heath
TimeNovember 6, 7-9pm
LocationUNO's Peter Kiewit Institute (PKI) building
1110 South 67th Street
Omaha, NE

Tuesday, October 23, 2007

Bloat

John C. Dvorak asks the following in his latest blog entry:
But I wonder if all open-source projects will eventually go the way of all software. Upgrade after upgrade adds more and more complexity, to the point where the software begins to get bogged down under its own weight. How many open-source projects have you seen in which the code gets leaner and meaner rather than fatter and fatter?

Good question. Software becoming more complicated and bigger is almost a universal truth. I don't see why open-source should be immune. Of course, the more features you add, the bigger your program will become. But, even software that is being maintained becomes an entangled network of goo. Brian Foote even wrote an anti-pattern about it called "Big Ball of Mud".

This is the problem that needs to be solved. I see a huge focus on creating tools that allow quick creation of code. But, I see few dealing with complexity of existing code and even dismissal of the ones that do exist. Refactoring tools are mandatory in the fight against creeping code. Tools that allow diagnosis of live running systems is a must. Code generation gets my code out the gate quicker, but without a gym, it becomes slow as molasses as the race continues down the path of new features.

I want to create systems that in their evolutionary cycle grow consistently with new features. The complexity should be in line with features. Right now, this becomes exponential and is proven by ever rising maintainance costs. Our current weapons are refactoring tools, code checkers (lint), metrics, debuggers, and let's not forget the most important: education. Actually, could that be the answer? Discipline and education just don't have the same kind of sexy ring to them, but tools can only take you so far. Still anything that can help our brains reel in the complexity is a welcome addition. Software is only going to get more complex as we go along. I think we spend so little time on reducing complexity in existing code because the feedback is not immediate. I want to get to the point where I can deliver the third version as fast I delivered the first.

It's a shame with all of the advances in our field that we have been unable to keep maintainance costs down. There are developers working on this problem. I've heard rumblings that tools are in the works. One possibly being a more macro level refactorer. I can't wait to use it. Until then, I'll keep my lint, refactorer, inspector, debugger, and metric runner close by my side. If anyone has any other tools that they like to use to keep complexity down, I would love to hear it. My brain can always use help.

I'll end with this all too true quote on Firefox in the same article as mentioned above:
Just look at Firefox, one of the poster children for open source. It loads more slowly than ever. It will be on some page within a tab, and that page will be refreshing ads or something in the background, and Firefox just hangs all its cycles there, slowing down the whole computer. Every couple of days the browser is hogging cycles, and I have to go to the Task Manager and kill it. Other people have this problem, too.

Go read the rest of the article. He makes some good points on mindless fans of technologies. Sadly, I think open-source is going to be the place where the tools to deal with complexity will be born. Until then, open-source will suffer the same as the rest of us with bloat.

Monday, October 22, 2007

"Considered Harmful" Considered Harmful

It's official. "Considered harmful" can be added to list of cliches to avoid. It needs to go into retirement along with factorial and prime examples.

Thursday, October 18, 2007

Debuggers...again

Giles Bowkett recently asserted: Debugger support considered harmful. It seems this has been going around for years. See this old post of mine: Am I a Bad Programmer?. Nothing new. The assertion is that if you have tests, you don't need a debugger. Interesting. I'm heavy into testing my code. Anything I write even for fun has a test to go with it. And yet, I still use my debugger quite a bit.

Why? Well, it depends on what I'm doing. I use the debugger for exploratory programming, when sinking into the depths of someone else's code (especially if they didn't write tests), during code reviews, and when faced with a nasty bug. Even though I write my code in small pieces (small classes and small methods), I am not perfect. When everything is combined and put into production, strange things happen to my code. The code doesn't change; the environment does. A situation occurs that I didn't think of and thus it is not tested. This is the realm of the debugger especially if the bug is nasty and hard to find. Any piece of complex software has these hidden. We are human. Let's embrace that. A world without debuggers is a weird sci-fi perfect world with monsters lurking beneath the surface.

Debuggers are great for exploratory programming when you are just trying out a new framework and seeing how it works. I like to walk line by line. I did this when I was learning Seaside and it was better than any documentation. Besides, watching beautiful code unfold in your debugger is nothing short of reading a great book. And when you're dealing with some ugly code, a debugger has shown me things that my eyes deceived me on when just looking at the code. Why dissect the dead animal when I can see how its organs work while it is still alive?

An expressive debugger saves time as well. I remember when I came back to Smalltalk after doing Java for several years. I had forgotten that you never need to restart your programs. I wrote a simple Seaside application and only restarted the web server once. I coded live in the system and when I saw a problem (that my tests didn't catch) in the debugger, I could change it right there. It was amazing.

I guess all of this talk of no debuggers or that debuggers is a crutch for bad developers. It can enable the "get it running once" mentality instead of thinking of all the cases and your design. Like any tool it can be abused, but that doesn't mean we should get rid of all tools. Duck typing can be abused as well and I wouldn't trade it for the world.

Monday, October 15, 2007

StAX Tomorrow Night

I'll be giving a short talk at the Omaha Java User's Group tomorrow night. It will cover the StAX API that's new to Java 6. StAX is the streaming counter-part to SAX. I'll probably also touch on a little bit of API design too.

Thursday, September 27, 2007

Omaha Dynamic Language Group

Erlang is the hottest new language in the land to learn. It's what on the tip of everyone's tongue. Why is it so hot? What makes it so special? I am proud to have Erlang guru Sam Tesla presenting to answer all our questions. He will be displaying why Erlang scales so well and it's many unique features. This will be one meeting that should not be missed!

And if that wasn't enough, we have none other than Tek Systems providing all of the pop and pizza that our bellies can take. Prepare to have your mind and stomach stuffed!

Come out and join us for the best user group in the land (In my opinion, of course).






TopicA Gentle Introduction to Erlang
SpeakerSam Tesla
TimeOctober 2, 7-9pm
LocationUNO's Peter Kiewit Institute (PKI) building
1110 South 67th Street
Omaha, NE

Monday, September 24, 2007

Good Design

I love Alex Ruiz's post on named parameters in Java. Why? For one, it shows how he got around Java's lack of named parameters. He then goes on to explain why he made the design choices he made. Pros and cons are then listed for the approach. But, the part that I loved is that he sided on the side of the API user. It made his life as the API designer harder and cost him more code to write. The result was something that allowed for more readable code for the client. I love it! I tend to design with making the client's life easier instead of mine. This article is excellent for outlining the design choices and not being dogmatic. Everything is logical and well laid out. Another reason I loved the article is that the lack of a language feature inspired him to work harder to get the same result. A post that inspires us to push for better solutions no matter the constraints.

Sunday, September 23, 2007

I'm embarrassed

I can't believe what gets passed off as humor these days. I'm embarrassed to be part of a community where one of the main evangelists of the community post such bile and garbage. It was meant to be funny. But, calling developers outside your community "morons" even in jest is not cool. It certainly doesn't breed communication and good will. And if you were interested in "making the world of software development a more enjoyable, productive place", then name calling is not the way to do it. I understand it was done in humor and I know you are writing off my serious reply as "dumb" because of your debate killing "if you didn't get the humor, then you're dumb" post. But, if you wanted to be funny, you went about it the wrong way. All you displayed was a level of immaturity that should be unacceptable in our community. It wasn't witty.

And to end I will add, yes, Ruby does need tools. It needs tools badly. I would love to have refactoring support (that works) and a good debugger. I can't imagine doing a project of any size without those tools. Not every one is a great developer and eventually you will step into some unsavory code. Tools are for helping with those unsavory pieces of code and even to gain understanding on a large system. This is where learning comes in. Instead of writing the developer off as a "moron", I use unsavory code and tools to teach how to do it better. So, who's really "making the world of software development a more enjoyable, productive place"?

Sunday, September 16, 2007

A Sorting Language

Inspired by Neal Ford's post on patterns and sorting in Ruby:

class Comparator
def initialize(&default)
if (defined? default)
@compare_block=default
else
@compare_block=lambda { |a,b| a <=> b }
end
end

def compare(a,b)
@compare_block.call(a,b)
end

def to_proc
method(:compare).to_proc
end

def to_comparator
self
end

def then_by(next_aspect)
next_comparator=next_aspect.to_comparator
self.class.new do |a,b|
comparison=compare(a,b)
if (comparison == 0)
next_comparator.compare(a,b)
else
comparison
end
end
end

def reverse
self.class.new do |a,b|
comparison=compare(a,b)
if (comparison == 1)
-1
elsif (comparison == -1)
1
else
0
end
end
end
end


def by(aspect_to_compare)
aspect_to_compare.to_comparator
end

class Symbol
def to_comparator
Comparator.new { |a,b| a.send(self) <=> b.send(self) }
end
end

module Enumerable
def to_comparator
inject do |thus_far, every|
thus_far.to_comparator.then_by(every.to_comparator)
end
end
end

require 'rubyunit'
class SortTest < Test::Unit::TestCase
def test_simple
a=Person.new("blaine", 36)
b=Person.new("blaine", 12)

result=[a,b].sort(&by(:name).then_by(:age))
assert_equal([b,a], result)
end

def test_array
a=Person.new("blaine", 12)
b=Person.new("alice", 12)

result=[a,b].sort(&by([:age, :name]))
assert_equal([b,a], result)
end

def test_reverse
a=Person.new("grue", 123)
b=Person.new("thief", 34)

result=[a,b].sort(&by(:name).reverse)
assert_equal([b,a], result)

result=[a,b].sort(&by(:age).reverse)
assert_equal([a,b], result)
end
end

class Person
attr_reader :name, :age

def initialize(name, age)
@name=name
@age=age
end
end

I loved Neal's post, but it got me thinking that sometimes I need to sort beyond one field. How could I go about that? I whipped up this example really quick. The function :by is simply syntactic sugar for converting to a comparator. I thought it read better. Neal's solution is the way to go if you need to sort on a single field. But when you need more, the above will work too. This is another one of my little late night coding thoughts. Enjoy.

Saturday, September 15, 2007

Duh....

pdcawley wrote the following comment to my previous "reduce" post:
[1,2,3,4].inject() {|a,b| a + b} # 10

So, I looked it up in ri and got this entry:
------------------------------------------------------ Enumerable#inject
enum.inject(initial) {| memo, obj | block } => obj
enum.inject {| memo, obj | block } => obj
------------------------------------------------------------------------
Combines the elements of _enum_ by applying the block to an
accumulator value (_memo_) and each element in turn. At each step,
_memo_ is set to the value returned by the block. The first form
lets you supply an initial value for _memo_. The second form uses
the first element of the collection as a the initial value (and
skips that element while iterating).

# Sum some numbers
(5..10).inject {|sum, n| sum + n } #=> 45
# Multiply some numbers
(5..10).inject(1) {|product, n| product * n } #=> 151200
javascript:void(0)
# find the longest word
longest = %w{ cat sheep bear }.inject do |memo,word|
memo.length > word.length ? memo : word
end
longest #=> "sheep"

# find the length of the longest word
longest = %w{ cat sheep bear }.inject(0) do |memo,word|
memo >= word.length ? memo : word.length
end
longest #=> 5

Ouch. All that coding for nothing (well, I did get to play around with some stuff). Next time, I will consult the documentation before I post. Duh...Good call.

P.S. It seems Rails implements the Symbol extension of #to_proc already. It's in the activesupport stuff. Their implementation is similiar to mind. But, I found one implementation better than mine. I love reading other people's code because it always shows me things I didn't think of. For your reading pleasure:

class Symbol
def to_proc
lambda do |this, *arguments|
this.send(*arguments)
end
end
end

This is better than using shift and cleaner. I got this from one of the comments off of Neal Ford's blog. Great stuff.

Friday, September 14, 2007

More Functional Fun In Ruby

I have no clue whenever this will be useful, but it was a fun exercise. Hope you enjoy it as well. It's an implementation of Lisp's cons, car, and cdr.

def pair(left,right)
lambda do |dyadic|
dyadic.call(left,right)
end
end

def left(pair)
pair.call(lambda {|left,right| left})
end

def right(pair)
pair.call(lambda {|left,right| right})
end

require 'rubyunit'

class WorkspaceTest < Test::Unit::TestCase
def test_simple
a_b=pair('a','b')
assert_equal('a',left(a_b))
assert_equal('b',right(a_b))
end

def test_again
a_b=pair('a', 'b')
c_a_b=pair('c', a_b)
assert_equal('c', left(c_a_b))
assert_equal('a', left(right(c_a_b)))
end
end

Python's Reduce, (Fun)ctional Programming, and Ruby

Mike Hostetler blogged about Python's reduce. He said he never had a use for it until recently. I looked at his example and I thought that looks a lot like inject, but it uses the first element in the collection as the seed instead of it being given. I thought what mad fun would it be to write one in Ruby? Exactly. Here's my implementation:

module Enumerable
def reduce(empty_return=nil, &dyadic)
to_execute=lambda do |thus_far,every|
to_execute=dyadic
every
end
inject(empty_return) do |thus_far, every|
to_execute.call(thus_far,every)
end
end
end

require 'rubyunit'

class ReduceTest < Test::Unit::TestCase
def test_simple
result=[1,2,3,4,5].reduce {|thus_far,every| thus_far + every}
assert_equal(15, result)
end

def test_empty_nil
result=[].reduce {|result,every| thus_far + every}
assert_nil(result)
end

def test_empty_default
result=[].reduce(0) {|result,every| thus_far + every}
assert_equal(0, result)
end
end

It has a somewhat functional style in that instead of using a boolean to check for the first iteration, I just use a special lambda for the first pass and then it turns itself into the original one. There is some state (to_execute), but I'm still a functional newbie.

I do love inject, which has a lot of uses beyond aggregation, and this will reduce (no pun intended) code in some places where I use it.

Anyway, I couldn't stop myself. I thought wouldn't it be nice to just pass in a symbol instead of a block? I added the following method to Symbol and another test. Check it out:

class Symbol
def to_proc
lambda do |*arguments|
arguments.shift.send(self, *arguments)
end
end
end

class SymbolTest < Test::Unit::TestCase
def test_simple
result=[1,2,3,4,5].reduce &:+
assert_equal(15, result)
end
end

All I do is take a list of arguments. I make the first one the receiver and send the rest as it arguments. How cool is that? I get to cut down on the line noise. I still have to put up with &, but until they make blocks first class citizens...

What's the point of this post? Nothing. Just wanted to do a fun little exercise. I thought others might find the implementation fun as well. Now, about that name 'reduce'...I think maybe aggregate would be better? But, that doesn't express for all cases either. Hmmm...

Monday, September 10, 2007

Why Is Groovy So Slow?

Peter Knego wonders "Why Is Groovy So Slow?" and shows some evidence. I will admit I expected Groovy to be slower than Java because even though it does compile to Java byte codes. It has to perform various translations to satisfy the VM that expects a lot to be already typed. The Java VM is an ugly world for dynamic languages because of the early bind nature to gain performance. Some of his numbers were shocking. He also mentioned he was going to run numbers on jRuby as well. I'll be curious about that too. I'm expecting the numbers to tell a similar story.

But, that's not the point of this post. I'm worried with posts like the above because developers will use it as evidence that you shouldn't use dynamic languages. I never thought the arguments for not using dynamic languages would be played out again. Back in the 90's, it was Smalltalk vs. C/C++. I remember having many a debate how the productivity gains out weighed the small performance hit for late binding. I thought when Java won, I would never have to argue about performance ever again.

It's not that the above posts are bad. I think they are wonderful. It gives something that the Groovy guys can use to make their product better. And that's good for all of us wanting to be dynamic in a static world. But, those numbers will also be used to prove why you shouldn't use dynamic languages. And that's sad. It's all come full circle. I hope I am wrong, but I doubt it. The numbers are not bad because dynamic languages are slow, but because trying to get them run on an architecture not built with them in mind.

We Need Each Other: Ruby and Smalltalk

Neal Ford made a blog post on meta-programming, Ruby, and Smalltalk recently. It caused some discussion from long-time Smalltalker, James Robertson, and Rubyist, Glenn Vandenburg. Even Avi Bryant got in the discussion. There was a lot of talking past one another on the issues of code generation in Ruby and Smalltalk.

I'll start with a quote from Neal Ford:
the Smalltalk version is a great example of accidental complexity, not essential complexity.

There is no example given of what the "accidental complexity" was in Smalltalk. But, let's look at an example that Rubyists are familiar with and then I'll go forward:
class Person
attr_accessor :name
end

This will generate the accessors :name and :name= at run-time. It's a nice way to describe a public field. There's even read and write only variations. It allows you to describe your intent of the field. Now, in Smalltalk you could do the same thing with class-side methods. Like so:
attributeAccessors
^#(name)

This could add the instance variable (if it didn't exist), and generate the getters and setters when the class is initialized. It is true in this case, we would use tools to do the generation and generate the code before hand. I think this is what Neal was talking about accidental complexity because we are adding methods that we later have to browse through. But, this is where they are mistaken.

Smalltalk has categories and usually, these code generated methods are placed in them. Accessors are generally placed in their own category so do not add to the cognitive friction. In fact, when I use code generation, I group the methods in a category with "AUTO" in it. This is so that I can later delete those methods and start over. Also, it allows me to not have to look at them when looking at the more important methods of the class.

There is one last way to do things like this in Smalltalk, but is rare. Classes are created in Smalltalk by sending messages. It's not some hard-coded construct in the language. It's a message. We can create our own messages to create our own classes. Here's what the example could look like in Squeak:
Object subclass: #Person
attributeAccessors: 'names'
classVariables: ''
poolDictionaries: ''
category: 'MetaExample'

And lastly, there is a initialize method for all Smalltalk classes that would give a more Ruby feel:
initialize
self attributeAccessors: 'name'

Now, with all of that said, these are just examples to show what is possible. It's all a matter of taste and what you are trying to accomplish to which method you choose.

finally, my mouth dropped when I saw this in the same blog post:
Smalltalk had (and has) an awesome environment, including incredible tool support. Because the tool is pervasive (literally part of the project itself), Smalltalkers generally shied away from the kind of meta-programming described above because you have to build tool support along with the meta-programmed code. This is a conscious trade off. One of the best things about the Ruby world (up until now) is the lack of tool support, meaning that the tools never constrained (either literally or influentially) what you can do. Fortunately, this level of power in Ruby is pretty ingrained (look at Rails for lots of examples), so even when the tools finally come out, they need to support the incredible things you can do in Ruby.

I will answer this as bluntly and respectively as I can. Smalltalkers have NEVER shied away from meta-programming because of having to build a tool. Most Smalltalkers have a bag of tools that they use and add to their environment. Tools are so easy to write in Smalltalk that most programmers in it have at some point written one or two to help them. It's trivial to add functionality to the browser and inspectors. Generally, Smalltalkers only stay away from things that are hard to debug (ala method_missing, doesNotUnderstand:), but do them when necessary. Readability is always the utmost importance to Smalltalkers. Abbreviations are generally frowned upon even.

The last thing I want to remark on is the quote in bold above. I'll repeat it here because it makes me both shocked and sad:
One of the best things about the Ruby world (up until now) is the lack of tool support

I hardly call that a strength. Really. Why would I want to go back to bear skin and stone development? I have finally become productive in Java because of Eclipse (code browsing, auto-format, code completion, refactoring, etc). Why would I want to go back to command line brute force methods? I keep hoping for a great Ruby IDE (some are close like Ruby's Eclipse plug-in, Arachno, etc). Besides, I think while tools like ri and rdoc are nice, I want to look at source code and it's difficult to find the definitions of methods (without using grep) when going through new source code. A friend once told me he never trusted a language you couldn't write an IDE for it. There's truth to that. I never got FreeRIDE to last longer than a few minutes of development. Tools and easy to read syntax are necessary.

Ruby has great potential, but the syntax needs to be heavily reafactored (%w while being nice shorthand is unreadable) and made more consistent (blocks do not take the same types of arguments as methods, I can not send a block with & into a block example, lambda {|&block| block.call } gives a compile error). But, those are my gripes and I do still like Ruby. I think boasting that your language has no tools is short sighted at best.

I think both Smalltalk and Ruby developers could learn a lot from one another. So, if any Ruby developer has questions about Smaltallk, please feel free to email me. I will even extend the same to Smalltalk developers curious about Ruby. The point of this post was mainly to educate and inspire both Rubyists and Smalltalkers to be better.

Saturday, September 01, 2007

Omaha Dynamic Language Group

Pinch me. Our speaker this month is none other than "Mister Groovy Eclipse Plug-In" Scott Hickey. He will be speaking about Rexx though. Rexx is a little known scripting languages with some unique features. This should be an incredible talk to make you think about Rexx in a totally different light. I can not wait.

I hope to see everyone there!





TopicRexx: The Little Known Scripting Language
SpeakerScott Hickey
TimeSeptember 4, 7-9pm
LocationUNO's Peter Kiewit Institute (PKI) building
1110 South 67th Street
Omaha, NE

Tuesday, August 28, 2007

String Concatenation

I made a small mistake in the code in "Promises and String Concatenation". The DelayString object not being stateless is a huge problem. Here's the test to prove it:
    def test_independence
first = "3" + "4"
second = first + "5"
third = "2" + second
assert_equal("34", first.to_s)
assert_equal("345", second.to_s)
assert_equal("2345", third.to_s)
end

Ouch. I fixed it by making DelayString only know a left and a right part. It cleaned the code up quite a bit. I factored out Promise because it made the code a little less readable. The resulting code is much simpler:
class DelayString

def initialize(oneString, anotherString)
@left = oneString
@right = anotherString
end

def +(another)
DelayString.new(self, another)
end

def to_s()
return @result unless @result.nil?
to_process=[self]
@result=String.stream_contents do |out|
until (to_process.empty?)
current=to_process.pop
current.process(to_process,out)
end
end
end

def process(to_process,io)
to_process.push(@right)
to_process.push(@left)
end

end



class String

def self.stream_contents(&monadic)
StringIO.open() do |io|
monadic.call(io)
io.string
end
end

def +(another)
DelayString.new(self, another)
end

def process(to_process,io)
io << self
end

end

All of our tests run. DelayString is stateless (minus caching of the result). There's still improvements to be made, but the code is simpler and easier to understand. The performance did take a hit. It's twice as slow (43.94s) as the previous version. Not to worry it still beats normal concatenation by a large margin. I'll take the performance hit for more readable code anyday!

Saturday, August 25, 2007

Promises And String Concatenation

You've read about it a million times. Beware of multiple string concatenations. They make your code slow and consumes memory. You've read it in the Java books (known as "use StringBuilder or StringBuffer instead of +"). But, why? Why isn't this handled at a lower level? Why can't the VM or compiler just do the right thing?

Messages are the power of objects. So, why not make a new object that when sent the + message, it simply returns an object that waits to do the concatenation until it is needed. This new kind of object should understand the same protocol as string. This could all be handled underneath the covers. If it was done at the VM or compiler level, programmers would never have to know.

I thought I would do a sample implementation. It's rather easy (in a dynamic language). First, we need to implement a Promise class and here's the Ruby code complete with a simple test:
require 'rubyunit'

class Promise
def initialize(&block)
@calculation=block
@value=nil
end

def value
return @value if @calculation.nil?
@value=@calculation.call()
@calculation=nil
freeze()
return @value
end

def value?
@calculation.nil?
end
end

def promise(&block)
Promise.new(&block)
end

class PromiseTest < Test::Unit::TestCase
def test_simple
promise = promise { 3 + 4 }
assert(!promise.value?)
assert(7 == promise.value)
assert(promise.value)
end
end

Pretty simple, huh? Create a new Promise object on a block (or closure or lambda or whatever you like to call it) and it will only call the block once when the message "value" is sent to it. If the message "value" is never sent, the block is never evaluated. Can you think where that might come in handy? I can think of several, but the best one is when trying to create a message to log. If you don't log the message, you wouldn't need to do the concatenation. Again, not doing the computation upfront can not only allow us to manage memory better, but also not to do needless calculations.

Enough talk, let's get to the good stuff, right? Here's my implementation of delaying concatenations and check the tests out at the bottom:
require 'stringio'

class DelayString
def initialize(oneString, anotherString)
@strings = [oneString, anotherString]
@promise = promise do
stream = @strings.inject(StringIO.new) do |output,each|
output << each
end
@strings = nil
freeze()
stream.rewind
stream.read
end
end

def +(another)
return another.concatBeforeDelayString(self)
end

def concatBeforeString(another)
@strings.unshift(another)
self
end

def concatAfterString(another)
@strings.push(another)
self
end

def concatBeforeDelayString(another)
strings_each do |each|
another.concatAfterString(each)
end
another
end

def concatAfterDelayString(another)
another.concatBeforeDelayString(self)
end

def to_s()
@promise.value()
end

private
def strings_each(&block)
@strings.each(&block)
end

end

class String
def +(another)
return another.concatBeforeString(self)
end

def concatBeforeString(another)
another.concatAfterString(self)
end

def concatAfterString(another)
DelayString.new(self, another)
end

def concatBeforeDelayString(another)
another.concatAfterString(self)
end

def concatAfterDelayString(another)
another.concatBeforeString(self)
end
end

class DelayStringTest < Test::Unit::TestCase
def test_simple
add = "3" + "4"
assert_equal("34", add.to_s)
end

def test_string
add = "3" + "4"
add = "2" + add
add = add + "5"
assert_equal("2345", add.to_s)
end

def test_delay
add_before = "1" + "2"
add_after = "3" + "4"
add = add_before + add_after
assert_equal("1234", add.to_s)
#make sure to get same answer twice
assert_equal("1234", add.to_s)
end
end

One new class called DelayString handles not doing the concatenation until absolutely necessary. It does this by creating a Promise that calculates the string by using a StringIO object (Stream or StringBuilder in Java terms). All it does is keeps a collection of all the strings it needs to append to one another. The power is now that we get the nice succinct message "+" and all of the benefits of using a stream object (or StringBuilder). Of course, we would need to add more methods on our DelayString so that it has the same protocol as String. A little more work to make our implementation seamless.

Below is the test method I added to find the times it took to run for delayed and normal concatenation:
    def test_performance
add = ''
1000000.times do |iteration|
add = add + 'a'
end
add.to_s
end

The new delayed implementation ran at 23.8 seconds. Not bad to do a million additions and a lot of little ones at that. Now, what were the results the old way? Well, all you have to do is comment out the + message:
#  def +(another)
# return another.concatBeforeString(self)
# end

It took 4565.68 seconds to run the normal way. It performed poorly and took up a bunch of memory. Yuck. It's what the books warned us about right? It's what we expected somewhat. I didn't expect how much of a performance gain I really got. Pretty cool, huh? Amazing.

It's unlikely that we'll do something to this extreme in the real world. But, wouldn't it be nice to not worry about performance in our regular code? If we find that our implementation is sub-par, one of the new benefits is that we can change it in one place.

Wait a minute. We just got better performance and got to keep the simple way of doing things? Not one lick of our already existing code had to change. The power of messages is powerful indeed!

Saturday, August 18, 2007

Quiet Lately

It's been a busy couple of months for me. I've been giving a bunch of talks (Refactoring, Good APIs, and Design). Switched from being a consultant to an employee working for an incredible team. I spent two weeks traveling and to top it off, I saw some of my fave artists (Alice Cooper, Behemoth, and Shadow's Fall) and caught a late summer cold. Still recovering from the cold and trying to get back into blogging. Sorry for being so quiet, I plan to correct that situation soon. Life is getting back to normal. I just got to kick this cold.

Saturday, August 11, 2007

My Favorite Smalltalk is Gone

I am so sad. I come back from seeing one of my favorite artists only to read sad news. I can not express how much I enjoyed working in Dolphin and using it. I was a proud supporter and was always excited to see a new version. This really sucks. Dolphin had the best Smalltalk period. In fact, it's the one I used to get people hooked. It looked modern and was extremely easy to use.

I realize it's hard to make money in the software development tools business. My own business failed as well. I was hoping for Dolphin to stick it out. Good luck to the Dolphin guys. I just want to thank them for all the love they put into the world. Dolphin will always have a special place in my heart. It will be hard to say good-bye.

Well, there's no reason for me to stay with Windows anymore now.

Friday, July 20, 2007

Sign Your Real Name

Penelope Trunk recently wrote a blog entry on why you should blog under your real name. I agree completely with all of her points. I would also add to comment under your real name as well. Personally, I can't stand anonymous comments or even ones with nicknames. If you're going to say something, stand beside it. Don't hide. Defend it. Dig?

Monday, July 16, 2007

Bad Code

I have a thing for bad code. In fact, I've been talking every month at the Omaha Java User's Group about it every month by refactoring ugly code. Well, I ran into this article about poor practice in coding examples. Don't worry give it a quick click. It's bewildering no matter how much technology changes, bad code remains. What's even more worrisome is I see the same errors in code today. It makes me wish they gave out Code Complete to everyone.

Sunday, July 08, 2007

My Job Went To India

Sam comments on "My Job Went To India" by Chad Fowler and I think I have been too harsh with this book. I have refused to buy it from the title and especially the cover. Sam discussed the problem they had with that. When I came out of college, there was a ton of "scare" books about how all programming jobs were going overseas. Let's just say that was several years ago. I hate "scare" books and the title of Chad's book smelled of that. I refused to even open it in the store. Sam explains they wanted a funny title and it didn't sell because of that. I can understand that completely. I've heard nothing but good things about the book and maybe it's time for me to my bias aside and to read it. But, I will probably put a book cover over it because I can not stand the title or cover. Let's hope the pragmatic programmers re-title it and re-release a second edition with something less scary or funny.

Besides, if it was a joke, it wasn't funny. Scare books are cheap shots and not worthy of anyone's money. So, if they are wondering why sales were poor, I gave my reason. I trust Sam and I will probably buy it now. What a marketing mistake though.

Smalltalk Obstacles

Smalltalk has some obstacles to get over for developers interested from the outside and to take it seriously. These have always been the obstacles and they are:

  1. Different World
  2. Image-based development is strange to most developers. Also, Smalltalk forces developers to drop all of their pre-existing tools to play in this magical world. It's a lot to give up.
  3. Different Syntax
  4. Smalltalk's syntax baffles a lot of developers because it's so different from anything else. Most of what they have seen has been Algol-based. But, I've never seen a developer not understand it within a few minutes, but it is a hurdle for folks. This hurdle will always be there. Changing the syntax would make Smalltalk not Smalltalk.
  5. Unwillingness to compromise
  6. Smalltalk is powerful and the integrated tools is what makes it powerful. But, a little compromise to help developers dip their toes would help. At least allow to have some sort of training wheels before they jump in all the way. We need to allow them to test the waters.

But, the new obstacles along with the old ones are:

  1. We no longer have the largest library
  2. It's incredible the amount of open source libraries that Java and Ruby has. It's especially true for Java. It's enormous. Anything I want and it's been done. From database mapping to GUI to XML to you name it, it's just a source forge click away.
  3. Dated
  4. All dialects besides Dolphin look dated. There's no pizazz and simple things like consistent key bindings are not there. It's all a matter of polish and it shouldn't matter, but it does to a lot of developers. Sad but true. Looks matter.
  5. Tutorials
  6. There has been movement in this area recently in both Squeak and Visual Works. It's great and we need more.
  7. Marketing
  8. All of the Smalltalk web sites look old. Some graphic designers would go a long way. Ruby on Rails got to the top of the heap and exposed Ruby because of great marketing. I was programming in Ruby before Rails and it had none of the benefits of Smalltalk. We have a strong community, but marketing wins. Java kicked our butts once and at the time, we had the best libraries, environment, and everything. Marketing is king.

Now, that being said, I think a better looking Squeak, VisualWorks, and VisualAge is a must. I think they should all look at Dolphin. Dolphin is everything a modern Smalltalk should be. It's gorgeous. The key bindings are consistent, tools are easy to understand, and it's a pleasure to work with. They are also constantly adding new tools to help productivity (IdeaSpace) as well. In fact, I usually show developers Dolphin first to get them interested.

I think a good looking GUI is the first step. But, I also think making it easy for developers to use Smalltalk as a scripting language is a must too. We need to allow for developers to ease into image-based development by using their own tools. Yes, they will be less productive, but consider it to be an olive branch somewhat.

If we are to get more developers interested, we must come a little to them. I tried writing a scripting like environment for Squeak to make it easier for developers outside of Smalltalk to code in a more scripting style. And I keep playing with syntax to keep the simplicity, but also things to developers from the outside more comfortable.

And last but not least and this is a deal breaker: libraries. Seaside is a huge advantage, but we need more libraries that not only do cool things, but practical things as well. We have a lot of growth needed in this area.

The Ruby community has done a great job at showing off what you can do with pure objects and closures. Now, let's make it easy for them to see why an image and integrated tools make your live easier! We need to get off our island and start mingling with everyone. I created the Omaha Dynamic Language User's Group in the hopes to show developers what makes Smalltalk great(along with other dynamic languages as well like Lisp).

Friday, July 06, 2007

Crabs In The Pot

My good friend, Steve Wessels, wrote an excellent tutorial on Squeak development that shows how to use all of the tools while showing off what Smalltalk coding is like. I simply love it. But, I was shocked when I read Ramon Leon's comments on Steve's tutorial. While I agree that Squeak could use a marketing image overhaul, we sorely need more tutorials like Steve's. My gut instinct to Ramon's comments was, "this is like a crab trying to escape the pot, the other crabs will drag him back". Steve put a lot of work in the tutorial and it shows. Sure, he could have used all the nice add-ons, but it was meant to show developers "how to fish". Once they know the basics, then they will have enough knowledge to install those add-ons.

I feel Smalltalkers should stop complaining (about bad marketing, java, ruby, whatever) and start doing. Steve took a bold step forward and I applaud him for that. We need to have more doers and less complainers. So, if you feel marketing of Smalltalk is not up to par, do something! I started a user's group here in Omaha to get interest in dynamic languages. It's been growing larger and larger. The user group has gotten a lot of people interested not only in Smalltalk, but Lisp as well. But, I know I could do more. Steve is an inspiration and incredibly enthusiastic. If we want people to join us, we need to support the group we have now. Feedback is good and welcome, but if you feel you can do better....Well, then DO!

I didn't mean for this come out like I'm being harsh on Ramon. I don't want that. I love Ramon's writing and by having a blog, he is doing. But, I think we need to be reminded our community is small and we need to support one another. If Squeak is ugly, let's do something about it!

I wonder who will write the next tutorial on how to make Squeak look awesome? Whoever it is rock on! And I hope Steve does more tutorials, the laser game is too much fun. It shows how playful and curious Smalltalkers are and that's a great thing.

Thursday, July 05, 2007

Omaha Dynamic Language Group

Get out the thinking caps because Jay Hannah is coming to speak about how to mix Bioinformatics and Perl together perfectly. It's going to be one night that you will not forget. Jay has a love for both and he will make you a believer that Perl is more than just another scripting language.

We are sponsored this week by none other than Bass. They will bring the food and beverages.

Intelligent conversation, great food, excellent company, and it's all free. Come and see that the fuss is us.





TopicBioinformatics and Perl
SpeakerJay Hannah
TimeJuly 10, 7-9pm
LocationUNO's Peter Kiewit Institute (PKI) building
1110 South 67th Street
Omaha, NE

Tuesday, July 03, 2007

Subversion

I just want to say that I have been completely been bitten by the Subversion love bug. I've been using it for a little while. It's easy to maintain and use. Even the command line is a pleasure to work with. The API is simple and everything just works. I've yet to find anything painful. Why would anyone use CVS?

More on Exception Handling

Another great comment from Malcolm Sparks:
I complete agree with you Blaine about not throwing away information. Keep everything, and add to that information whenever you have something to add. For example, when a caller catches an exception, the caller always has some indisputable and unique information it can add: exactly what it was trying to attempt when the failure happened.

Dropping this information is like using a shredder. It's not responsible behaviour for developers to shred information that might be useful to the poor sod who had to fix your buggy code at 4am in a production environment.

Actually, such information is often the 'single golden clue' that leads to a rapid diagnosis of the error. For this reason, I believe it's justified to add such information even when unchecked exceptions occur. "Yes, you got a NullPointerException, but what exactly were you trying to do when you caught the NullPointerException?"

For that reason only, I disagree with you about catching only the most specific exception- I always catch, wrap and rethrow any subclass of java.lang.Exception. I started handling exceptions in Java this way back in 1997, and haven't seen anything since that has caused me to change my mind (but I'm open to debate).

What a great idea! I love it. I agree if you are checking for generic exceptions and then wrapping them into more domain specific for more information, then rock on. My original comment was aimed at catching generic exceptions in your code and then doing nothing with them. I still generally try to catch the things that I expect to go wrong and use my top level to catch things I didn't. Always adding more information is a good idea in my opinion especially if it gives you more context. As with any rules, it really requires thought and good judgement to make a good program right? Thanks for the suggestion!

T.H.O. Part ][

Malcolm Sparks had this to say:
I think that we a few more people with that T.H.O. attitude to prevent open-source libraries from stagnating. It is a good thing that the incumbent 'standard' library gets regularly challenged by contenders. Without continual selection and reselection, evolution dies and progress stops.

The argument that we only need just one of anything is really unhealthy. It leads to mediocrity: I present J2EE as a perfect example. One of everything you could possibly want, put it all together and what do you have? Crap.

I think you might have misunderstood me or I didn't make myself clear. My point is if you have want to do something better, then do it in the open source community. Go at it and have all the fun you want. I think the open source community needs and thrives on forward thinkers. At least there, you will have feedback, tons of people testing, and a chance for your idea to mature. But, I believe doing that on a corporate project is risky and prone to maintenance nightmares. Why? Because generally they have not gone under the same scrutiny an open source project has.

When I learn some new technique or have some crazy idea, I write it in my spare time. If I like it, I'll publish it on my site. Now, there's a lot of things that I did (like LazyCollections) that I would never do on a real project. Why? Well, LazyCollections was a chance for me to play around and try things out. I thought the experiment might be a helpful learning exercise to other people. But, the code is generally hard to understand for most developers.

I have empathy for the people that will have to maintain my code. Generally, this means I don't code things that I can, but what can be easily tested and maintained. It's not dumbing down the code or the design. Simple designs don't need tricks. They just need thought and lots of it. Simple designs are not easy and generally not the first solutions you come to. They are hard work.

Monday, July 02, 2007

Good code tells you where it hurts

I've been meaning to write an entry on exception handling and how important it is to not throw away information. So, here it is. I'll start with one my pet peeves below:
try {
...hard stuff here...
} catch(Exception problem) {
problem.printStackTrace();
}

OK, first off, I'm usually skeptical of catch all blocks at low levels. But, there can be good reasons for them, but the problem I have with code above is printing the stack to the standard out and continuing. At the very least, this is only good for when you are doing command line utilities and even then it's not good. Worse yet, this is the default from Eclipse! I've been bitten too many times where code went wrong and we couldn't find out why because the stack was written to the standard out and we couldn't see what it was. Or maddeningly the code continued and caused other problems further down. Fun to debug those problems it really is. My solution is if it's informational and you can continue log it, if not re-throw the exception. But, there's times when you catch a checked exception, but it's something that's serious enough to stop current processing. I've seen this:
try {
...something hard here...
} catch(Exception ex) {
throws new RuntimeException("Something bad happened");
}

Thankfully, I haven't seen the above code so much since 1.4 added support for wrapped exceptions. But, I still see it. The problem with the above is the original exception is dropped. When debugging or trying to find a problem, the above code gives me no information of the original context. It's useless, but it did stop bad things from happening further down. But, it would be almost possible to find out what really went wrong.

Always catch the most specific exception and leave the catch all exception handlers to the top level code. It will save you headaches, I promise you.

My rule of thumb to exception handling is: if something goes wrong, what would I want to know? I see too much code where this is forgotten or it is written as if nothing will go wrong. In a perfect world, all code works beautifully and there is no need for exception handling, but we don't live in that world. As always think about helping the poor developer that has to come behind you.

T.H.O.

T.H.O. used to be an acronym that a friend of mine would use to describe code in which it was apparent that a developer put his ego before the good of the team. The code exhibits clever behavior when a simple approach would have sufficed. But, the developer had to show off that they knew a certain trick. Sometimes, it can be more sinister. A complete library written from scratch when there are open source equivalents better tested and designed. But, they just couldn't resist doing it themselves (also known as the "not invented here" syndrome). They think they can do better. But, normally, it is some poor maintainer that has to deal with their "better" solution after they are long gone to the next T.H.O. In this day and age, I can't see how anyone can justify writing a library from scratch if there is an open source equivalent. It boggles my mind. Of course, if you think you can do better, then do so on your own open source project and live with the code before causing a maintenance nightmare for years to come. Besides, you'll get valuable feedback and fix bugs from other developers. Value simplicity and doing the least to get the most.

Tuesday, June 05, 2007

"Get 'Er Done" Programming

OK, if you don't like my rants, stop reading now. I've been trying to write this entry for a while without sounding venomous, but I just can't do it. But, I'll start with what I call "Get 'Er Done" programming. Now, I'm sure you've seen the highly annoying "cable guy" comedian that utters this despicable phrase. But, it's what I hear when I see lazy code written until it works. It's maddening I tell you! Basically, writing code until you can get a simple example to work and stopping there is lazy. Failure to look at the big picture should be punishable. But, I see examples of it littered everywhere.

Alright, you might ask what does "look at the big picture" mean exactly? What I mean is do proper analysis. Think about your problem before you write any code. I'm not advocating huge up-front design here, just thinking before you burn up your keyboard. It might also entail asking a few questions about the problem to fellow team mates and the user. It all depends on what your coding and your understanding. Looking at the big picture also means in making your code to be able to have future extensions that you can't anticipate. You might think this is impossible, but it's not. If you make the objects small, each one has a single responsibility, have good intention revealing names, and make small methods, then you have made your code extensible.

The whole point of this blog post is don't be lazy and make life difficult for the person that has to come behind you. Think about what you're doing and make your code easy to read. Remember there is always someone coming behind you that has to learn what you did. Make it obvious and show that you cared by going beyond the simple example. Well, looking back this wasn't so bad was it? Sometimes rewriting and thinking about what you write works too.

I'll end with a piece of advice: always re-read your code once you have written it and it works. You would be amazed at what you catch (misspelled words, uncalled methods, unused variables, etc). Of course, with today's tool this is quite easy. In fact, Eclipse can flag most of these with a warning, but it's still a good habit to read your code before you check-in. Let's stop "Get 'Er Done" coding today. Besides, only idiots write code that way and I know you are not an idiot, right?

Tuesday, May 29, 2007

Omaha Dynamic Language Group

The air is warm, the sun is shining bright, and the monitors are glowing. Yes, it's time again for another stupendous Omaha Dynamic Language User's Group meeting! This month we are honored to have Ryan Stille speak on Cold Fusion! If you've ever been curious about this technology, then you need to see this presentation. You may never see the world the same again afterwards!

This month we are also honored to have Concentric sponsor us! They will be providing food, drinks, and much merriment. We are glad for their participation.

I will see you all there for the greatest user group ANYWHERE!






TopicCold Fusion
SpeakerRyan Stille
TimeJune 5, 7-9pm
LocationUNO's Peter Kiewit Institute (PKI) building
1110 South 67th Street
Omaha, NE

Friday, May 11, 2007

Jargon

I just have to scream, "RIGHT ON!", on this post from Penelope Trunk: What the jargon you use reveals about you. I think this is true for us technologists as well. See my post below about Idea Killers. Stop using jargon and mantras! Think! Wait a minute? Isn't that a mantra?

Idea Killers

Recently, I've loathed hearing the phrases: "YAGNI" (You Ain't Gonna Need It) and "Is that the simplest possible thing?". My gut becomes knotted and disgusted. It makes me not want to be considered agile anymore. Why you ask? I always saw agile as positive forces in the software industry. I welcomed them with open arms because they were a shot of fresh air and made everyone think about how they did things. But, now the mantras are being used to be idea killers.

The mantras were meant to shake your thinking. How could you do this as simple as possible and still work. A nod to good engineering and design to shake the brain to think of another solution. Or ask questions like "Do you really need that huge framework?" But, lately, these mantras have been having the opposite effect. I've been in meetings where they were used to shoot down good ideas. And they work well. It's hard to argue against. You don't want to be the person that doesn't want the simplest solution right? But, when you are at the phase of generating ideas, these critical phrases kill the creative spirit. I say no more.

I say no more mantras. Let's think. Let's generate ten great ideas and then be judgmental of each one. At the idea phase, all ideas cost the same. Crying "It's not the simplest thing" too soon kills good design thoughts dead before they are allowed to grow. I think these phrases have become too common place. They are used to shut off thought and prove you are right. Besides, it's been a rare event when someone meant truly simple and not easiest. The two are confused frequently. Simplicity takes practice and thought. There's a reason why Einstein said it. It took several rewrites to get Smalltalk to its current state of simplicity.

Think about it. Refuse the use of mantras. And let ideas flourish.

Truth, Justice, And The American Way

There's one subtle feature of some languages that keeps causing me pain and in the wrong hands causes more harm than good. What is this feature? Let me show you some Javascript code:

if (transaction.amount) {
transaction.markValid();
} else {
transaction.markInvalid();
}

Nothing wrong here, from the looks of it the code is checking if the transaction has an amount defined and then marks the transaction valid or invalid. Simple right? But, what if an amount is defined and it is zero? You would think the transaction is marked valid right? WRONG! It will be marked invalid because anything that's zero, nil, or undefined in Javascript is considered false.

And that's my beef, why not treat booleans with their own type. Why treat any other value as equivalent? Subtle bugs like the one above are infuriating to me. The simple reason is that they can easily be avoided with a few extra characters.

if (transaction.amount == undefined) {
transaction.markValid();
} else {
transaction.markInvalid();
}

The moral of this story is to code exactly what you mean. Be specific. Don't rely on arcane language features to save a few key strokes. Java and Smalltalk do the right thing and make you use boolean types.

Wednesday, May 09, 2007

I Can't Stand Pretentiousness

There I said it. I don't care what it is. A programming language, methodology, religion, music, art, coffee, movies, or what have you it doesn't matter. It reeks to me and I'm sorry for anyone who uses it to make themselves feel superior. Somethings I don't understand being pretentious over like wine (angry grapes because they are bitter for being made into that) or scotch (yes, I would like some turpentine please). I've tried them, I didn't like them. But, if you do, then more to you. It's not a reason to think your are better. But, I digress. I'm always running into people that stick their noses up based on what I like. Nothing cuts off a conversation sooner for me than when someone says, "Why do you listen to that Y garbage?" or "How can you stand to program in language X?" I just walk away because you are not worth my breath. I think it blinds your thoughts and makes it impossible to reason. I would rather hear, "Why do you like X?" or "Give me the top greatest pleasures of Y". I like to ask those questions. I'm always amazed at the answers.

I guess it's my southern upbringing. I like simple things, but I also enjoy richer experiences as well. I just hate it when someone is not open to the joys of the simpler things. I listen to all kinds of music, food, or what have you. I will try anything once. And I research any language I can get my hands on. They each have their strengths and pluses.

Now, don't mistake pretentiousness with excitement. I love excitement and a healthy jubilation for your newest discovery. But, when it turns to thumbing your nose at something, then I think the coin has been flipped.

Oh well, I had to get that rant off my chest. I'll probably read it tomorrow and go "What the hell were you thinking?!" Or maybe I was just trying to say, "There's something positive about everything, find it", in a really negative way.

Live Refactoring May 15

I got talked into doing a "live" code refactoring at this month's Omaha Java User's Group with Sam Tesla. It will happen on May 15. Actually, you need to come because we don't know what code we will refactor yet except that it will be horrendous. You will see the ugly come elegant and simple! Sam and I did a similiar "live" refactoring for the local Software Process Improvement Group not too long ago. It went well and was a lot of fun. It's fun collaborating with Sam and our styles compliment each other very well. Of course, the code will be in Java and we'll be showing off what you can do with Eclipse. It's rare you get to see the journey to elegance and this will be an opportunity not to be missed! I hope to see everyone there.

Sunday, May 06, 2007

DSLs: What's the big deal?

I've always wondered what the big deal with DSLs was. Now, i'm not saying they are bad quite the contrary.But, I believe a DSL is a healthy bi-product of a good object-oriented design. So, I was a little annoyed with all of the talk and the tricks. I kept thingking to myself, "But, if you did a good design, you would have this!"

But, I should really be kicking myself. I should be glad that good design is back in vogue. and you know what? I am. I'm not annoyed any long and I relish all of this new talk on DSLs. I even feel guilty. You see, DSLs have always been part of the Smalltalk farbic. It's natural to us because it's the way we have learned to code. I remember having the mantra "Code should read like a conversation" shoved down my throat until it became second nature. The cool thing is that there is a whole new generation finding out about this and doing it. Very cool.

I'm now promising myself to show non-Smalltalkers the other cool things that we have in our fabric and what we take to heart. The power of messages compels thee!

Groovy: Java 7?

Sometimes I wonder why they just don't make Groovy Java 7 (or even 8). I mean, c'mon! I think it makes a lot of sense. Closures and dynamic typing that is still understandable by most Java developers. I think it would be a step in the right direction. I know I enjoy programming in Groovy more than in Java.