Saturday, October 11, 2008

Forced Pairing

Let's be honest. I'm not a big fan of "forced" pairing. I believe in active collaboration between cooperating team members. In other words, two people should pair if they want to. The energy of pairing is incredible when both partners are engaged and having fun. The code is better and so is the resultant design. It's the other side of the coin that I don't like and think the results are worse, even if the two programmers were working separately. A good pairing starts with the pair liking to work with one another. They don't have to see eye to eye, but they must enjoy the journey of working on code together. They will push and encourage each other to do better. A fun competition that will result in another problem being pushed past and the winner being a well-maintained system.

"Forced" pairing is what XP advocates and I see a huge problem with it. The reason is if the pair doesn't like or respect one another, the code quality will be on par with that of the worst of the pair. When pairs don't get along, one side will disengage. When this happens, you get none of the benefits. The team still thinks its safe from doing code reviews because they had four eyes on all code. Not so. To ignore the effects of "forced" pairing is to ignore that the team is human.

Sunday, August 24, 2008

Mentoring

One of the round table discussion at Des Moines Bar Camp was how to get students excited about our field. The discussion went from how to get students interested in non-coding aspects of software development like QA testing to finding the passionate students. One thing that I suggested was that we needed to mentor more. I think we need not only to mentor students, but people within in our industry.

Let's face it. There's no way to know everything about software development. I would even say it's impossible to know everything about Java (the number of frameworks and new ideas is overwhelming) which is a small part of the entire computing realm.

Getting back to mentoring students though. In the user groups that I attend, it's been rare to come across a student. We are they not coming? Could we be scaring them away? Are user groups too advanced? What?! I think it is none of those things. I just don't think we are marketing to them. How do we do that? I think simply putting up posters and targeting students is a start. Reaching out to teachers is another avenue. Embracing students who come to these meetings is also needed. We need to keep those passionate about what we excited.

Which leads me to that we need to mentor everyone. I've been blessed in my career to have several mentors and I try to be a mentor when asked as well. I want to give back to those that have given me so much. There's only so far that books can go. Experience is best handed down through mentorship. I think it also allows us to feel freedom to try out new things. As we move to move functional programming languages, wouldn't be nice to be mentored by the people with the most experience?

I would love to see our industry to move to an apprentice model. I think the caliber of developers, testers, and leaders would increase dramatically. We're an industry that is just starting to tap into networking (Bar Camps are excellent for this) and embrace sharing (open source). It's exciting times right now and I can see where everyone needs to be mentored. I'm always learning and love talking with people who have more experience in a technology. We need to keep the learning going.

I think the new social networking tools could be used to great effect for setting up these relationships. So, let's get together and start mentoring. Create the developers we would like to work with and be.

Bar Camps

In the past week, I've attended both the Omaha and Des Moines Bar Camps. At each, I gave my Seaside and advanced Javascript talks. The responses and turn out was incredible. Interest is growing in Seaside and Javascript is being viewed more as real language than a toy. It makes me a happy person. Everyone I met was passionate, articulate, and excited. I can honestly say that all of the Bar Camps I have attended thus far have been incredible. I've met many new friends and I can't wait to go to another. They are addicting! Hope to see everyone again! Check out my presentations page.

Wednesday, August 06, 2008

Update on Javascript

I've been meaning to write an update to my post on Javascript prototypes. Let me just show the updated code and then I'll explain what's changed.

Base = new Object();
Base.clone = function() {
var creator = function() {
this.constructor = arguments.callee
};
creator.prototype = this;
var result = new creator();
if (result.initialize)
result.initialize.apply(result, arguments);
return result;
}

Base.mixIn = function(properties) {
for ( var each in properties)
if (properties.hasOwnProperty(each))
this[each] = properties[each];
return this;
}

ZipCode = Base.clone().mixIn( {
initialize : function(standard, extension) {
this.standard = standard;
this.extension = extension;
},
toString : function() {
return this.standard + "-" + this.extension;
}
});

print(ZipCode.clone('56777', '4567'));

First thing you will notice is that I got rid of Object.prototype. I'll admit all of my recent Javascript code has been scripting on the server side. I do sometimes forget about all of the legacy code running on the browser(Adding properties to the Object.prototype can cause bugs in naive for loops). Not to fear, I created a Base object and put the clone and mixIn functions on it.

The next change is to the clone function where I introduced code that will setup the new clone if an initalize function is present. It calls the initialize function with the arguments passed into the clone function. I love doing things like this with Javascript.

Lastly, I had mixIn return itself. The reason is so that I could put the clone and mixIn on one line and only name the prototype once. This means I'm not duplicating the names of my objects and can more easily refactor the names. It also makes it easy to see the name and what prototype it is inheriting from.

I've always been infatuated with prototype-based programming languages. Javascript makes it possible to play with a real life prototype-based language. It saddens me to know that the next release of the standard introduces classes and that so many frameworks force classes into it. Once you get into using prototypes, you don't want to go back. You can use prototypes for a primitive versioning system, change tracking, and more that I haven't thought of yet. If you find more, let me know. Have fun using Javascript in new excting ways.

Sunday, July 13, 2008

Functional Programming Has Warped Me

Look at this method that I recently wrote in a class for describing my database. The responsibility of this method is to commit the current session (which is encapsulated from the user) after x number of database events (adds, updates, deletes, etc). I need his functionality because I was bulk inserting objects that I had read from an XML feed. Here's what I first came up with:

commitEvery: aNumber during: aBlock
| count |
count := 1.
[self session beginUnitOfWork.
aBlock value:
[count := count + 1.
count > aNumber
ifTrue:
[self session commitUnitOfWork.
self session beginUnitOfWork.
count := 1]]].
self session commitUnitOfWork

The method takes a one argument block that will be called with a zero argument block that when called will increase the count and decide whether to commit and start a new transaction if it has reached the number given. At the end, I commit whatever active transaction there is. The thing I like about this is that I put the logic of counting and when to commit in one place. Here's how it would be used:

populate
| db |
db := self new.
[db
commitEvery: 1000
during:
[:afterAdd |
ITunesSAXHandler readUsing:
(ITunesTracksHandler onEachTrackDo:
[:each |
db addTrack: each.
afterAdd value])]]
ensure: [db disconnect]

Notice how "afterAdd" is used. It is passed into the block that will handle all of the transaction adds. It is called after an item has been added. I like this code because it doesn't worry about anything, but adding things to the database. It also makes it obvious how often we will commit. But, I'm unhappy with commitEvery:during:. The reason is because it just seems like I could make it more generic and at the same time easier to test without resorting to mocks. I abstracted out the counting and put it as a method on BlockContext (this is Squeak):

duringDoEvery: aNumber onBegin: beginBlock onEnd: endBlock
| count result |
count := 1.
beginBlock value.
result := self value:
[ count := count + 1.
count > aNumber ifTrue:
[ endBlock value.
beginBlock value.
count := 1 ] ].
endBlock value.
^result

This turns our first method into this:

commitEvery: aNumber during: aBlock
^aBlock
duringDoEvery: 1000
onBegin: [ self session beginUnitOfWork ]
onEnd: [ self session commitUnitOfWork ]

It's a mini-DSL! Let's write a simple test. Note, this is not an SUnit test, it simply writes to the transcript. But, I wanted to show it without all of the assertions:

[:afterAdd |
| count |
count := 0.
10 timesRepeat:
[Transcript show: (count := count + 1) printString; cr.
afterAdd value]]
duringDoEvery: 5
onBegin: [Transcript show: 'begin'; cr]
onEnd: [Transcript show: 'end'; cr]

Gives this output:

begin
1
2
3
4
5
end
begin
6
7
8
9
10
end
begin
end

Everything looks wonderful until we hit the last two lines. It seems pointless and unnecessary to do a begin and end with nothing in between. Our code will need to get a little bit more complex. Here's my next try:

duringDoEvery: aNumber onBegin: beginBlock onEnd: endBlock
| count result hasBegun |
count := 1.
hasBegun := false.
result := self value:
[ :eachBlock |
count := count + 1.
hasBegun ifFalse:
[ beginBlock value.
hasBegun := true ].
eachBlock value.
count > aNumber ifTrue:
[ endBlock value.
hasBegun := false.
count := 1 ] ].
hasBegun ifTrue: [ endBlock value ].
^ result

It's more complicated. And now, I'm passing another block around to get its value. The reason was because to properly remove empty begin/end combinations, I needed to know when the before was and when the after was. This means passing a block to the afterAdd from before. So, now the test code looks like this:

[:onEachAdd |
| count |
count := 0.
10 timesRepeat:
[onEachAdd value:
[Transcript show: (count := count + 1) printString; cr]]]
duringDoEvery: 5
onBegin: [Transcript show: 'begin'; cr]
onEnd: [Transcript show: 'end'; cr]

I renamed afterAdd to onEachAdd which is a better name and indicates its role better. Now, the reason I wrote this post is that I sat back and went, "Wow. I have something easily testable, but might hurt some brains." My next thought was, "Why would this hurt someone's brain?" The answer is all of the indirection of the blocks. I will be quite honest at this point, I would normally start turning all of these blocks into objects and have better names for what they were doing. Blocks worked perfectly in this context and if you think about it. This code is not much different than what Collection>>streamContents: does.

This is one of the things that learning functional programming has done to me. The above code looks and feels natural. Passing a block into a method that will accept another block doesn't bother me at all. I love the DSL-like nature of the implementation too, but I can see where it might confuse (Hell, inject:into: still does). This is where objects come in because now we can create our small objects with more meaningful names than just value or value:, this will at least make the indirection less painful. Thought this was fun exercise to show off something else that you can do with higher order functions. Squeak on.

Monday, June 30, 2008

Too Complex?

There's a lot of features of Ruby that I like, but there are some that just drive me nuts like blocks not taking blocks and the ampersand operator. Raganwald did a great job of explaining blocks, procs, and the ampersand in this blog post: Explanation of Ruby's Unary operator. I came away with the feeling, "Wow! It took that much explanation just to tell how to send blocks around?" If blocks were first-class citizens, Ruby would be more elegant. Raganwald would not be writing huge blog posts on block vs. proc because it would be unneeded.

Ruby has all it needs right now. Ruby 2.0 should be a pruning of features and removing special cases. Get to the things that help you concentrate on your design and not on the language. Ampersand is nothing more than noise in your code and brain. Remember elegant is simple.

Sunday, June 29, 2008

Weakest Link

"The deliberate use of a weak element that will fail in order to protect other elements in the system from damage." - Universal Principles of Design

Unit tests could be seen as a form of weakest link in that we want the system to fail in our tests instead of in our production environment. Pre-condition and post-condition assertions (remember Bertrand Meyer don't you?) are the perfect example of weakest links in software design. The assertion fails, then the program stops or does something intelligent about the detection: logging the anomaly or dropping an incorrect record. We have more options available to us when our weak link fails in software than other domains. I would even put exception handling under the weak link design umbrella.

So, why don't we use it more? It's rare I see pre-condition assertions at all. I know the performance overlords declared them to be bad. But, when you have Rails running high traffic websites, does a few extra assertions really matter? I think not. I would rather have my program run slower with safety belts than doing something catastrophic with my data. Brian Foote once gave a talk where he equated pre and post conditions to the goalie in a game of hockey. And asked the question, "Would you want to play with or without the goalie?" It's a statement that's lived with me since.

With that being said, are they places in your current design that could use a few more fuses?

Sunday, June 22, 2008

My Hopes For Ruby 2.0

I must admit I haven't been following Ruby 2.0 too closely lately. But, I since I've been using 1.8 quite a bit lately. I thought I would list the things that are in 1.8, but I hope are gone in 2.0. This is a prayer of good vibes.

  1. Make blocks first class citizens. So, no more & in your methods. Everything should be an object. Blocks are no exception in fact, they have more right than anyone. This will make blocks syntactically cheaper too. No more "lambda". Happiness is cheap syntactic blocks.

  2. Reflection on everything. Yes, this means the stack. It also means keep the source in memory as well as part of classes and blocks. This might could used for a lot of cool things (like interesting ways to traverse code). Don't worry. It doesn't add much memory.

  3. Make blocks accept the same kind of parameters as methods. Right now, you can not have methods take an implicit block (you know with the & in front). Wait a minute. If number one is satisfied, this will be too. Oh goody. Cheap blocks take away complexity. Isn't this reason enough to have them?


OK, that's it for now. The above things would make life so much easier. I could lobby for taking away case statements and most keywords, but I think the above would be great to take the language forward without hurting too much.

Saturday, June 14, 2008

Five Years

I can't believe it. I missed my fifth anniversary for blogging! I started out in 2003 to be a public diary for my technical side. I've enjoyed doing it and plan to do so for many years to come. It's just too much fun to read through all of the posts and remember where I was at during that point of time.

Monday, June 09, 2008

Twitter

I've joined the modern age. I'm now on twitter. I know, I'm behind the curve. See you there!

Tuesday, May 27, 2008

Yet Another Seaside Talk

At the next Omaha Dynamic Language User Group, I will be speaking on Seaside. If you missed my talk at the BarCampKansasCity, you can catch it now. I will be showing how to build web applications with the best web framework out there. Expect lots of simplicity and heretical statements.

Change of Plans

Due to a change in plans, I will not be attending the Chicago Lisp Workshop.

No, I'll be there. Things looked bleak this morning, but I'm all clear now. Amazing what a day can do.

Thursday, May 22, 2008

Chicago Lisp Workshop

I will be in Chicago on May 31 to participate in this Lisp Workshop. It should be more fun than one person is allowed to have. A weekend of Lisp sounds nice doesn't it? See you in Chicago.

Reading other people's code is good

Reading other people's code is the needle lost in the hay buried deep in this article entitled "Language Dabbling Considered Wasteful". Forget the dreadful title that makes my eyes roll back in my head. It's still too close to Dijkstra's famous paper. But, I digress. This is not a pointless rant on over abused trivia.

If you want to become a better programmer, read code and understand it. There's no way around it. Read code, experiment with it, and figure out if you like it or not. Bad code can teach just as much. It's no fun to read, but it shows how not to do things. The danger with bad code is being picking up incorrect habits. Get into the practice of reading code and not the Javadocs. If you're learning a new language you will see the idioms and be able to apply them. Plus, you will know how to find how things work underneath the covers if you run into a super thorny issue.

Yeah, give me the source any day. I love reading code and it's how I learn. Once I get past the basics, I start reading and understanding others code. I will say it again, there are no shortcuts.

Sunday, May 18, 2008

And we wonder why we are one of the most hated careers

This is a shame: No Dashs or Spaces. We should be helping and not being a road block. I know I've cussed at a few of these sites listed. Sometimes I think we should put ourselves in the shoes of our customer and think, "What would make their life easier?" We should make it as easy as possible for a user to achieve their goals. The computer should disappear and only the problem at hand should be on the user's mind. We still have a long way to go. Let's start being more empathetic. The users are people too.

Situated Web Application Platform

Pete Thomas presented "Situated Web Application Platforms" at BarCampKC. The talk was wonderful and it made me think about current IT solutions. A talk ensued after his wonderful presentation about Excel, email, agile methodologies, and enterprise development. It was pondered why business users embrace Excel and email and are reluctant to move off of them. The alternatives, SWAPs, are clearly superior, so why stick with cruder applications? I reasoned because Excel and email were good enough. Why would they want to learn a new tool if the current one fulfills their need? They are not computer people and would rather be solving problems than wasting time in front of a computer. Their passion and strength is not in development, but solving business problems. We should embrace that. While this might startle us because we wouldn't stand for it (I know I would not want to merge data from a bunch of Excel spreadsheets into one, but my passion is different).

So, why fight and try to replace Excel? We need to change our thinking and embrace it. It could help with requirements gathering. It could help us find the missing pieces in our software. We are always on the lookout for solving problems with technology, but in this case, we should be asking our users why they have the need to use Excel. What else could we do for them. It's time for us to stop mindlessly implementing what the customer tells us and figure out what their true goals are and solve those.

Wednesday, May 14, 2008

Standards Gone Wild

There was a discussion recently on standards where one poster said that they were big on alignment. Here's an exchange:
Hi__ jwen,

jhdn> Simple solution: set in your coding standards that ALL
jhdn> classnames MUST be a specific length, and also dictate specific
jhdn> lengths for all member variables, method names, etc. etc.

Hmmm_, I___ thnk that mght caus more prbs, mayb even a___ rvln from
the_ devs. Not_ to__ mntn that it__ lmts your cr8v ablt to__ use_ good
nams and bild a dict* that hlps bild betr apps.

Grgg

* I Just couldn't come up with a four letter substitution for
"vocabulary". :)

Classic. I laughed coffee through my nose. It hurt, but was well worth it. I'm glad I don't work somewhere they have standard on the size of my variables. I don't think I would be working there much longer.

Tuesday, May 13, 2008

Javascript: Stop Fighting It

I recently came to the realization that I've been fighting Javascript too much. It's because I've been going against the grain with it. It's like trying to force the OO paradigm in a functional language or the opposite. You might say that I've been treating Javascript like an OO language and you would be right. But, I've been forcing my class-based thinking on it and it's been not so nice.

I've been reacquainting myself with Self and Io again. And it hit me like a rhino slamming into me. I've been doing Javascript all wrong. I should have treating it like the prototype-based language that it is. Sure, it doesn't have the ability to inherit from multiple prototypes like Self, but the way to succeed is with prototypes. Forcing class-based OO is like walking up the rainbow and finding no pot of gold at the end.

First, let's write the following:
Object.prototype.clone=function() {
var creator=function() { this.constructor=arguments.callee };
creator.prototype=this;
return new creator();
}

Object.prototype.mixIn=function(definitions) {
for (var each in definitions) if (definitions.hasOwnProperty(each)) {
this[each]=definitions[each];
}
}

It's just two methods up on the Object prototype. Why clone is not part of the Javascript standard is beyond me. Clone is required in all the other prototype-bases languages I have seen. It is the only way to create new objects. Enough complaining, it was only a few lines of code. All my clone method does is make the object I call it on the prototype of the result. I get a clean object with all of the properties of the receiver inherited. Nice. This is the behavior we want. Next, I added a convenience method to Object to mix-in in other objects. This is helpful to keep my code organized. I can just create a hash object with my functions and properties like before. So far, this is standard stuff. But, here is how I use it:

Pounds = new Object();
Pounds.mixIn({
of: function(value) {
var result=this.clone();
result.value=value;
return result;
},
toString: function() {
return this.value.toString() + " lbs";
},
value: 0
});

print(Pounds.of(5)); // => 5 lbs
print(Pounds); // => 0 lbs
print(Pounds.isPrototypeOf(Pounds.of(5))); // => true

Notice, normally, you define the constructor with the first letter of the name upper cased. I no longer need the constructor, so I upper case on the prototype that will be the example for all the instances that I clone off it. The example above is a measurement class. "Pounds" is my example so I default it with values that the objects that I clone from will have. This is how prototype-based languages work. It feels slightly unusual coming from the class-based background, but I think it makes my Javascript look a lot less alien. I like it.

Let's look at a more complicated example shall we?

Animal = new Object();
Animal.mixIn({
name: "Unknown",
sound: function() {
return "?";
},
toString: function() {
return this.name
+ " goes " + this.sound()
+ " and weighs "
+ this.weight.toString();
},
weight: Pounds.of(0)
});

Cat = Animal.clone();
Cat.mixIn({
name: "Unknown Cat",
sound: function() {
return "Meow";
},
weight: Pounds.of(10)
});

grendel = Cat.clone();
grendel.mixIn({
name: "Grendel",
sound: function() {
return this.constructor.prototype.sound.call(this) + " and Purr";
},
weight: Pounds.of(20)
});

gracie = Cat.clone();
gracie.mixIn({
name: "Gracie",
sound: function() {
return "Purr";
}
});

print(Animal); // => Unknown goes ? and weighs 0 lbs
print(Cat); // => Unknown Cat goes Meow and weighs 10 lbs
print(Animal.isPrototypeOf(grendel)); // => true
print(grendel); // => Grendel goes Meow and Purr and weighs 20 lbs
print(gracie); // => Gracie goes Purr and weighs 10 lbs

"super" is implemented with "this.constructor.prototype". It seems wordy, but prototype on the object is not built-in to Javascript. Besides, you should use "super" sparingly. To me, this reads better and works better for inheritance. I have dropped all references to classes. This makes meta-programming easier as well (I simply walk up the prototype chain with "this.constructor.prototype" and iterate through the properties.

The constructor function used as a class always seemed awkward to me. It was inelegant, but the above fits Javascript coding better. The reason is because I'm now using it as a prototype-based language and not forcing class-based OO on it. The above is meant to get started playing around. Prototype-based programming is so cool and I'm still exploring all of the possibilities. There's little documentation, but the little that is well worth the effort to track down. Have fun!

The example above was tested in SpiderMonkey. A great little REPL for playing with Javascript.

Two years after XP

I feel like I can finally write about my XP experiences. I was once a member of the largest XP teams in the country for three years. The XP practices were the main reason for me joining the team. I had been experimenting with agile at my prior work places with great success, but no one wanted to jump in. I found this team and they were up to their necks in it. I loved the thought of it. The people were passionate, caring, and intelligent. What could go wrong?

Nothing went wrong. But, I'm a bit of a skeptic now when some company touts agile to me now. I'm a bit shell-shocked. How could this possibly happen? I'll just list them. Don't worry it's only a few.

  • Everyone owns the code

  • In theory, this sounds wonderful. It really does and I think it works on a small team of 3-4 dedicated developers. It doesn't scale beyond that. The 3-4 developers must be dedicated to keeping the code clean too. If someone fails to clean up ugly code, then it quickly turns into glue. It turns against you if everyone thinks that everyone else will do the cleanup. There are plenty of negatives to personal code ownership, but the point is to have at least two people as masters of each section. Multiple eyes should see any code commit. But, someone or a pair should own it.
  • Mandatory pairing

  • Pairing sounds so good on paper, but it completely takes away the human element. Programmers are introverts by and large. Pairing can wear out some people quickly. I found forced pairing tiresome because not all folks get along. There were some people that I would enjoy pairing with and I learned a lot from. I would always want to pair with them, but other folks it was a constant struggle. I think pairing should be an optional activity that developers should naturally want to do when brain storming or checking in code. I find that code reviews with a pair of eyes who have never seen the code that I am checking is always a good thing. This should be done often. If you think about it, what I am describing is collaboration. Pairing to me as a term basically means one side can turn off. Collaboration is where both sides are equally engaged.

You will notice I didn't list test-driven development above. If anything, XP got that one right. I write tests for everything and stand behind them. I don't see how anyone can stand behind their work without them. I even write tests for my research code. I'm still 100% agile, but I think each practice needs to be tailored to your team. Don't blindly follow the book. If something hurts, don't keep picking at it. You might lose the limb and your project.

This is only the beginning. I plan to write more the subject.

Monday, May 12, 2008

My Passion

I guess I don't conceal my passion and love for Smalltalk very well:
...seeing Blaine’s eyes light up every time he got to either hear or utter a sentence that included the word “Smalltalk”.

To me, Smalltalk defines elegance. If you want to see elegance in computing, go download Squeak right now. The very least that will happen is it will warp your mind and make you a better programmer. It might even make you see the world a little differently.

Seaside Presentation

Just a reminder I have my Seaside presentation (scaled down a bit from the BarCampKC one ala no database mappings) and my Smalltalk Coding competition (100% Seaside) here. So, if you missed the presentation, feel free to download the Seaside presentation image and the coding competition. Lots of good examples to pour through in each. I'm going to try to put instructions with the new presentation and get it published. But, in the meantime, you can check out these older (not that old) materials. I will also remind folks to read Introduction to Seaside. It's a great and fast introduction into the coolest web framework on the planet!

BarCamp KC

I attended and presented at my first BarCamp this weekend. What a blast! I would like to thank Pete for putting on such a wonderful event. I'm always in need to mingle with brilliant folks and BarCampKC had them in spades. I enjoyed the discussions on Ruby, Situated Web Application Platforms, UML, customers, and of course, Seaside. It was well worth the 3 hours to attend and I would do it again in a heartbeat. My only wish is that it had been longer. I'll be making some more blog posts based on discussions had. If anyone has the chance to attend a BarCamp, please do. I know I made several new friends over the weekend.

And what would you know? No sooner that I have unpacked my bags and there's a webpage for BarCampOmaha. You can count me in being there and presenting something. Perhaps this time, I will give my Advanced Javascript talk (ran out of time in KC) or maybe I'll do something completely different. We'll see. I'll be having lots of fun this summer.

Sunday, May 11, 2008

Quote that describes OO perfectly

I grabbed this from Io Language Guide:
In all other languages we've considered [Fortran, Algol60, Lisp, APL, Cobol, Pascal], a program consists of passive data-objects on the one hand and the executable program that manipulates these passive objects on the other. Object-oriented programs replace this bipartite structure with a homogeneous one: they consist of a set of data systems, each of which is capable of operating on itself.
- David Gelernter and Suresh J Jag

I couldn't have said it better myself. It's not what Paul Graham says at all. I can't help it if he never took the time to understand it.

Lost The Fight

You know you've lost the fight when you make direct attacks on your competitor on your front page. Do you see google slinging mud? You don't have to sling when you're so far in the lead. Only the company in 2nd place needs to do those things.

Friday, May 09, 2008

Seaside at Bar Camp Kansas City

If you are in Kansas City tomorrow and want to learn more about Seaside, then come to BarCampKC. I will be giving a presentation on Seaside. It's the one you can download from SqueakMap, but beefed up. I've included how to do GLORP, script.aculo.us, and more! I will be showing off Smalltalk and Squeak in the process. If you ever wondered why Smalltalk was so cool, now is the time to find out. See you there!

UML, Design, and Paper

Why did the UML design tools fail? By fail, I mean never gain popular acceptance. To this day, I still do my designs by hand and then do them in a drawing tool when they are solidified. The UML tool makers never understood that when designing, you need to be able to make mistakes and explore different options. Instead, they forced you to make decisions too early in the process so they could auto-generate your code. I always found it cumbersome and they got too much in the way. And that's why they failed. I love paper. All of my friends that design still use paper for their designs as well. The reason is that you can try out ideas and the design can always be thrown away. Design is an exploration journey. The tools only looked at the destination and not how to make the journey easier. The journey is what mattered.

Tuesday, May 06, 2008

Comments on Binstock on Software: Perfecting OO's Small Classes and Short Methods

OK, when I originally linked to Binstock on Software: Perfecting OO's Small Classes and Short Methods, I had not read the comments. Wow. Varied opinions and were a lot of fun to read. I would like to comment on a few.

One mentioned using automated enforcement software to make sure developers abide by these rules. I used to love this idea because I would run those tools over my own code. But, once I made it public what I was doing, my fellow developers would figure out ways around it. It's human nature. Now, I keep those tools to myself and use them on my own code. I think code beauty is a personal thing and strict enforcement to one standard is an open rally call to defy it. The end result is code that is worse than it was before.

Secondly, I took the rules to be a an exercise to limit your code in extreme ways so that the power of the message send comes through and the ugliness of data structures is exposed. The point is let go of central control in your objects. For that, I think this exercise is gorgeous.

Lastly, I think the recommendations are things to strive for. It makes you code more readable, testable, and flexible. Who wouldn't want to strive for those things?

I cried

I almost cried for joy when I read this post on one of my favorite topics: Small Classes, Short Methods. Someone has been reading my mind. I love the set of rules. It's something that I strive for in my code. I've run into problems with other developers though (they generally think I am nuts when I wrap things like phone numbers, ids, domain specific codes, etc into objects instead of strings). But, by wrapping the primitive into an object that states it's role, you start moving logic closer to where it belongs. The books "Genius Within" and "Prefactoring" were the books that really brought this home for me (especially "Genius Within"). Lots of great advice. Go read it now!

Monday, April 14, 2008

Missing Explanations

I was looking over my last post and forgot that I didn't discuss these two methods below:
Function.prototype.everyTimeButFirst=function() {
var self=this;
var toCall=function() {
toCall=self;
return null;
};
return function() {
return toCall.apply(this, arguments);
};
}

Array.prototype.toString=function() {
var result="[";
var addComma=function() { result = result + ", " };
var addCommaOnlyAfterFirst=addComma.everyTimeButFirst();
Array.prototype.each.call(this, function(every) {
addCommaOnlyAfterFirst();
result = result + every;
});
return result + "]";
}

It might seem a little overkill to have the everytimeButFirst function, but I think it reads better in the method and communicates the intent. Normally, you could implement putting in the comma in between items in the collection like so:

Array.prototype.toString=function() {
var result="[";
var shouldAddComma=false;
Array.prototype.each.call(this, function(every) {
if (shouldAddComma) {
result = result + ","
} else {
shouldAddComma=true;
}
result = result + every;
});
return result + "]";
}

It's a little bit longer. I hate the boolean variable "shouldAddComma". I really do. It just doesn't read well. It's hard to see what's going on. The naming makes it better. But, it's just adding unnecessary noise.

But, all is not well in the first version that I used either. Not all programmers are versed in functional programming, but even a functional programmer would scoff at the first version. Why? It changes state. Plus, the implementation of everytimeButFirst while clever would not be obvious. Basically, what you're seeing is my experiment in using nothing but functions instead of a boolean. Fun for blogging and brain stretching, but not for production systems. Clever is the enemy of the maintenance programmer. But, what if we did this:
Function.prototype.everyTimeButFirst=function() {
var shouldExecute=false;
return function() {
if (shouldExecute) {
return toCall.apply(this, arguments);
} else {
shouldExecute=true;
return null;
}
};
}

You might say I just displaced the boolean to somewhere lese and you would be right. But, I got it out of the method toString which is where I didn't like it. It's safely behind a wall where it makes sense to have. The internal implementation of everyTimeButFirst was too clever the first time around. It is still using higher-order functions, but one is easier to understand than nested ones that change themselves out.

Remember I said the original implementation would make a functional programmer gag because of the side-effects. We could make it side-effect free by making it recursive. But, Javascript is not optimized for tail-recursion. So, I did what I thought was best.

Sunday, April 13, 2008

"Super" was wrong

My implementation of "super" was wrong. I did an implementation in this blog post. It was wrong for several reasons. The number one reason was because it was too complex. The first hint that it was too complex was when I was setting the "constructor" property manually. This is done for you and only needs to change if you set the constructor's "prototype" property with "{}" or "new Object()". I was guilty of the this sin. Turns out if I play by the rules, I don't need the "subclassFrom" function nor do I need to add the special "super" properties. It's actually less verbose and it's playing by the Javascript rules. When in Rome, do as the Romans.

My second mistake was that I thought each object had an immutable property "prototype". This is why I was getting "undefined" when I asked for it. I should have known that I was wrong and not the implementation. Anyway, my belief was WAY WRONG. I don't know where I got this piece of mythology from. I think I pulled it from the sky. The truth is that the "prototype" property is only on Function objects. It's set on the objects it constructs and it is not available. Mozilla and Adobe implementations have a property "__proto__" that stores it, but it is not in the standard and thus, not to be used. All objects by the standard should get their prototype from their "constructor" property. Learn something new everyday.

For the new implementation, I got rid of the "subclassFrom". It's not needed now and I'm only left with the "methods" function from before. It now simply moves properties from one object to another. It's only for syntactic shorthand now. I did add something new: function "proto". It's "super" basically. Here's the implementation:

Function.prototype.methods=function(funcs) {
for (each in funcs) if (funcs.hasOwnProperty(each)) {
this.prototype[each]=funcs[each];
}
}
Object.prototype.proto=function() {
return this.constructor.prototype;
}

So, how do you do super by playing by the rules? Here's how:
Function.prototype.methods=function(funcs) {
for (each in funcs) if (funcs.hasOwnProperty(each)) {
this.prototype[each]=funcs[each];
}
}

function Base() {
print("base constructor called");
}
Base.prototype.toString=function() { return "aBase"; }

function Sub() {
this.proto().constructor.call(this);
print("sub constructor called");
}
Sub.prototype=new Base();
Sub.prototype.toString=function() { return this.proto().toString.call(this) + " and aSub"; }

Output from the above:
base constructor called
********
base constructor called
aBase
********
base constructor called
sub constructor called
aBase and aSub

Notice the "this.proto().constructor.call" in the Sub constructor function, it expands to "this.constructor.prototype.constructor.call". This is calling the "super" constructor. We could also do "arguments.callee.prototype.constructor.call" instead, but really it's a lot to type in isn't it? We also couldn't put that into a function as easily without calling "arguments.callee".

I got a better implementation and something that's more like Javascript. I like keeping my Javascript close to what a Javascript developer would expect. Prototype-based programming is powerful and it's worth exploring things without classes. But, that's a small digression. All I wanted was super and some shorthands for grouping my methods. I have that now.

Annotations and Aspects in Javascript

Here's the moment, I've been building up to:
var logAround=function(func,name) {
this[name]=defineAround(function(proceedFunc) {
print("before: "+name+" "+Array.prototype.slice.call(arguments,1));
var result=proceedFunc();
print("after: "+name+" "+result);
return result;
}, func);
}

var doesItLog=function(each) {
return each.log == true;
}

Transaction.prototype.eachFunction(logAround.onlyWhen(doesItLog));

var test=new Transaction();
test.begin();
test.commit();

Here's the output:
js> load("aspect.js")
before: begin []
begin
after: begin undefined
before: commit []
commit
after: commit undefined

Not much to explain at all. I think the code speaks for itself. The output shows the arguments passed in and what the results were from the call. I didn't return anything from either method, but it wouldn't be hard to verify that it does indeed work. I implemented my own "toString" for Arrays to print out the arguments and it's worth looking at. "arguments" is not an array, but we can call array functions on it. Most of the built-in Array functions can be called on any object. You just have to use the wordy "Array.prototype.functionName.call" to use it.

I wrote this for this blog post, but I'm planning on beefing it up with exception handling and un-weaving among other things. I also plan on adding more tests to my test suite that I did not show. The purpose was to show some cool tricks in Javascript and I hope it was fun.

And here's the entire implementation once more:
function defineBefore(beforeFunc, proceedFunc) {
return function() {
beforeFunc.apply(this,arguments);
return proceedFunc.apply(this, arguments);
};
}

function defineAfter(afterFunc, proceedFunc) {
return function() {
var result=proceedFunc.apply(this, arguments);
afterFunc.apply(this,arguments);
return result;
};
}

function defineAround(aroundFunc, proceedFunc) {
return function() {
var args=Array.prototype.slice.call(arguments,0);
args.unshift(proceedFunc.bindTo(this));
return aroundFunc.apply(this, args);
};
}

Function.prototype.bindTo=function(thisObject) {
var selfFunc=this;
return function() {
return selfFunc.apply(thisObject, arguments);
};
}

Function.prototype.everyTimeButFirst=function() {
var self=this;
var toCall=function() {
toCall=self;
return null;
};
return function() {
return toCall.apply(this, arguments);
};
}

Function.prototype.onlyWhen=function(ruleFunc) {
var self=this;
return function() {
if (ruleFunc.apply(this, arguments))
return self.apply(this, arguments);
}
}

Object.prototype.each=function(everyFunc) {
for (var name in this) if (this.hasOwnProperty(name)) {
everyFunc.call(this, this[name],name);
}
}

Object.prototype.eachFunction=function(everyFunc) {
this.each(everyFunc.onlyWhen(function(every) {
return every.constructor == Function;
}));
}

Object.prototype.run=function(func) {
func.call(this);
}

Object.prototype.define=function(name, annotations, func) {
this[name]=func;
annotations.each(function(each, name) {
func[name]=each;
});
}

Array.prototype.each=function(everyFunc) {
for (var index=0; index < this.length; index++)
everyFunc.call(this, this[index], index)
}

Array.prototype.toString=function() {
var result="[";
var addComma=function() { result = result + ", " };
addComma=addComma.everyTimeButFirst();
Array.prototype.each.call(this, function(every) {
addComma();
result = result + every;
});
return result + "]";
}

Annotations in Javascript

Last post, I talked about how to implement crude aspect advices. I say crude because the implementation would need to be beefed up a bit for wider use. The ideas were more important. I wanted to spend the article on the tricky bits of implementation. I'll take the same tactic with this article.

Let's start with what our code will look like. In fact, let's implement something everyone is familiar with: a transaction. Now, our transaction will have a blank implementation (we'll print out the important bits). It's the API that we will care about later. Here's the definition:
function Transaction() {
}
Transaction.prototype.run(function() {
this.define(
"begin",
{log: true},
function() {
print("begin");
});
this.define(
"commit",
{log: true},
function() {
print("commit");
});
this.define(
"rollback",
{log: true},
function() {
print("rollback");
});
this.toString=function() {
return "i am transaction";
}
});

OK. There's some new functions named "run" and "define". I'll show their implementations soon. You can probably guess the implementation of "run". It's simply so that my hands don't get tired typing "Transaction.prototype". I could use "with {}", but I have found its implementation inconsistent among Javascript dialects. The next new function, "define", is how we're going to define our annotations. It's a shorthand for better readability and to reduce duplication. All it will do is add the function to our object and add the annotations as properties. Annotations are simple in Javascript because functions are just objects and we can add anything we want to them. How cool.

Here's the implementations:
Object.prototype.run=function(func) {
func.call(this);
}

Object.prototype.define=function(name, annotations, func) {
this[name]=func;
annotations.each(function(each, name) {
func[name]=each;
});
}

Both are straightforward. But, I introduced another function: "each". Those familiar with Ruby will notice what it does right away. For the non-Rubyists, it iterates over all the properties of the object. My implementation also sends the name of the property as an extra parameter. Here's how I did "each":
Object.prototype.each=function(everyFunc) {
for (var name in this) if (this.hasOwnProperty(name)) {
everyFunc.call(this, this[name],name);
}
}

It basically allows me not to have a "for" loop. Simple. You might have noticed my use of "call". The reason is because I wanted to pass along "this" to the function passed in.

That is it for implementing annotations. The query language is already built in (albeit a little verbose). We only have to iterate over the functions of an object. Here's some code I would like to use to test my annotations and query implementation:

var every=function(each,name) {
print(name);
}
var doesItLog=function(each) {
return each.log == true;
}
Transaction.prototype.eachFunction(every.onlyWhen(doesItLog));

Oh boy. Can you guess the output from the above? Here it is:
begin
commit
rollback

The annotations I have is to mark a function to be logged on entry and exit. I'll spend the rest of the article on the implementation and bring together the annotations, aspects, and logging in the next article.

Let's talk about the new functions: "onlyWhen" and "eachFunction". I think you can guess what each of them do. "onlyWhen" is defined on a function and takes a function to check the arguments for some condition. If the condition is true, it executes the receiver function. It returns a function that brings all of this together. This is more functional programming at work. "eachFunction" takes a function that will be called for each function that is a value of a property on the object.

Like always, here's how I implemented them:
Function.prototype.onlyWhen=function(ruleFunc) {
var self=this;
return function() {
if (ruleFunc.apply(this, arguments))
return self.apply(this, arguments);
}
}

Object.prototype.eachFunction=function(everyFunc) {
this.each(everyFunc.onlyWhen(function(every) {
return every.constructor == Function;
}));
}

In the "onlyWhen" implementation, I have to bind "this" (the function) to self so that we can use it later in the function that we use a result. "this" will be bound to a different object. "eachFunction" brings together the functions "each" and "onlyWhen".

That's it! You could of course add implementations to define annotations so that we make sure that only pre-defined ones are used in functions. I'll leave that as an exercise to the reader. It wouldn't take much to implement it. The next article will put everything together. All we have to do now is weave based on rules. We have the means to iterate over functions and we have the means to replace implementations through our advices. The next article will mix this batter.

Friday, April 11, 2008

Aspects in Javascript

Just like I promised! I'm going to describe how to do aspects in Javascript. Now, this example will be simplified. You will probably want to beef up the implementation given here. I'm really showing off an idea and how you can apply it to your Javascript libraries. I did this for fun and was shocked how easy it was. In these examples, I will be using Spidermonkey.

I'm first going to show off how to implement advices. Let's start with "before" advice and then have a simple test for our implementation. I would recommend using JSUnit for testing. I'm simply going to output it for demonstration purposes.

The easiest advice to implement is "before". All we need to do is define a function that creates a new function that calls our before function and then calls the function we originally wanted to call. "defineBefore" handles this quite nicely. The rest of the code below is defining our "before" advice and the function we want to call and then doing the wrapping. Pretty simple.

function defineBefore(beforeFunc, proceedFunc) {
return function() {
beforeFunc.apply(this,arguments);
return proceedFunc.apply(this, arguments);
};
}

function printArg(x) {
print("proceed: " + x);
return x + 1;
}

before=function(x) {
print("before: " + x);
}
printArg=defineBefore(before, printArg);
print("result: "+printArg(6));

Here's the output:

js> load("aspect.js")
before: 6
proceed: 6
result: 7

You can see from the results that our "before" advice implementation can look at the arguments (but, not change them, we'll get to that). And be basically benign to the whole operation. Our weaving works!

"After" advice is equally as easy. We just need to remember the result and return that from our weaved function. Again, the "after" function will be benign and not be able to change the result. Here's the implementation:

function defineAfter(afterFunc, proceedFunc) {
return function() {
var result=proceedFunc.apply(this, arguments);
afterFunc.apply(this,arguments);
return result;
};
}

after=function(x) {
print("after: " + x);
}
printArg=defineAfter(after, printArg);
print("result: "+printArg(8));

Here's the results:

js> load("aspect.js")
before: 8
proceed: 8
after: 8
result: 9

Now, our "before" and "after" advice weaving did not allow us to change the arguments or results. I wanted to keep it simple without a lot of complications. If we need to change the arguments or tamper with the result, let's do it with an "around" advice.

The implementation for "around" is a little bit more complicated. I want to make calling the proceed function as simple as possible in the after advice function. To do this, I need to wrap the proceed function with another function that will bind the "this" so that we don't have to worry with sending "call" on the proceed function. The implementations before didn't have to deal with the proceed function in the advice and that made life easier. Now, we'll have that control and with that power, comes the ability to change arguments and results. Here's the implementation:

Function.prototype.bindTo=function(thisObject) {
var selfFunc=this;
return function() {
return selfFunc.apply(thisObject, arguments);
};
}

function defineAround(aroundFunc, proceedFunc) {
return function() {
var args=Array.prototype.slice.call(arguments,0);
args.unshift(proceedFunc.bindTo(this));
return aroundFunc.apply(this, args);
};
}

function concatAndPrint(first,second) {
print("first: "+first);
print("second: "+second);

var result=first + second;
print("concat result: "+ result);

return result;
}
around=function(proceedFunc, first, second) {
print("around first: "+first);
print("around second: "+second);
var result=proceedFunc(first, second);
return result + "c";
}
concatAndPrint=defineAround(around, concatAndPrint);

print("final result: "+concatAndPrint("a","b"));

And where would we be without the results?

js> load("aspect.js")
around first: a
around second: b
first: a
second: b
concat result: ab
final result: abc

One more detail, I didn't do an error handling or recovery. You will probably want to wrap any kind of exceptions that might happen in the proceed function and take appropriate action.

So far, our implementation is nice and clean. We're mainly using functional programming concepts for it. The next steps is writing the implementation for the pointcuts and combining that with what we did here. I'll also going to show how to define annotations. Trust me it's going to get more fun as we combine the batter and get ready to bake!

Tuesday, April 08, 2008

Javascript Inheritance with super

One thing that has always bothered me about Javascript is there is no implementation of "super". Most texts suggest to simply call the super function explicitly via its prototype. It makes for refactoring your inheritance hierarchy no fun because of the direct calls. And let's not mention all the duplication.

Let's think for a minute. Everything in Javascript is an object. What if we added the super automatically to the overriden functions so we could get access to it? And while we are at it, why not make our object definitions a bit more explicit along the way?

So, I whipped up the following code:

Function.prototype.subclassFrom=function(superClassFunc) {
if (superClassFunc == null) {
this.prototype={};
} else {
this.prototype=new superClassFunc();
this.prototype.constructor=this;
this.superConstructor=superClassFunc;
}

}
Function.prototype.methods=function(funcs) {
for (each in funcs) if (funcs.hasOwnProperty(each)) {
var original=this.prototype[each];
funcs[each].superFunction=original;
this.prototype[each]=funcs[each];
}
}

It's two very short functions. But, it allows me to do this:

function Parent(z) {
this.z=z;
}
Parent.subclassFrom(null);
Parent.methods({
methodOne: function(x) {...},
methodTwo: function() {...}
});

function Child(z,y) {
arguments.callee.superConstructor.call(this,z);
this.y=y;
}
Child.subclassFrom(Parent);
Child.methods({
methodOne: function(x) {
arguments.callee.superFunction.call(this,x);
...
},
methodThree: function() {...}
});

"arguments.callee.superFunction.call" is a little verbose, but it's better than duplicating the name of my "super" implementation prototype all over the place. Plus, how often do you call "super". I generally think too many calls to "super" is a design smell.

I like this approach mostly. The only thing I don't like is the names I chose. But, I'll keep working on it. I was just happy in two functions, I have "super" in my constructors and functions. If anything, it's a different way of thinking about the problem.

Coming next, how to do aspects and annotations in Javascript.

Saturday, April 05, 2008

A Phrase Past Its Expiration Date

I've been a fan of Roger von Oech for a long time. I love his books, blogs, and cards (yes, cards). His latest blog entry entitled, "A Phrase Past Its Expiration Date", struck a chord with me that I thought I would share. In it, he asks his readers what phrases are overused and should be put to rest. His phrase was "It is what it is." The reason why was because it is commonly used to end debate and thought.

There are several phrases that carry the same role. Here's mine:

  • "YAGNI" also known as "You Ain't Gonna Need It"
    If I never heard this phrase again in my entire life, it would be too soon. I hate it. The original intention was well meant, but many a poor developer took it the wrong way. I've heard it uttered too many times to end discussion because a weak mind couldn't support their assertion.

  • "Do The Simplest Possible Thing That Could Work"
    Another well-intentioned phrase that originally came from Albert Einstein. How could it be bad? Again, I've heard it from one too many hacks to be lazy and not think through their design. It was once used in a debate to store records in XML files instead of a relational database. Even though it was known that the system was to deal with lots of records that had to be randomly accessed. Why? Because they thought relation databases were "hard". The resulting XML files architecture turned out to be way more complex than any OO mapping tool could dream of being. On the surface, the XML seemed simpler, but only when you ignored all the other factors to take into account. The above phrase ended the debate despite cries of the obvious. Confusion abounds because simple is often confused with easy instead of elegant.

  • "If It Ain't Broke, Don't Fix It"
    The maddening catch all to stop refactoring code that everyone fears. This one has been used because apparently certain developers like hearing the buzzing of pagers at 3am. The code in their eyes "worked" even though it was riddled with bugs. The code need to be cleaned, but they just wouldn't let it go. Fear is a terrible thing to use matras to justify.


That's my list for now. I'm sure there's more. I'm really bothered by most mantras because they are used in the most inappropriate places. I'm for debate and rational thought. Anything that short-circuits that annoys me without measure.

Friday, April 04, 2008

Monkey Patching

Monkey patching seems to be all the debate rage currently in the dynamic language blogosphere. The one that caught my attention was Gilad Bracha's in particular. I don't disagree with him at all. I know it's strange reading that from a Smalltalker. But, I view monkey patching like inheritance. It's a great device to have in your programmer back pocket, but can be dangerous. Use with caution and look at your options. Don't use it without thinking of the implications it can cause. The reason its dangerous is because it's a global change that widens the protocol of the affected object or worse changes the contract for an already existing method.

The main reason monkey patching is so dangerous is the global change it makes and the increased probability of having a collision if another project names a method the same. Or worse, another project overrides the default behavior and replaces it with their own. Both can cause subtle bugs that can be hard to catch and find. It's the global nature of it that can bite. It's convenient, but you should think twice before doing it. It's limits your project's options.

Groovy has a novel approach to monkey patching in that it allows them to be scoped for the duration of a block called categories. This reduces the risk of a global change and the addition is only in affect for the duration of the block. Now, it can cause issues if something gets called outside of the block by accident, which is why I wish it had different ways of scoping (class, package, etc). But, with AspectJ these problems can be reduced. Categories reduce a lot of the risk of monkey patching in that collisions are highly unlikely and the protocol is only widened for that invocation. It also ensures that unknown project dependencies will not creep in. I worry less about monkey patching in this instance because if you get burned, it will be your project not everyone else. I think categories are the way to go (if they added class scoped categories, I would be in heaven).

I don't hate monkey patching. Far from it. It is handy to override method implementations during debugging. I can change pre-existing methods if they have bugs in them even before the next release is out. I don't have to wait on the vendor. These are great pluses. I'm just advocating thought before you monkey patch in your own projects. Much like before you swing the inheritance hammer, you should do the same with monkey patches.

Tuesday, April 01, 2008

What's that Squeaking in Omaha?

If anyone in the Omaha area wants to learn how it's done in Squeak and Smalltalk, feel free to stop by at the Omaha Dynamic Language Users Group tonight. I will be speaking on what makes Smalltalk cool and how to setup your Squeak environment. Bring your curiosity and appetite. See you all there!

Wednesday, March 12, 2008

Uh oh

I should have played the Adventure in Emacs before I went wildly blogging. It is not the original Adventure, but another one entirely. Oh well, it's still fun to play.

Tuesday, March 11, 2008

Houston, We Have Zork

Malyon is a Z-code interpreter written in Emacs Elisp. Now, I have an Infocom mode to play Zork, Enchanter, Starcross, Hitchhiker's Guide To The Galaxy, and more. Love is. I have all of the Infocom Z files and a bunch from other interactive fiction authors. I've got some reading and adventuring to do while I continue my Emacs journey. Maybe I'll play a little Stationfall during my next *cough*compile*cough*.

Giggling With Emacs

I started out with AquaEmacs, but quickly switched to Carbon Emacs. The reason was because I still use Windows in other places and it was easier switching between GNU Emacs on Windows and Carbon Emacs on Mac. After my efforts tonight, I have line numbers displaying in the left column thanks to linum.el. I'm finding Emacs Wiki to be a great resource for information. I'm mainly learning by reading other people's code and .emacs files. As with anything, I'm finding lots of things that don't work and performing tons of searches into what certain commands do. Emacs has great help support built-in and is proving to be indispensable in my journey.

But, these are not the reasons for my giggling. I was going through the menus and saw Games under the Tools menu. How quaint. I'm not a big game player. I look at the games listed and see "Adventure". I think to myself, "No way". I click and "XYZZY!" It's the real deal. Oh, I love interactive fiction (Infocom is my fave) and I have never played Adventure. This might keep me busy for a little while. The one kind of game that I love, Emacs has the original built-in. How cool.

Sunday, March 09, 2008

Emacs

To see what I have been missing, I have decided to really get into and learn Emacs. So far, I can I configure the modes and know a lot of the basic commands. I have the Erlang, Ruby, Slime, and Javascript modes working. The thing that has made the difference this time has been making Emacs my editor for everything everywhere. There's no way to fall into old habits.

Some might be wondering why am I torturing myself? I want to see and experience what so many developers that I respect love about Emacs. It's a different viewpoint than mine. Everything is viewed as text whereas I view the world as all objects. It's interesting. It's pushing me out my comfort zone of rich IDEs. I'm not going to say that I've been dealing with is better yet. But, I am making an effort in earnest to learn.

Next steps, I would like to start customizing Emacs through ELisp. Should be exciting and fun!

Wednesday, February 13, 2008

Yet More On Tools

I got so many good comments on Tools that I couldn't just let the replies go to waste. Here's another one from Sam Tesla:
Sooner or later I was going to bite on one of your posts.

While I agree that tools for a language should be written in the language, I have to disagree on specifics.

Why should I have to write Yet Another Yet Another Yet Another Editor for my language in my language when a perfectly good one already exists?

The Erlang/OTP team asked that question and decided they shouldn't. Instead they made an elisp module that turns your Emacs into an Erlang node and uses Erlang's distribution primitives to hook into a live Erlang node.

They provide many of the tools you'd expect from a Smalltalk, including the ability to inspect and interrogate (inasmuch as it makes sense for a functional language) running processes.

It's in Emacs, sure, but that's because Emacs has had at least ten years more to mature than Erlang, let alone any editor written in Erlang.

Good programmers don't repeat themselves if they don't have to.

My answer to this is simply why write a new language to begin with? The reason is simple: to solve a specific problem better than before. We shouldn't stop trying. Now, with that being said, let's move on. I know Erlang is a powerful language and have many times sang its praises. There's a lot of languages in the same boat (Io, Mozart, and many more). I can understand not wanting to do another editor in the beginning, but it's a good exercise. There are non-trivial problems to solve in doing your own editor. Plus, it allows new developers to see a non-trivial example of your new language's code. Again, let's move on.

My main rant was on tools (not necessarily editors), yes, I know I picked on Eclipse and Emacs. But, Eclipse is really much more than a text editor. It has several tools to reason about your code (Refactoring), give your different viewpoints (Call Hierarchy, Class Hierarchy), and ways to ignore what you don't care about. These are the kinds of tools that I am interested in. I think a code beautifier and debugger are the price of admission. You are not even playing the game without those. Now, Erlang is a different way of thinking, it should have tools to support that thinking. Much like the Refactoring Browser changed the way we view code in Smalltalk. I think Ruby is ripe with opportunities to change the way we think about code. Again, the tools should reflect that.

I'll use a simple example: AspectJ. Now, it's not a language per se. But, it's a different way of viewing code and a different way of developing. I liked the idea of aspects, but it didn't click until the Eclipse support came. Once it was easy to see the consequences of my actions, my mental model became stronger. It also made it easier to reason about what my systems were doing. Tools should aid and enhance your mental model. They should allow you to ignore details and quickly hone on the ones you do.

Lastly, I'll add that I wouldn't even think about doing Java code without Eclipse. It's the tools. But, when I'm programming in another language like Ruby for example. I want to stay thinking in that language. So, if I have an idea for a nice tool, it should be easy to whip it up in the language I'm working in. I shouldn't have to switch gears to another language. We should think of languages as playgrounds to change the way we program and change it for the better.

More On Tools

Friedrich had this to say about my Tools post:

I wrote about this on the Squeak mailing list and I guess somewhere else also. I asked for decent editor written for Squeak, AFAIKT such a thing does not exist. But does that mean that Smalltalks are not good for programming an editor? And if no-one sees that this would be good thing, am I expected to step in?

First off, I could give the quick flippant Smalltalker response and say, "If you need a text editor that can handle large chunks of text, then you're doing something wrong." But, I'm not. Sure, we don't need to handle large chunks in coding for Smalltalk, but the world is a different place now. The need is there. Today we need to handle XML documents, source from other languages, HTML, and that's just a start. But, an editor that can handle large amounts of code and makes it easier for new Smalltalkers to get them into the swing of things so to speak.

Secondly, the Smalltalk community might not know they need it. Write it! If anything you might deficiencies through the exercise and decide to fix those as well. I wrote a Java Serialization framework to learn its format, but to fix bad streams as well. Nobody wanted it, but me. You got to do things for yourself and for your own journey as a developer. If you need any help, feel free to contact me. But, don't expect any community to follow along. The best you can hope for is to make the music and hope other people like the melody to join in.

Monday, February 11, 2008

Tools

I'm a firm believer in that tools should be written in the language that they are to be used for. I always treat a language with caution if the only tools for it are written in Emacs Lisp or Java and not itself.

But, why does it matter? It matters because writing tools for your language in another language tells me something. It tells me that:

  1. It's possibly harder to write in than Java

  2. It's hard to parse

  3. Limited or no reflection support

  4. Not user friendly

  5. Can not perform well enough to support tools written in itself


Any of the above points are bad in my book. But, I see it constantly in new programming languages (even in ones 10+ years old). Now, I love languages and learning them. Why? Because I always walk away with a new way of thinking about things. It's also nice to see how other people solve certain problems. It shocks me though that so many languages depend on Eclipse or Emacs for their tools. At some point, a language moves from command line pet project to a true programmer amplifier. The language has to be elegant in syntax, yet have the tools to make debugging and reasoning about the system simple.

Now, before you get angry with me, I do realize that using Emacs or Eclipse gives a huge boost in the beginning with their frameworks. But, by never leaving them, it could also mean there are holes in your frameworks or in your language itself. Tools written in your language help to expose issues like limited reflection or that your language is hard to parse. I believe writing tools should be easy and for everyone to do. If writing tools in your language is hard, then you might need to redesign your language.

I think if we had more languages that had their tools written in them, we would all benefit. Plus, with tools written in your language, new developers have some example code that has real world applications. The way to prove to me if your language is elegant is not to show me how easy factorial is to write, but to show me how easy it is to write an inspector.

Wednesday, January 16, 2008

Presentations

I finally broke down and started a page with my presentations. Check it out here. I included the talk I gave tonight at the Java User's Group. There's not much up there, but I will be adding more soon. Lastly, I would like to thank everyone for coming out and supporting me. It meant a lot to me when people told me that they read my blog and enjoyed it. Omaha rocks. Thanks for the support. I love you all!

Saturday, January 05, 2008

Hugs

I think some folks in the Ruby community need a hug. If you find one, give them one and tell them it'll be OK. Not everyone can have a job doing Rails.

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