Suitability

sandal edited this page Dec 6, 2011 · 8 revisions

Building high quality software is about more than just solving a particular problem. Instead, it is important to try to make sure that the tools you build fit their problem domain as naturally as possible. As an example, we can consider the task of downloading the contents of a single webpage which is protected by HTTP Basic Authentication.

Using the Net::HTTP standard library is one possible option:

require "net/http"

uri = URI('http://browserspy.dk/password-ok.php')

req = Net::HTTP::Get.new(uri.request_uri)
req.basic_auth 'test', 'test'

content = Net::HTTP.start(uri.hostname, uri.port) do |http|
  http.request(req)
end

puts content.body

This approach clearly gets the job done, and if evaluated on its own may seem suitable for the task. However, the OpenURI solution shown below solves this problem in a very different way:

require "open-uri"

content = open("http://browserspy.dk/password-ok.php", 
               :http_basic_authentication => ['test','test'])

puts content.read

The difference between these two tools is that Net::HTTP is meant primarily to be a low level wrapper around the HTTP protocol, while the OpenURI library focuses on the most common problems and presents a more simple API for those operations. This makes it a more suitable tool to use when our needs are simple, as they are here. However, as soon as our network interactions get more complex, Net::HTTP becomes the better solution. This scenario shows just how dependent on context suitability is.


Turn the page if you're taking the linear tour, or feel free to jump around via the sidebar.

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.