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.

Sunday, April 29, 2007

Built-in Persistence/Transactions

We have long now been able to let the computer handle memory management in our programs via garbage collection. Why not let it also handle persistence and change management? I think these are things that should be built-in and it would be handled more easily by the virtual machine. There could be a low level API for hooking up different persistence strategies (relational, object, etc) and code would no longer have to be dirtied up with SQL or even worse HSQL. At the very least, change management of objects should be handled by the VM. How much easier would exception handling be if you could also rollback all the changes that had occurred and you could get back to the state you were in before the error? I think these should be the new primitives.

Gemstone is the realization of this on the server. It would be nice to make the code on the client as transparent as well. I know some might laugh at this idea, but I think it has merit. Just like garbage collection seemed strange at first, why not allow automatic persistent management as well?

Re: Make Debugging Tests Easy

Boris Popov left a comment on my post "Make Debugging Tests Easy":

Can you give a more specific example please? I don't see anything wrong with this, for instance,

| file |
file := self loadPaymentFile: self sample.
self assert: file validPayments size = 3.
self assert: file invalidPayments size = 1.

Well, I would probably change the file to a stream, but that's a different topic and discussion (I generally don't like to access outside resources in my test; they only cause problems later). Back to the conversation, the last two lines are what I don't like. The reason is that say another developer changes any of the code that gets called during the loadPaymentFile: and they run all tests. And let's say it's in common code and this test fails. Let's also say that we get back 2 valid payments and 2 invalid payments.

The developer is going to have no clue which one became invalid and what made it valid in the first place. You could put in comments explaining what the 3 valid payments and 1 invalid payment were to help. or you could break out and have several asserts for each of the cases. Otherwise, I have to revert code and rerun this test to see which payment is now incorrect. And then, put my code in and see where my code is incorrect. The above code makes the original intent hard to understand. Why were only 3 valid? Why was only 1 invalid and what made it invalid?

Really the above test is not incorrect per se, it's just not very thoughtful of the other developer's time. A couple of extra minutes of coding time would save the other developer a couple of hours. It's about coding and feeling sorry for the poor person that has to come behind you and figure out what you did. I try to always code with the maintainer in mind. Most times, the maintainer happens to be me and I'm always thankful I took the extra time to help myself.

Thursday, April 26, 2007

Omaha Dynamic Language User Group

This month's meeting is brought to you by the letters G and B. Brent Adkisson is taking time out of his busy schedule to show us the power of Google's new GData API. It's a safe bet that you'll be astonished and will can't wait to find a use for GData for yourself. Brent has been telling me all about the exciting things he has been discovering with it. This is one meeting not to be missed.

Pizza, drinks, and a special prize (just like a box of Cracker Jack) will be provided for by this month's sponsor's Tek Systems.

Free food and stimulating conversation make for an exciting Tuesday night! See you all there.






TopicGData
SpeakerBrent Adkisson
TimeMay 1, 7-9pm
LocationUNO's Peter Kiewit Institute (PKI) building
1110 South 67th Street
Omaha, NE

Tuesday, April 24, 2007

Make Debugging Tests Easy

One pattern I see over and over in tests is the assumption that the tests will always run to green. Now, you might think that's an odd statement right? I mean the whole point of tests is to make them run green, right? Well, in a way, yes. But, more importantly they are a communication device to help new developers understand your intentions. Too many times, I've seen assert statements that simply check a size of a collection. Sure, the tests pass, but what does that saw? Why that specific size for that collection? It's frustrating because when I see these things, it's obvious the developer never thought the code would break after the test was passing.

Think about it if I check that the size of a certain collection is 5. I can bet in 6 months the reason will be fuzzy. Of course, you could name the 5 as a constant and that would certainly make it more readable. It is a step in the right direction even. But, why 5? If I change code and I get back 7, what does that mean? A constant might help, but it might not. Be specific in what you check. Don't get lazy in naming or being general. Spell it out. It might take more effort now, but it will pay huge dividends when the test breaks. More than likely, when a test breaks after it is running that it is unexpected.

Feel sorry for the poor developer that has to change your code and then figure out your tests. Take as much care in your test code as your main code. You will be thankful later. Your tests will spell out exactly what's wrong, be easy to debug, and most importantly easy to be fixed again.

Thursday, April 12, 2007

Tiny Types, Abstract Data Types, And Little Objects

Darren Hobbs wrote about one of my favorite topics: Tiny Types. I call them abstract data type, but I like Darren's name better. The idea is the same. I think it's just good design. I once thought that tiny objects were too much as well. But, I now think tiny objects is the only way to go.

Tiny objects make unit testing easier, aid in reuse, stop duplication dead, provide for better messages when things do break, puts functionality closer to where it is used, and I could go on all night. The amazing thing is at first I started to use tiny objects to put constraint checking in so that it didn't get propagated everywhere. But, something strange happened. These tiny objects started to take on more functionality and have real protocols beyond just get and set of their values.

I think tiny objects are even more important in dynamic languages than in Java. They can make stupid programming errors easy to find and correct. Also, your functionality is spread across several single responsibility objects working in concert to provide complexity.

Tiny objects are good design period.

Tuesday, April 03, 2007

The Power OF Smalltalk Compels Thee

I've been talking with Edward Povazan lately and showing him Smalltalk to give him ideas for the Eclipse Groovy plug-in and he had some nice things to say here: Crazy Sensible Smalltalk - random ripples. I think us Smalltalkers forget what a unique experience we have inside of our tools. It's great to get someone excited about our world and show off what's possible. I'm hoping for great things to come for the Eclipse Groovy plug-in. ROCK!

Thursday, March 29, 2007

Java VM Puts Shackles On Development Tools

I love showing off Smalltalk. It never ceases to impress people with what you can do with it. One thing java developers find strange is no pauses in your work flow. What do I mean by that? Smalltalk compiles on the fly and immediately links in the new code. The time to compile one little piece is almost instantaneous to us. But, to developers not used to this environment, it feels weird. The Smalltalk IDE image comes up immediately (pick any Smalltalk and it's the same story). Strange, it takes a few minutes to even start up Eclipse. Smalltalk just feels like magic and we've been taught to mistrust magic.

But, this post is not about how foreign Smalltalk is to java developers, but how still in 2007 with dynamic languages finally getting recognition that few people are screaming for the capabilities of a Smalltalk VM. The productivity of Smalltalk owes not only to its dynamic nature, but to its always running and lively IDE. It's a living environment. Objects are alive and not dead. Why are there not other environments that do this? (OK, Lispers, I didn't forget about you...anyone else?) And why aren't these environments in the newer dynamic languages (Ruby, Python, Groovy, etc)? Have the shackles of the java runtime environment ruined us?

Or maybe the problem is just that we are always thinking of runtime and not development time. Java places a lot of barriers in the way of developers in the name of security. Why not have a specific VM purely for development? One that could dynamically load classes and code. One that could take snapshots of the running system and save the state for later. One that could compile incrementally and keep all of the bookeeping in order so that our tools stay snappy. One can dream.

Now, for Ruby and Python, there is no excuse. They have their own VM and why don't they support IDEs to implemented in themselves? Java, Groovy, and Scala have the excuse of the java VM. One of my hopes for Ruby was a Smalltalk-like IDE, but sadly, I don't think it will ever happen. The first step would be not to throw away the source code when they compile.

The thing that makes Smalltalk IDEs so cool is that they are alive. The VM supports object mutability and snapshotting state. The whole IDE is written in Smalltalk and is part of the live development system. You don't have to restart anything to try something out or shut down the everything to run a new tool. It morphs into what you want and let's you do what you want. No shackles.

This is what I want from the new generation of dynamic languages. I wonder how hard it would be to have a development java VM. Hmmm....

Omaha Dynamic Language Group

Has it already been a month? Wow. We have a stupendous talker this month, Axel Jenson. He will be presenting the us the new Flex framework and showing off the next verion of ECMAScript: ActionScript! This promises to be a talk that you will be talking about for months. I've heard it will make you instantly download Flex and try out all the cool things it has.

Want more? How about sponsorship from ProKarma, Inc. (eSymbiosis)! They will be providing us with a door prize, pizza, and drinks.

This is one exciting meeting that you can not afford to miss. I will see you all there!





TopicFlex/ActionScript
SpeakerAxel Jensen
TimeApril 3, 7-9pm
LocationUNO's Peter Kiewit Institute (PKI) building
1110 South 67th Street
Omaha, NE

Tuesday, February 27, 2007

Where Did Use Cases Go?

I've always liked use cases as an analysis/design tool. I was even the lead developer on a now defunct use case management tool. What ever happened to them? I never hear any one talking about them anymore. Sad really. They were an important part of the journey to understanding user needs. It made gathering easier as well as grouping functionality together. When done right, domain modeling was a breeze. Sure, you never got all of the use cases before design started, but at least you had a good idea of what the goals of the system are. I'm still shocked when I get on a team and the goals of what the software is to do is not clear.

It seems in the rush for agility that people threw away use cases as well. I don't know why. I think stories are a horrible mechanism for understanding. They are the lazy man's use case. Modeling the main domain objects and a good cut at use cases is crucial before you start coding. It will save countless hours. Now, this might seem un-agile. But, thinking about your problem and trying to get a good grip on it before you start coding IS agile. Writing use cases does not end when you start designing or when you start coding. It's a continual process. Use cases are needed to be not only for the knowledge of the developer, but also so that the client knows exactly what you are building. They are to be done together. And as any experienced developer will tell you, you never know everything about what you're building. Customers and developers need each other. Use cases are proof of that.

Use cases rock.

Omaha Dynamic Language Group

The great talks keep coming and this month we have none other than Matt Secoske talking about Domain Specific Languages (or as you might have read about: DSLs). This looks to be an all out blitz to the senses and one that will be talked about for ages. I think it's safe to assume, you need to get out and see for yourself. Matt will show how dynamic languages are perfect to implement DSLs in. It's at the same place we had last month and should be great. See you all there!





TopicDomain Specific Languages
SpeakerMatt Secoske
TimeMarch 6, 7-9pm
LocationUNO's Peter Kiewit Institute (PKI) building
1110 South 67th Street
Omaha, NE

Monday, February 26, 2007

Made it home...

I made it home and I was exhausted! But, I did write down some more ideas:
  1. Seats in the airport should double as beds. And they should be more comfortable.
  2. There should be a stock of pillows for people sleeping in the airport when bad weather hits.
  3. Lower volume on the intercom. In fact, get rid of the damn thing. It's annoying and there's only so many times I want to hear about "orange" security level. Place more terminals with good information and have it be up to do date. The biggest problem over the weekend was lack of information. Rumors ran rampant and a terminal with information would have stopped most of it.
  4. No leaning back chairs on airplanes. They are simply a BAD DESIGN. They are good for one passenger and bad for another. Either that or make more room on the airplane.
  5. Don't lie. If you don't know the answer, tell me. If the answer is unpleasant, then tell me. Imagine my surprise when I was told that my luggage was following me through the cancellations, but in fact, it is still in Memphis.
OK, that's all of the extra ideas. I think flying could be so much nicer. Everyone I talked to complained about security, but I think we are stuck with that situation. I know people will probably roll their eyes, but it was good to turn that negative energy into creativeness. It also got me thinking of other things as well. But, more on that later!

Saturday, February 24, 2007

Stuck in Memphis

I've been at the Memphis airport all day long trying to get home. The weather has not been nice. Hopefully, tomorrow I'll be able to get somewhere, but I'm thinking it might just be another day of waiting. I spent most of the day waiting in line when flights were canceled and it got me thinking. Instead of complaining about a bad situation, how would I fix it? So, I started to spend my time brainstorming ideas to make canceled flights easier on everyone. Here's my list:
  1. Create more than one line. I would divide them up by flexibility of travel plans. I notice a lot of time is spent with just a few passengers. You could use one line to determine what the needs are and then pass them on to more dedicated lines. This would speed things up for everyone on the whole.
  2. Updated information on the boards. Most of the problem is that you don't know what's going and there's no confirmation that you're doing the right thing. It's chaos. Some road signs would answer most people's questions (flight delayed - for how long - and yep, it's canceled and with the reason!).
  3. Send flight information to your cell phone for each of your flights. If it gets canceled and they automatically rebook, then notify me. If the default is unacceptable, then I'll wait in line. But, give me options. I'm thinking the default would the best for most people and reduce the line size.
  4. "Feed" the line. People are generally tired, cranky, and hungry. Pass out refreshments while they wait in long lines. It will keep the natives peaceful.
  5. Workout a deal with a local taxi company to pick up the slack to take people to the hotel. I waited an hour tonight just to get to the hotel.
  6. Workout a deal with the tourism department to show around town if their flight is canceled. They have time to waste and might want to venture out.
  7. Have shuttles from the hotel that take people to malls or Wal-Mart. Why? Because you don't have your luggage and might want a fresh set of clothes.
  8. Have private areas in the airport. I would spend money just to have a small place to prop up my feet and take off my shoes. I'm thinking something with walls and a Laz-E-Boy chair.
  9. Better food. Airport food is expensive and junky. Sometimes I would give anything for some vegetables and something healthy. How hard can that be?
Well, that's all I can think of right now on 2 hours of sleep. I'm sure I'll think of more tomorrow. Good night.