Friday, February 29, 2008

AJAX, the REST Killer

I was at a demo today that was showing off an application that was designed to be a reference implementation / blueprint app. Of course it had some AJAX based features in it. One of the AJAX calls allowed an existing object to be edited, and another would delete said object. I noticed that the AJAX was using HTTP GET. I pointed out to the developers that since this was supposed to be a blueprint app, it should get everything right and use POST for both of these. Of course it should really use a PUT for the update and DELETE for the delete, but browsers just don't support that.

After the presentation, one of my colleagues pointed out that a lot of times we are forced into GETs because of cross-domain calls. He was right, and made me realize how the hack-that-is-AJAX is always rearing its ugly head. Cross domain calls are part of life for any large, distributed site. In an AJAX world you either have to use JSONP style calls, i.e. using a Script tag to make your call, or you have to use a server proxy. Of course going directly to the appropriate domain is much more efficient, so JSONP is going to usually win. There's no way to do an HTTP POST on a Script tag, so there you go. Forget all about respecting the REST protocol.

Of course Flash and Silverlight (gotta include it now!) both allow for declarative cross domain security. No need for JSONP hacks. Now if only they both supported HTTP PUT and DELETE...

Thursday, February 28, 2008

Silverlight Slim and Fat Flex

A couple of days ago, I talked about Silverlight 2.0. One of the interesting things to me was that it was how Silverlight RIA-style apps could be a lot smaller than Flex apps. I posted a comment to Scott Guthrie and he was kind enough to post a reply to my question. His reply indicates that for Beta 1, a relatively complex application will be slightly smaller than the same thing in Flex. However, much more of the framework is going to be included with the initial Silverlight download starting in Beta 2, thus giving Siliverlight a huge advantage in terms of app size.

When Adobe announced that the Flex framework could be cached on the Flash player across domains, I wondered why the didn't just included it with the Flash player. I have even bugged Flex evangelist Ted Patrick with this question. His response to me was that they would open themselves up to "DLL hell." In other words, there could be problems with people building their app against Flex framework version X, but a user has an older version installed.

As if this doesn't already happen! Let's not forget that Adobe jumped ActionScript from version 2.0 to 3.0 and thus required Flash player 9 or higher for anything authored using 3.0. This was not just some update in framework, it was the entire programming language being overhauled. It is common to use JavaScript to detect Flash player version and require people to upgrade. It is so common and so part of Flash development, that Adobe distributes the ExpressInstall SWF for doing this as easily as possible. Heck, I usually require users to be on 9.0.28 or higher, since that is the version that fixed some bugs with ExternalInterface.

So back to the Flex framework/DLL hell issue. It would simply require people to check for a certain minimum version of the Flash player (since that would correspond to a version of the Flex framework) and prompt for an upgrade if needed. In other words, it would require something that most folks already do today.

To me the real reason is that it is more economical for Adobe to not include the Flex framework. Ted has a widget he wrote showing over 3.9 billion downloads of Flash player 9. Add an extra 200K to that and you get over 726 TB. That's a lot of bandwidth to pay for. That's a price Microsoft wants to pay, because it would indicate lots of folks with Silverlight installed. Perhaps once that happens, Adobe will reconsider.

Wednesday, February 27, 2008

Project Euler

A friend of mine pointed me to Project Euler. Being a mathematician and a programmer, he knew I would love it. It is a lot of fun. It reminds me of these computer competitions I used to participate in when I was in high school. You would get some list of problems on sheet of paper, have to code a solution, and a judge would come by to test your program. Anyways, I am a 4% genius having completed seven problems so far. I am mikeg on the message boards on there, if you want to check out my solutions. So far I have done everything in Ruby. I picked Ruby for two reasons. First, I like its syntax and want to use it more often. Second, it is slow. So I figured it would force me to come up with good algorithms. Here is a sample of one of my solutions. The problem was to find the largest palindrome that is the product of two 3-digit integers.

def isPal(num)
if num % 11 == 0
return num.to_s == num.to_s.reverse
end
return false

end
 
max = 0
999.downto(100){ |i|
i.downto(100){|j|
val = i*j
if val > max
if isPal(val)
max = val
end
else
break
end
}
}
puts max

Monday, February 25, 2008

Silverlight 2.0

We all knew this would happen at some point. Even when it seemed like it would not, you just had to know in the back of your mind that it would happen. Microsoft has given a preview at Silverlight 2.0. This time it is not about media, it is about RIAs. They even use the term correctly now... You should really check out that link and especially the tutorials it links to. They are very high quality.

Like I said, we knew this had to happen. Silverlight 1.0 was really just a streaming media platform. Silverlight 1.1 was only a little better (and isn't it still in beta?) It gave the first real clue though. It included a stripped down CLR, allowing C# to run inside Silverlight. This was a clear indication that Silverlight was going to take aim at developers and thus become Microsoft's answer to Flex.

Now this has finally happened. I spent the last hour reading through the tutorials. There were several things that really made me raise my eyebrows:
  • A 4KB Hello World : It looks like either the controls (and the framework code that lets them get wired up, etc.) are either really small or the compiler is very smart at stripping things down (or both.) Hello World in Flex is 140KB because all of the Flex framework is included. I don't think all of the Silverlight controls/app framework is included with the base runtime, as it clocks in at 4 MB, i.e. about the same size as the Flash player.
  • Crossdomain Silverlight: MSFT wisely just re-uses the Flash crossdomain.xml policy file system to get the same kind of declarative security. Very nice of MSFT to just tip their cap and say Flash got this right, let's not reinvent the wheel on this one.
  • Silverlight Styles: Their style syntax is ... different. Well different from CSS certainly. Adobe has tried to leverage CSS in Flex. The Silverlight style syntax is probably much more powerful than CSS, but you have to wonder if it is really worth it. It is still a declarative XML syntax on top of the selector paradigm used in CSS.
  • Silverlight for the Desktop: Ok not really. But MSFT is going out of their way to point out how easy it is to take a Silverlight app and turn it into a desktop app. This is clearly in response to the attention that Adobe AIR has received.
So I find myself eagerly awaiting the release of Silverlight 2.0 along with the tooling for it in Visual Studio 2008. I will definitely have to (finally) create a Silverlight Stocks Quote app.

Sunday, February 24, 2008

TDD Gone Wrong

Last time I wrote about TDD. I read this article from some guy at Spring about doing TDD with the Google Web Toolkit. I have to say this is a good example of how TDD zeal can lead to some twisted thinking.

The article starts by point out how GWT enables RIA development in pure Java. That's a good thing. He then talks about some of the difficulties he's experienced trying to write unit tests for GWT widgets and concludes:

views are usually very hard to test, therefore they should know and do as little as possible ... Most of the GWT code has pretty much all the logic in widgets, so most developers using GWT extend a widget and just add some more logic. My advice is simple: don't go there.

RIAs are all about putting lots of logic in your view. Now it's not just any logic, but view logic. You see there is logic involved in creating a rich user interface and the place for that logic is the user interface. So this guy's obsession with testing has led him to the conclusion that you should dumb down your view code so you can test it. This completely defeats the purpose of using GWT. Very sad.

I think the author does bring up some valid points on unit testing GWT. If you place a huge importance on unit test coverage, then the more logical conclusion is that you should not use GWT. Don't try to dumb down the technology so that you can sleep better at night. Just pick a different technology.

Thursday, February 21, 2008

Test Driven Development

Terry wrote a great post about "pragmatic" programming. It brings up the usefulness of test driven development(TDD). It is good that this is debated. It seems like it is almost accepted as fact that TDD is good. Period. Whenever people start accepting something without questioning, it leads to very bad things.

So I am glad that Terry questions TDD. Many folks I work with question it, too. Their arguments are different than Terry's. For example they point out that much what you code in a test has to be duplicated by QA. Of course that's not an issue for some folks, because they don't have QA, but it is an issue in larger organizations. Terry uses the example of Facebook as a large organization that uses no hard rules, i.e. TDD, for development. Also, folks I work with point out that TDD is a recurring tax. You not only spend time coding the test to start with, but you spend more time re-writing the tests every time you make changes to your code. The cost of TDD must be weighed against its benefits, you should not just accept it blindly.

To me, the value of tests greatly depends on the clients of your code. Let's say you have code whose only client is the end user, i.e. "application" code. Generally what matters for that code is that it is accepted by the end user. If it does what they want, that is all that matters as that is the only purpose for the code. I can definitely see how writing tests may not have as much value for this kind of code, though I think there is still some value to it.

Now compare this to code whose clients are other pieces of code. To make it simple imagine application code that calls infrastructure code. In this case it's harder to argue that if the end users of the application are happy, then the infrastructure code is good. Imagine if the infrastructure code has an API that is supposed to produce a formatted date. The infrastructure code could produce the wrong formatting, but the application code could work-around this to keep the end user happy. Maybe that is ok, but things get uglier when somebody "fixes" the infrastructure code, particularly if a second application uses the same infrastructure code. Having fine-grained tests for the infrastructure code becomes more valuable.

For me personally, I like using TDD, though I am not religious about it. There are times that I write a test first, then I write the code. There are other times I write the code, then a test, run the test, tweak the test, fix the code, etc. In general, I like to write tests just because I like to test my code to be sure that it works. I figure if I am going to go through the effort of doing that anyways, I might as well do it in an organized way that could be useful to others. Also, writing test code is at least as useful as writing inline documentation in your code, maybe more useful. A unit test is sample code, or darn close to it.

Sunday, February 17, 2008

Clemens v. Congress

The big story in sports this past week was the testimony of Roger Clemens before Congress. Now obviously this was a huge waste of time and (more importantly) tax payer money. It is classic pandering by Congress. We all know this, right?

There was something else that bothered me even more about the Congressional hearings. That was the obvious division along party lines. Republicans clearly supported Clemens and tried to discredit his accuser, Brian McNamee. Democrats clearly wanted to prove Clemens had taken steroids and HGH. I don't have a problem with folks having an agenda (though if everyone has their mind made up already, why a hearing? Oh never mind.) No what bothers me is that this division was along party lines.

Why does the Republican Party need to support Clemens? How is his innocence somehow a priority for the Party? One can only conjecture. Is Clemens a significant contributor to Republicans and the Party?

Similarly, why does the Democratic Party need to prove that Clemens is guilty? Is it just to spite the Republicans? Do they want to bring greater government regulation and involvement to Major League Baseball or sports in general?

These questions just lead us back to the beginning of this post. The government has no business doing hearings on Roger Clemens. Not only is it wasteful, but inevitably the issue itself becomes meaningless thanks to partisan politics.

Oh, and for what it's worth, I think Clemens is lying and that he used steroids and HGH. I don't care if he did or not, but clearly the evidence points against him.

Thursday, February 14, 2008

Metaprogramming in Grails

Groovy is a swing-and-a-miss. It will go down like OS/2 did. People will say "man that Groovy language was so good, I don't know why it didn't catch on." Here's an example of why it is a fail.

I was reading this article on developerWorks about GORM, the OR framework in Grails. Like everything else in Grails, it is "inspired" by Ruby on Rails. In this case GORM was inspired by ActiveRecord. In GORM here is an association:

class Airline {
static hasMany = [trip:Trip]

String name
String url
String frequentFlyer
String notes
}

Compare this to the same thing in Rails

class Airline < ActiveRecord::Base
has_many :trips
end

Forget the explicit listing of fields for a minute, concentrate on the has-many notation used by both frameworks. In Grails, you have a static field that has a special name. In ActiveRecord you use a meta-API or macro (or whatever you want to call it) to dynamically add methods to each instance of Airline. Grails accomplishes the same thing, but it is much more of a hack. You just happen to have a static field that has a special name.

It just feels like "wow that feature is cool, we can't do it the same way ... but we can hack something together that is pretty close!" Just seems like Groovy comes up short.

Tuesday, February 12, 2008

New Version of JsonViewer: Now Open Source!

I updated the JsonView AIR app I wrote a couple of months ago. It has wound up being pretty useful for some of the folks I work with, hence there have been some bug fixes new features requested. I have also had some folks email me about the source code. So as a result of these two things, not only did I update the app, but I released it as open source via Google Code.

So you can get the latest version here, or you can check out the source code for yourself. I was almost embarrassed to show the source because it so trivial!

Saturday, February 09, 2008

NFL Rumors

From an this article on Y! Sports:
"Cowboys owner/GM Jerry Jones will feel compelled to make a big splash this offseason. The most popular speculation is he'll trade his two first-round picks and running back Marion Barber (a restricted free agent) to the Miami Dolphins for the No. 1-overall selection in the NFL Draft. Jones then could select Arkansas running back Darren McFadden."

Whoa! I like that rumor. I know Miami needs D, but I think Glen Dorsey is way-overrated. He is the logical #1 pick for Miami, so I would love to see them deal the pick. Getting two #1's would be great. I love Marion Barber as well, even though Ronnie Brown looked like the best back in football last year before he got hurt. Seriously the guy would put 100 yards on the ground in the first half of games. Then in the second half, with Miami down by double digits (because they had no defense to speak of) he would rack up another 100 yards receiving. If nothing else, Marion Barber is an awesome insurance policy, and he has ties with new Dolphins head coach Tony Sparano.

The Dolphins offense looked ok before injuries killed them. Oh and before trading Chris Chambers. QB continues to be a problem, but from that same article..."
"Eagles could trade McNabb"

How Much for that Moss?

This article on ESPN rightly wonders how New England should be willing to pay to keep Moss. They make some good points, namely that it will cost the Pats a lot to sign him to a multi-year deal and that he might be disgruntled and play poorly if they resort to using the Franchise tag on him for all of next year. Then they make some stupid points.

Like why expect New England to re-sign Moss when they didn't re-sign Deion Branch who played big in two Super Bowls. After all, New England lost the Super Bowl with Moss. They also try to claim that New England's all-pass attack was foolish because they lost to New York. They even try to use statistics to justify this by pointing that starting late in the third quarter, New England only average 3.8 yards per pass.

Ah, but when dumb people start quoting statistics, they get themselves in trouble. They don't mention that New England only average 2.8 yards per rush. I mean, if passing the ball is not working, then you should run the ball more, right? Oh if that stinks too ... well I guess you could just punt on first down?

Back to Moss, he was the key to New England becoming the most productive offense in the history of the game. They would be above average without him, but they are the best in the league with him. I am no expert on NFL economics, so I can't say what he is worth. All I know is that as a Dolphins fan, I can just dream that New England lets him go.

Finally, one last parting shot on the Super Bowl. It would be dumb for such a successful team to try to "fix" non-existent problems based on the outcome of one game. New York did what many team tried to do against New England: get pressure on Brady. That is the only way to neutralize a great passing game. This has been common knowledge for decades. It's the Lawrence Taylor effect. So if for some reason New England wanted to "fix" something, then they should look at their O-line and in particular Matt Light. I think Light is fine. He is undersized slightly for an LT. He is going to the Pro Bowl this year for the first time, but that is largely because of New England's success. That's the place to look for "fixes" though, not at WR.

Friday, February 08, 2008

99 Bottles of Beer

First off, if you like programming, you should check out this hilarious site on the venerable song 99 Bottles of Beer.

Ok, now I am assuming that you just spent the last hour or so at that website, but you are back. If you are into Java, one of the most interesting solutions is one that eschews typical control structures (for/while/do loops) and instead uses Java's exception system to sing the song. Actually the way that I came across the site was from an email sent by one of my colleagues. He was amused by the exception based solution. I was amused, too. Obviously such code will perform exceptionally bad (pun intended.)

One of my friends was inspired to do a Python variant that used the same technique:


#! /usr/bin/env python

class BottleException(Exception):
def __init__(self, i, c):
self.cause = c
self.cnt = i
try:
a = 1/(99-i)
raise BottleException(i+1, self)
except ZeroDivisionError:
pass

def getCause(self):
return self.cause

def printStackTrace(self):
print("%d Bottle(s) of beer on the wall, %d Bottle(s) of beer" % (self.cnt, self.cnt))
print("Take one down and pass it around,")
print("%d Bottle(s) of beer on the wall" % (self.cnt - 1))
try:
self.getCause().printStackTrace()
except AttributeError:
pass

try:
raise BottleException(1, None)
except Exception, e:
e.printStackTrace()


He and I are both pure hackers when it comes to Python, so there are probably numerous improvements that can be done to that code.

Update: I submitted the Python code to the 99 Bottles of Beer site and they accepted it. You can view it here.

Wednesday, February 06, 2008

Setting Custom HTTP Headers in Flash

I needed to set a custom HTTP header in Flash. ActionScript 3 makes this easy, or so I thought. Here was my original prototype code:

import flash.net.navigateToURL;
private function href(url:String):void
{
var req:URLRequest = new URLRequest(url);
var header:URLRequestHeader = new URLRequestHeader("Koostoom", "tmttos");
req.requestHeaders.push(header);
navigateToURL(req);
}

Like I said, this is easy. To verify it was working, I wrote a quick prototype using PHP:

$headers = getallheaders();
foreach ($headers as $name => $value) {
echo "[$name] = $value<br/>\n";
}

I think I copied this out of the PHP manual pretty much. So I tested the above code and everything worked, right? I wouldn't be writing this post if that was the case!

I tried the above in Firefox and Safari. My usual test plan is to make sure it works in those two browsers first, and then deal with IE. In this case it didn't work in either browser. I knew that some HTTP headers were off-limits in Flash, so just for just kicks I tried changing Koostom to Referrer. This should have caused an exception, but of course it didn't. It did nothing.

Finally, I found the answer through experimentation. You have to do an HTTP POST with form data in order to get the custom header sent:

import flash.net.navigateToURL;
private function href(url:String):void
{
var req:URLRequest = new URLRequest(url);
// begin stupid hack
req.method = "POST";
var formVars:URLVariables = new URLVariables();
formVars.blah = "blue";
req.data = formVars;
// end stupid hack
var header:URLRequestHeader = new URLRequestHeader("Koostoom", "tmttos");
req.requestHeaders.push(header);
navigateToURL(req);
}

Now the PHP script showed my Koostoom header...

I don't know if this is a bug with the Flash player, or the browsers. I don't think it is part of the HTTP spec, i.e. I think custom headers are just as valid in an HTTP GET as in an HTTP POST.

Monday, February 04, 2008

Super Tuesday

Obviously I'm voting for Ron Paul. I really thought that the Republican race would still be clouded. Oh well, I was wrong. It does mean I will get to vote against McCain twice this year! More on that in another blog... Let's talk about the more interesting stuff on the ballot in California tomorrow: The Propositions!

Prop 91 -- Places restrictions on tax money earmarked for transportation infrastructure. Definitely a yes.

Prop 92 -- The key here is that this freezes community college fees. Wait, so I "own" (pay taxes) a business (state government) that produces a product (community college education) and I want to fix what my business charges for that product, even if I have to pay more (pay professors more, etc.) for it? That is stupid. It will only cause community college education to suffer just like all other forms of public education... No.

Prop 93 -- Reduce term limits from 14 to 12 years ... I am against term limits. Let people vote for who they want to, so No.

Props 94-97 -- Ah, the new Indian gaming "compacts". First off, Indian casinos are state backed monopolies. They get special privileges from the state, and in turn pay the state a percentage of profits. Personally I have nothing against Indian tribes having casinos, I just have something against laws that prevent non-Indian tribes from having casinos. So I have to vote against these measures. No.

Sunday, February 03, 2008

Super Bowl Prediction

New York 27, New England 23

I have to root for New York. I have a good friend from Jersey who is a huge Giants fan. Using the same logic, I have rooted for Pittsburgh the last two times they were in the Super Bowl. So I have to root for New York.

That being said ... If New England wins, they will have completed the most impressive season by any (American) professional sports team. They will not be the best football team ever. That's because of parity. You just can't assemble talent like you could just 10-15 years ago. Of course that is part of why their season will be the most impressive ever. They don't have overwhelming talent across the board, like say the 49ers and Cowboys of the early-mid 90's. They may have the best offense ever. I can't remember a team that could stretch the field horizontally and vertically like they do.

Anyways ... go New York!