Monday, August 22, 2011

Wrong is Better Than Vague

Vague
I've got this idea for the next killer app. It's this game, you see, that'll leverage the unique properties of tablets. Do you want to work on implementing it with me?

What's the game?  Oh, something fun.
So this will be for the iPad? That and other tablets.
Who's going to play it?  Everyone.

Wrong
I am going to create a 3D minesweeper for the iPad and I'll sell it for $473.26 per copy. Minesweeper is already popular on the Windows, and there is this huge market of iPad owners who have already shown they are willing to pay a lot for gadgets. And with the 3D angle we can get rich off of this. Do you want to work on it with me?

The Difference
The problem with vague is that most ideas sound either good or bad depending on the listener's optimism. Vague is how a small project turns into a years long boondoggle, or how the next billion dollar idea gets missed.

In my experience most new ideas from management types (and a disturbing number of research scientists) are of the vague variety. They have these great pie in the sky ideas, but if you try to actually evaluate them for engineering or business practicality, you can't. Without details there is no way to determine if the idea is good or completely infeasible.

Take the vague example above. Would you work on it? Is it going to be successful? Who knows. What about the wrong example? Of course you wouldn't work on it, as is. But because it is concrete, it could be improved.

Nobody pays $400 for apps!   Oh, then I guess we can charge $4.95. 
The iPad doesn't support 3D.   Hmm.. then maybe we should target those cell phones that do. 
Minesweeper really doesn't lend itself to 3D.    Well, what about this other [fill in specific details here] game? 
How much work will this be?   Oh, given those details it'll take about 3 months. 
So how many do have to sell to make it worthwhile?    Oh, my time is cheap, probably just 10 copies. 
Then you'll probably be successful, but I don't think I'll help you.
As you can see, with concreteness, even wrong concreteness, decisions can be made in an informed way.

Even more important than concrete plans, are concrete implementations. There's a reason people create research prototypes, whether it is for a physical product or software. You can learn so much more from what goes wrong than you can from just the high level ideas.

So the next time you have an idea, make it concrete. A wrong implementation is worth much more than just the vague idea itself.

Monday, August 15, 2011

Emailing Server Errors

I've talked about checking the server's health, but its even nicer if the server lets you know if it has a problem. In particular, you don't want user's experiencing errors and for you to remain in blissful ignorance. A simple fix is to have your server email you whenever a user encounters an error. Here is how I did this in rails.

Catch the Error
The first thing to do is to capture any exceptions that get thrown. This can be done easily by adding the following line to your ApplicationController.
unless Rails.application.config.consider_all_requests_local # don't rescue on local testing
  rescue_from Exception, :with => :handle_error
end
As of this writing, apparently Rail 3 doesn't support 404 errors this way, so a fix for this is to add a catch-all route at the bottom of your config/routes.rb that looks something like:
# this must be the LAST rule in the file
# it allows our custom 404 error to execute
match '*path', :to =>'application#routing'
Handle the Error
Now that I have caught unhandled exceptions and 404 errors, you need to do something with them. These methods in the the ApplicationController are the ones called from the above code:
def routing(exception = nil)
  record_error "404 error", exception
  render :template => "/errors/404.html", :status => 404
end
 
def handle_error(exception)
  msg = exception ? exception.message : "unknown error"
  record_error(msg, exception)
  render :template => "/errors/500.html", :status => 500
end

def record_error(msg, exception)
  return nil if Rails.application.config.consider_all_requests_local # don't email during local testing

  referrer = request.env['HTTP_REFERER']
  url = request.url
  app_name = Rails.application.class.to_s
  user = current_user
  name = user ? user.username : "UNKNOWN"
   
  error_msg = msg
  if exception
    error_msg += " #{exception.message}\n#{exception.backtrace.join '\n'}"
  end
   
  ip = request.remote_ip
  remote_ip = request.env['HTTP_X_FORWARDED_FOR']

  logger.warn "Error #{error_msg} for url [#{url}] coming from url [#{referrer}] from user [#{user}] at ip [#{ip}] forwarded from ip [#{remote_ip}]"
   
  mail = ErrorMailer.log_error(msg, app_name, url, referrer, ip, remote_ip, name, exception)
  mail.deliver
end
You can make the 404 and 500 error pages that these methods render be whatever you like, though it is suggested that you make them useful. The record_error method that these methods calls, collect a bunch of information about the request, log them (in case mailing fails), and then emails them. The emailing is done using Rails mailing capability. Since the actual configuration for talking to the mail server will depend on your situation, you should read the documentation for that.

Emailer
To send the email, I created mailers/error_mailer.rb which is analogous to a controller. All it does is package all the variables into instance variables that the view will have:
class ErrorMailer < ActionMailer::Base
  default :from => "myApplication@myurl.com"
  helper :application

  def log_error(subject, app_name, url, referrer, ip, remote_ip, user_name, error)
    @app_name = app_name
    @url = url
    @referrer = referrer
    @ip = ip
    @remote_ip = remote_ip
    @user_error = user_error
    @user_name = user_name
    @error = error
    mail :to => "myAddress@somewhere.com", :subject=>"RAILS ERROR in #{@app_name}: #{subject}"
  end
end
The view (views/error_mailer/log_error.text.haml) turns this information into an email message:
There was an error in app #{@app_name} at time #{Time.now}.

URL:  #{@url}
Referrer:  #{@referrer}
IP:  #{@ip}
IP via a portal:  #{@remote_ip}
User: #{@user_name}
 
- if @error
  Error class: #{@error.class}
  Error message: #{@error.message}
  Error Stack Trace:
  - @error.backtrace.each do |line|
    = line
- else
  No exception to log
Warning
I do have one piece of advice: Make sure the subject you give your error emails is something very distinct that you can write mail filter rules. After I deployed a similar solution at work, the security teams scanner found my app and proceeded to run through its entire litany of tests against the server. I came in the next morning to more than 4,000 emails from 404 errors. The fact that I had put the entire development team as the recipients of these emails was just the icing on the cake.

Maybe emailing every error isn't great, since you can look in the log files for the same information. However, I find the immediacy and in your face nature of an email is good for making sure that errors get fixed and aren't just silently experienced by your users (and ex users). However, be aware that if something goes wrong, you have the potential to receive a lot of email. (not to mention choice comments from anyone else who is also getting those emails).

Monday, August 8, 2011

One year of regular posts

Though I started this blog years ago, it was one year ago that I started posting regularly. This was partially inspired by Jeff Atwood's advice to post regularly. I have no idea how he regularly posted 6 times a week given that I have a hard time posting once a week. And I think that Syd (a commenter on that post) hits the nail on the head that there is more to being a popular blogger than just being reliable. However, being reliable is definitely a prerequisite.

So how have I done? Well, I missed two weeks in the past year. And I feel like I am struggling each week to keep up. However, Google Analytics shows that I've been at least a little bit successful. I've trended up pretty consistently since I started posting regularly.


100 page views a week is far from a popular blog. But it is a number that is high enough that I know that it isn't just me and my closest friends reading my blog. So that is some measure of success.

If you've been following my blog you've noticed that I have two different types of posts, my philosophical posts and my practical/tutorial posts. When I started this blog, my goal was to post primarily philosophical posts and to generate a discussion on each post. My secret goal was to learn more from my comments than I put into my posts. Unfortunately, so far, I don't get many comments, so that isn't working out. At some point I decided to also write tutorial type posts describing how I solved a specific problem. I've learned much from others who have posted what they know, so I feel I should give back. Based on Google Analytics, the majority of people who see my blog come to view these posts. Unfortunately, if the readers don't leave comments, I have no idea if what I posted was useful or just a waste of time. I can only hope that some people are finding it useful. Even more, I hope that some of these people become regular readers (and commenters) on my more philosophical posts. I am the eternal optimist and still hope to achieve my original goal.

Of course, to accomplish that, I need to continue Jeff Atwood's advice and post regularly. While I have plenty of ideas, it is somewhat daunting to me to actually turn those ideas into posts each week. Well, here's hoping that next August I get to bore you all with another post like this.

Monday, August 1, 2011

Documentation and Context

A few weeks ago Scott Adams (of Dilbert fame) wrote a blog post about the context of a message. One of his points was that the context that a message is presented in affects how the message is received. Saying the same words at a standup comedy club and at a funeral won't have the same affect. This is related to a thought I've long had about software design documentation. We all have a context in our mind, but that of a reader is probably different.

A specific example of this difference came up at work recently. Asok, Alice, and I (not their real names) were discussing a new feature we wanted added. The feature was something Alice and I needed to support our project, but it required a change in Asok's code. Over the course of an hour long meeting Alice and I kept suggesting changes to Asok's code and he kept telling us that what we were suggesting didn't make any sense.

So why did Asok keep telling us our suggestions made no sense? It wasn't arrogance, he was right. Our suggestions didn't make sense in the context of his code. It was a lack of understanding on Alice and my's part. We were looking at database and classes, and based on their names we were making certain assumption that turned out to be wrong.

Why didn't Alice and I understand Asok's design well enough to make good suggestions? We both have plenty of experience in the field, so it wasn't that. It would be easy to blame poor naming of databases and classes on Asok's part, but now that I understand it, I'm not sure I can come up with anything better. Really it was just a matter of context. Asok had worked on this system for months, and everything fit into a model he had in his head. Alice and I didn't have that model, so we made up our own. As often happens, the model we assumed didn't match reality.

How should [we] document our designsThis, to me, is the big problem of software design documentation. I have been on both sides of this problem. I have seen people completely mangle my code because they didn't see the "correct" ways and places to extend it. I have also mangled others people's code for the same reason. This is how unmaintainable behemoths get created. The challenge is: how should Asok, Alice, or I document our designs such that the context we have in our head is conveyed to the next person?

Some people say that the code is the documentation. While the code is the reality of today, the context of the code shows how to extend, modify, and use that code. Sharing this context from the code writer's mind is crucial to code being able to be maintained beyond the original author.

So, I guess this is another one of those posts where I point out a problem and have no solution. Do you have a solution?

Monday, July 25, 2011

Checking Web Application Health

There are certain things you want to know about your web application to make sure it has started correctly and to help diagnose problems.
  • Is it up?
  • Can it connect to the database(s)?
  • Can it connect to the web service(s)?
  • Can it do any other actions that may independently break?
  • What are the server settings?
  • What version of the code is running?
The first question is easy to answer? But what about the others? You can obviously determine if the other dependencies are up by going to the appropriate place in your application, but it'd be nice to have a single location to check all of these. And what about server settings or code version? Ever had a bug reported that you know you fixed? It's nice to also be able to make sure that you really are running the version you think you are.

Here's how I've accomplished this on a Ruby on Rails project.

Single Location
First, I created a controller with a single page:
prompt> rails generate controller Admin index
Here is the beginning of the controller class.
class AdminController < ApplicationController
  before_filter :require_admin

  def index
  end
end
As you can see, I've protected it, so only administrative users can view this page. Here is the views/admin/index.html.haml where I show server state.
This is the status page.
%br
%h2 Version
%pre= @version
%h2 Environment
%br
%b RAILS_ENV:
= ENV['RAILS_ENV']
%br
%hr
%h2 Site Tests
.test
  = button_to "Test DB", {:action=>"test_db"}, :remote=>true, :onClick=>"startTest()"
%hr
%h2 Test Output
#testOutput

:javascript
  function startTest() {
    $("#testOutput").replaceWith('<div id="testOutput">Loading...</div>');
  }

Dependency Tests
I've implemented each test as a separate Ajax call. In the view code above, this everything from "Site Tests" on down. This consists of the buttons (one for each test, just one here), a place to show the output, and the javascript to make this work. For each test, I just add a new button in the .test div. As you can see in the code above, the button makes an Ajax call (:remote=>true) and calls a javascript function to show that the result is loading. It is up to the controller to then update the testOutput div with output status.

In my admin_controller.rb I have a function for each button that looks like:
def test_db
  standard_test do
    # insert test code here
  end
end
The helper function standard_test looks like:
def standard_test
  begin
    yield
    @success = true
  rescue Exception => e
    @success = false
    @exception = e
  end
  respond_to do |format|
    format.html {
      flash[:error] = "This should've been ajax"
      redirect_to admin_index_path
    }
    format.js {
      render 'test_output', :layout=>false
    }
  end
end
All it does is executes the test code (via the yield statement) and catches any thrown exceptions. If there is no exception, it considers the test a success. Assuming it was called via an Ajax call, it then renders the javascript template test_output.js.haml which is simply:
!= "$('#testOutput').replaceWith('#{escape_javascript render(:partial=>'test_output')}')"
As you can see, this merely replaces the testOutput div with what is rendered by the _test_output.html.haml partial:
#testOutput
  - if @success
    %b SUCCESS
  - else
    %b ERROR
    %br
    %b Error Class:
    = @exception.class
    %br
    %b Error Message:
    %pre= @exception.message
    %b Error Stack Trace:
    %pre
      - @exception.backtrace.each do |line|
        = line
    %b Error Inspect
    %pre= @exception.inspect
Of course, don't forget to make sure your routes are in your config/routes.rb.
get 'admin/index'
post 'admin/my_test' # separate route for each test
Version
Including version information is going to be very specific to your environment. We use Mercurial for our version control, and since we have a number of Java project, we use ant for our deployment process. Here is how I connected these together.

In the ant deployment script, I added a target that looks like:
<target name="write.hg.version">
  <exec executable="hg" dir="${project}" output="${project}/config/version.txt">
    <arg value="summary" />
  </exec>
</target>
All that is left is to get the contents of this version.txt file into the @version variable that is displayed by index.html.haml. This is done by simply having the index method in admin_controller.rb read in the file.
def index
  name = File.join(RAILS_ROOT, 'config', 'version.txt')
  if File.exists? name
    f = File.new(name)
    @version = f.read
  else
    @version = "Unknown version"
  end
end
Conclusion
This really wasn't too much work, and now I have a single page that I can go to and at a glance see what version of the code was deployed and which rails environment is being used. Adding new tests is just a simple matter of adding a new button to the view, which calls a new test method in the controller. By leveraging the standard_test method, new tests can consist of just the code they are intended to test.

Monday, July 18, 2011

Windows Command Line Cut & Paste Rant

Just a quick rant this week. When selecting text in the windows command console, why does it do a "block" mark rather than a line based mark?!?! In every other text based environment I've used, including Windows Notepad and MS Word, if you start highlighting text in the middle of one line and move down to the middle of the next line it select the end of the first line and the beginning of the next line.  i.e. all the text that starts where you started the mark and ends where you ended the mark. For some reason the Windows Command shell only marks the text that is actually in the box, i.e. a couple characters in the middle of both lines.

Is there a time that this behavior is useful? If you know, please share it with me.

For me, I often want to copy either a long command line I ran, or the output of a command, to put in an email, IM, a wiki, or even to paste into another terminal to run. But if the line is wrapped, then to make sure I get everything I want, I have to also copy the command prompt. This means I have to add an intermediate step of editing my selection before I can send it.

What's even more bizzarre to me, is that in searching on the web, I can't even find any other comments about this behavior. Nor can I find a way to change this. Am I the only one who finds this annoying? More importantly, does anyone know how to change this behavior?

(I know, I know. I shouldn't be using Windows, and I shouldn't be cutting and pasting. Well, I have to admit that I sometimes do both, and I was doing a lot of both this past week.)

Monday, July 11, 2011

Attack of the Clones

As I mentioned, I was recently at ICSE. One of the big topics there was Clones. How do you detect them? How do you remove them? The talk that I found most interesting on the topic was one where they tried to measure how bad clones really are.

First, the definition for those of you aren't familiar with the term clone in the context of software engineering. (I wasn't before this conference). A clone is just what it sounds like, duplicated code. Clones are most often created via cut and paste.

The idea of removing duplicated code through common modules, whether they are libraries, classes, functions, procedures, or macros is an old one. Probably about as old as programming. In recent years, removing duplicated code has even got a hip acronym: DRY. The idea that clones are bad was basically a given at this conference. I have pretty much internalized that idea, so this didn't seem strange to me at all.

So how bad are they? Well, as I mentioned above, there was research that tried to answer this question. Researchers analyzed the version control history of a few different projects and tracked all of the clones in these projects. They then tried to evaluate some of the problems. For example, one of the problems with clones is that if you change the code, you have to remember to do that change in multiple locations. What they found was that in the vast majority of the time, clones either never changed, or only changed once. Meaning that the majority of the time, the work of refactoring the code to remove the clones would be at least as large as the work of just maintaining them.

What about the situation where one clone is modified, but another copy doesn't get updated. Well, they found that this is also very rare, and a lot of the time when this does happen, its intentional. And even of the times when they are unintentionally out of sync, the resulting code is typically not a bug.

So what does all this mean? I don't know. Maybe their sample projects weren't representative of most software projects. Or maybe, just like most other engineering decisions, there are trade offs, and there isn't a 100% right answer, independent of context. I still find that clones offend my sense of software ascetics most of the time, but I am trying to be a little more open-minded and be critical about what and when I refactor.