logo
  • Jobs
  • About Me
  • Contact
  • Home

Chuck Norris: The Programmer

Posted June 15th, 2009 by Matt Berther

Saw this from codesqueeze earlier today… Hilarious stuff. :)

  1. When Chuck Norris throws exceptions, it’s across the room.
  2. All arrays Chuck Norris declares are of infinite size, because Chuck Norris knows no bounds.
  3. Chuck Norris doesn’t have disk latency because the hard drive knows to hurry the hell up.
  4. Chuck Norris writes code that optimizes itself.
  5. Chuck Norris can’t test for equality because he has no equal.
  6. Chuck Norris doesn’t need garbage collection because he doesn’t call .Dispose(), he calls .DropKick().
  7. Chuck Norris’s first program was kill -9.
  8. Chuck Norris burst the dot com bubble.
  9. All browsers support the hex definitions #chuck and #norris for the colors black and blue.
  10. MySpace actually isn’t your space, it’s Chuck’s (he just lets you use it).
  11. Chuck Norris can write infinite recursion functions…and have them return.
  12. Chuck Norris can solve the Towers of Hanoi in one move.
  13. The only pattern Chuck Norris knows is God Object.
  14. Chuck Norris finished World of Warcraft.
  15. Project managers never ask Chuck Norris for estimations…ever.
  16. Chuck Norris doesn’t use web standards as the web will conform to him.
  17. “It works on my machine” always holds true for Chuck Norris.
  18. Whiteboards are white because Chuck Norris scared them that way.
  19. Chuck Norris doesn’t do Burn Down charts, he does Smack Down charts.
  20. Chuck Norris can delete the Recycling Bin.
  21. Chuck Norris’s beard can type 140 wpm.
  22. Chuck Norris can unit test entire applications with a single assert.
  23. Chuck Norris doesn’t bug hunt as that signifies a probability of failure, he goes bug killing.
  24. Chuck Norris’s keyboard doesn’t have a Ctrl key because nothing controls Chuck Norris.
  25. When Chuck Norris is web surfing websites get the message “Warning: Internet Explorer has deemed this user to be malicious or dangerous. Proceed?”
No Comments

Properly utilizing XslCompiledTransform

Posted February 27th, 2009 by Matt Berther

Not long ago, we noticed some degradation in performance after we upgraded to .NET 2.0 and migrated to the XslCompiledTransform class from the now obsolete XslTransform class. Our implementation was fairly straightforward, although we hid it behind an interface for easy mocking/testing.

The code looked something like the below:

public interface TransformLoader
{
    XslCompiledTransform Load(string name);
}
 
class XslTransformLoader : TransformLoader
{
    public XslCompiledTransform Load(string name)
    {
        XslCompiledTransform transform = new XslCompiledTransform();
        transform.Load(name);
        return transform;
    }
}

This is a pretty standard implementation, although after JetBrains .Trace pointed out that a majority of the time was being spent in the Load method, we started doing some research. As it turns out, we mistakenly understood the XslCompiledTransform to be smart enough to determine whether or not the transform had already been compiled. If it was, we thought, it would use the compiled version. As it turns out, this is not the case. To effectively utilize this class, it is important to save off the instance of the class for subsequent uses.

To do this, we created a new implementation, the CachedXslTransformLoader, which looks like this:

class CachedXslTransformLoader : TransformLoader
{
    private Dictionary<string, XslCompiledTransform> transforms = new Dictionary<string, XslCompiledTransform>();
 
    public XslCompiledTransform Load(string name)
    {
        XslCompiledTransform transform = null;
        if (!transforms.TryGetValue(name, out transform))
        {
            transform = new XslCompiledTransform();
            transform.Load(name);
            transforms[name] = transform;
        }
 
        return transform;
    }
}

When running the older XslTransformLoader through a loop of 100 transformations with our XSLT and XML files, we found that it was taking approximately 48 seconds to transform the entire loop. However, when utilizing the new CachedXslTransformLoader, the exact same loop only took 1.3 seconds to execute.

This is where the performance improvements from the XslCompiledTransform really come to fruition, so make sure that you are saving off the instance of the class. As we saw, the class is not smart enough to determine whether or not the XSL has already been compiled.

By the way, the performance problem we were experiencing went away with this minor change. On another note, it was nice to see this adhere to the open/closed principle. We were able to correct issues in the system by adding new code, not by touching existing/tested code.

Bottom line: when using XslCompiledTransform, make sure to save off the instance and reuse it for maximum performance benefit.

2 Comments

Sometimes the problem is in your tests

Posted February 13th, 2009 by Matt Berther

I was TDDing a new website that I’ve been working on last night and got caught in the interesting predicament where the tests failed, but the production code worked. For the life of me, I could not figure out why my test was failing. It turns out, I missed a tiny little piece of documentation on how shoulda works.

By the way, before we get into this, if you are writing Ruby code and writing tests (you are, arent you?), do yourself a favor and check out the shoulda library. Excellent work from the great folks at thoughtbot.

context "with valid attributes" do
  setup do
    @user = Factory.create(:user)
    @updated_attributes = Factory.attributes_for(:user)
 
    put :update, :id => @user.id, :user => @updated_attributes
  end
 
  should_not_change "User.count"
  should_respond_with :success
  should_redirect_to 'root_url'
end

For quite some time, every test was passing with the exception of should_not_change "User.count". After consulting the documentation and source code for shoulda, I realized what should_not_change was actually doing.

The should_not_change macro was evaluating the User.count statement *PRIOR* to the setup method executing and stored the result in a variable. Then when the test executes, it evaluated the User.count statement again. Since the Factory.create call in the setup method created a new instance in the database, of course, User.count would change.

To get around this particular example, I ended up having to create a nested context to make the test pass. I dont necessarily like this, but it does get the test to pass and gives me an opportunity to change it if someone has a better solution.

context "updating User information" do
  setup do
    @user = Factory.create(:user)
    @updated_attributes = Factory.attributes_for(:user)
  end
 
  context "with valid attributes" do
    setup { put :update, :id => @user.id, :user => @updated_attributes }
 
    should_not_change "User.count"
    should_respond_with :success
    should_redirect_to 'root_url'
  end
end

Indeed, sometimes the problem lies in your tests.

No Comments

puts vs print in ruby

Posted February 11th, 2009 by Matt Berther

I discovered something a bit peculiar about the puts and print methods in Ruby. puts seems to flush immediately, and therefore shows up on $stdout right away. Take the code example below:

5.times {
  puts "."
  sleep 2
}

This functions exactly the way that you would expect. It places a single period on $stdout, followed by a two second pause for five iterations. puts inserts a new line character as well, so instead of placing each period on the same line, each one is on a new line. print does not insert the automatic newline sequence, so it would place each one on the same line. However, the code below does not function the way you would expect.

5.times {
  print "."
  sleep 2
}

The code above waits for 10 seconds and then prints all 5 periods. As it turns out, this is because the print method buffers the output. The easiest way to get around this (for a situation like the above) is to set the sync property on $stdout.

STDOUT.sync = true
5.times {
  print "."
  sleep 2
}

This sets $stdout to avoid buffering the input, which most modern operating systems do. If you find yourself in a situation where you need to have a small amount of output sent immediately to the screen, this is a good technique to utilize to serve this requirement.

3 Comments

Implementing method_missing

Posted February 10th, 2009 by Matt Berther

Earlier, I was working on creating a script that would iterate a set of folders and execute a chunk of code against that file when it was found. The script itself is easy enough to write with straight ruby. For example:

Dir.glob("./**/*").each do |f|
  # your ruby code here
end

However, as much as we tend to do this during our daily life, I was hoping to hide this behind an api that some less technical users may be able to use. To promote reuse, I created a class that would provide this functionality.

class FileWalker
  def root_path=(path)
    @root_path = path
  end
 
  def each_file_of_type(type, &block)
    Dir.glob("#{@root_path}/**/#{type}").each do |f|
      yield f
    end
  end
end

The users of this API utilized it in a manner which you would expect (coming from a statically-typed language):

walker = FileWalker.new
walker.root_path = "."
walker.each_file_of_type("*.rb") do |file|
  # your ruby code here
end

While this covered the functional requirements of what I was hoping to do, I really did not like the way this reads. One, the user of the API was expected to implement the wildcard for the type. Two, did I say that I didnt like the way it reads? What I was really hoping for was an API that worked like this:

FileWalker.dir "." do
  each_rb_file do |f|
    # your ruby code here
  end
end

The first thing you’ll notice is that I remove the file specification from the call with the each_rb_file method. However, I certainly do not want to corrupt the FileWalker class with dozens of methods to iterate different file types. Having to add a new method every time I want to iterate a different file type would most certainly violate the open/closed principle.

As I thought about the best way to accomplish both the API I desired and the long-term maintenance, I decided to take advantage of a great method on ruby’s Object class called method_missing. method_missing is a method that gets called every time a method on the receiver does not exist. The method gets passed three arguments, the name of the method, any arguments to the method, and a block to execute.

Using a little regexp magic, I am able to intercept calls to each_rb_file and delegate them to the earlier each_file_of_type method (which is now private). Take a look:

class FileWalker
  def initialize(path)
    @root_path = path
  end
 
  def self.dir(path, &block)
    walker = new(path)
    walker.instance_eval(&block) if block_given?
  end
 
  def method_missing(method, *args, &block)
    if method.to_s =~ /^each_(.+)_file/
      each_file_of_type "*.#{Regexp.last_match[1]}", &block
    end
  end
 
private
  def each_file_of_type(type, &block)
    Dir.glob("#{@root_path}/**/#{type}").each do |f|
      yield f
    end
  end
end

So, as you can see with a little method_missing mojo, we now have access to any number of methods that allow us to retrieve all files of a particular extension. The above script and class will work with any sort of file extension. Calling each_exe_file, each_xml_file, or each_py_file will all function the same way, without adding any new code. The advantage here, as mentioned earlier, are that 1) we get to provide a *readable* API to our consumers, and 2) we conform to the open/closed principle by not having to modify already written and tested code to implement a new extension.

If you’ve not looked much at method_missing and ruby, I encourage you to discover it more. I’ve only touched the surface with its capabilities. Others have gone much further, including implementing an entire XML dsl utilizing this method.

Perhaps in a subsequent post I’ll dive into how I’d go about implementing this… til then.

1 Comment

Testing Helper Modules with Rails 2.2

Posted January 27th, 2009 by Matt Berther

I recently found myself in a situation where I wanted to make sure that the current year is always displayed in the copyright statement at the bottom of a Rails application. At first glance, this is easy enough. All that a person needs to do is add the following to their application.html.erb:

Copyright &copy; 2007-<%= Date.today.year.to_s %>

However, as we start to implement this, it becomes apparent that this is not very test driven. I sought to find a way to implement and verify this functionality with a breaking test first.

Since view tests can often be very brittle, I really wanted to implement this in my ApplicationHelper module, so that I could hopefully test it easier, but also reuse to functionality in other areas.

Testing Rails helpers has been hard historically, but as I investigated how I might test this functionality in the ApplicationHelper module, I discovered the ActionView::TestCase base class. This class provided all the hook up that I needed to call methods on my helpers. Armed with this, I set out to write my test:

class ApplicationHelperTest < ActionView::TestCase
  def test_copyright_includes_current_year
    actual_copyright = copyright_text()
    assert(actual_copyright.include?(Date.today.year.to_s), "Copyright must include current year.")
  end
end

This fails pretty quickly, since it cant find ActionView::TestCase. The easiest way to resolve this is to add require 'action_view/test_case' to your test_helper.rb. When we run the test again, it fails again, since the copyright_text method does not exist, so we flip back over to the ApplicationHelper module and implement the method.

def copyright_text
  "Copyright &copy; 2007-#{Date.today.year}, Company Name. All Rights Reserved."
end

Voila. Our tests now pass. The last step is to add a call to this helper method in the view:

<%= copyright_text %>

We may take this a step further and also implement additional checks around the copyright statement, which can be easily done with the assert_match method. This was not needed in my particular case though.

No Comments

New MacBook Pro

Posted January 19th, 2009 by Matt Berther

About 18 months ago, I purchased my first MacBook Pro… a 17 inch monster laptop. I absolutely loved the big (1920×1200) display that I purchased as an additional feature.

Over the course of the past year, I realized that I was not really very mobile with that behemoth. Obviously, at more than 17 inches wide and almost 7 pounds, it can be quite a cumbersome unit to drag around with you. Even more, the space it takes up on your lap makes it almost unusable. Calling it a “laptop” was a bit of a stretch.

No more… earlier today, I traded in that MacBook Pro and got the new 15″ unibody MBP. 320gb of drive space, with 4gb of ram packed into a nice little 5 pound chassis. Not quite as small as my wife’s 13″ MacBook, but certainly more inline with what I would consider a laptop. All that said, I really do miss the 1920×1200 resolution, even though the LED display on this is much brighter. If I do want that resolution, I can always plug it into my wife’s 24″ Cinema display.

1 Comment

Hiding an email address from spam harvesters

Posted January 15th, 2009 by Matt Berther

Using a little css trickery, you can completely hide your email address from spam harvesters. The drawback to this approach is that it will only work on sites that read left-to-right as it uses CSS to reverse the direction of text.

Add this class somewhere in your CSS file.

span.reverse {
  unicode-bidi: bidi-override;
  direction: rtl;
}
 

At the point that you are ready to present the email address, code it in your HTML, but just key it in backwards. For example:

<span class="reverse">moc.rehtrebttam@retsambew</span>

The CSS above will then override the reading direction and present the text to the user in the correct order.

Pretty clever technique.

7 Comments

Curse thee, IE6

Posted December 17th, 2008 by Matt Berther

I work in an environment, where, unfortunately we are somewhat constrained as to which browsers we support. Our target market has a very slow update cycle and our products are not necessarily the kind where the loss of use would force an IT upgrade. Therefore, our ASPNET applications must continue to support IE6.

A few clients have been consistently reporting an issue where in IE6 only images where randomly disappearing after they were clicked on. However, we had never been able to reproduce the issue. Until earlier this week…

The images in question were being toggled dynamically with a bit of javascript that looked something like this:

function toggleImages(id) {
    var img = document.getElementById(id);
    if (img.src == "active.gif") {
        img.src = "neutral.gif");
    } else {
        img.src = "active.gif";
    }
}

The html markup for the image display looked like this (with some irrelevant code removed):

<a href="javascript:void(0);">
    <img id="imageIdentifier" src="neutral.gif" onClick="toggleImages('imageIdentifier');"/>
</a>

The first clue that this was something that was caused by IE6 was that 1) no other browser was affected by the way this code was written, 2) it only manifested itself when accessing the web server through a proxy (local hits to a test website failed to reproduce this problem), and 3) only when the ‘Use HTTP1.1 for proxy traffic’ was selected from the advanced options did we see this.

As we begin to investigate this further, we find a few reports of this issue via Google. The issue has something to do with the events not being fired properly when using javascript in the href attribute. Ultimately, the fix was very easy. We simply needed to add a return false; after the onClick handler.

No Comments

Authentication WTF

Posted December 17th, 2008 by Matt Berther

So there I was earlier tonight… Trying to review my credit reports like I do about this time each year. A visit to annualcreditreport.com and I was on my way… until I got to Equifax’s site.

I’d managed to forget my login information to Equifax’s site, so I used the “forgot username/password” link and was presented with a form to enter my last name, social security number, and date of birth so that they could present my challenge question to reset my password.

Imagine my surprise when I got this (click the picture for a full-size version):

wtf-small.png

So, what is my what? I’m not really sure what to type in here. What is my red star?

Equifax has also disallowed me from setting up a new account, since I already have an account tied to my social security number. So, here I have an interesting paradox. I cant login to the account because I dont know the secret word, but I cant create a new account, because I already have an account that I cant log in to.

Epic FAIL.

1 Comment
« Previous Entries
flag
Favorite Charity
wounded warrior project
Search
Social
  • mattberther on twitter
  • mattberther on linkedin
Syndication
Archives
  • June 2009
  • February 2009
  • January 2009
  • December 2008
  • November 2008
  • September 2008
  • August 2008
  • June 2008
  • May 2008
  • April 2008
  • March 2008
  • February 2008
  • January 2008
  • December 2007
  • November 2007
  • October 2007
  • September 2007
  • August 2007
  • July 2007
  • June 2007
  • May 2007
  • April 2007
  • March 2007
  • February 2007
  • January 2007
  • December 2006
  • November 2006
  • October 2006
  • September 2006
  • August 2006
  • July 2006
  • June 2006
  • May 2006
  • April 2006
  • March 2006
  • February 2006
  • January 2006
  • December 2005
  • November 2005
  • October 2005
  • September 2005
  • August 2005
  • July 2005
  • June 2005
  • May 2005
  • April 2005
  • March 2005
  • February 2005
  • January 2005
  • December 2004
  • November 2004
  • October 2004
  • September 2004
  • August 2004
  • July 2004
  • June 2004
  • May 2004
  • April 2004
  • March 2004
  • February 2004
  • January 2004
  • December 2003
  • November 2003
  • October 2003
  • September 2003
  • August 2003
  • July 2003
  • June 2003
  • May 2003
  • April 2003
  • March 2003
Jobs
mattberther.com © 2003 - 2009