March 15, 2014
On Mentoring: Mind the (Knowledge) Gaps

When I first started learning how to develop software I was fortunate enough to be paired with a mentor right off the bat. Then only six months after writing my first lines of code I was asked to mentor other beginners. What I did was probably a little more teaching than mentoring- but it was probably one of the best things I could have done. Not only is the enthusiasm of beginners infectious, but at that time I even felt like I was getting more out of it than the apprentices. The act of teaching everything I had learned forced me to be comfortable enough with those ideas that I could speak about them— and the questions my apprentices asked forced me to dive deeper so that I could provide the right answer.

The Teacher’s Gap

Some years have passed and I’ve continued mentoring, and as I look back I realized that when I mentored early on I had one distinct advantage. It was a small gap between where I was and where my apprentice’s were so it was easy to put myself in their shoes. I refer to this as “the teacher’s gap”. When this gap was small, when I’d faced the same struggles as them only a few months earlier, it was easy for me to empathize with their challenges and help them work through various pitfalls and gotchas.

As I’ve continued further down my own path, and certain things about writing software have become second nature, the teacher’s gap between myself and the newer apprentices I work with has grown. When I’m not mindful of this I’ve made the mistake of answering a question without enough context or providing a challenge that might be so littered with little pitfalls and gotchas my apprentice ends up down a rabbit hole (not that exploring rabbit holes is bad, but it’s easy for beginners to get stuck there).

Being mindful of the “teacher’s gap” requires equal parts empathy and retrospection. I take a step back, put myself in the apprentice’s shoes and think about the discrepances between what I know about how to solve a problem and what the apprentice might know. Then I identify what things would be most beneficial for an apprentice to learn on their own, and what things might be best if I provide a little more direction on.

The Student’s Gap

The other gap I’m acutely aware of as a mentor is the “student’s gap”- that space between where an apprentice is and where they are trying to get to. Their destination could be an app they want to build, a specific problem they are trying to solve , or learning a new language— but maybe they are still wrapping their brain around a certain syntax or struggling with a design choice.

As a mentor I’ve found that being aware of the size of the student’s gap is even more critical to providing guidance— and this was a lesson I first learned as an athlete and coach in the cycling world. Just because a rider wanted to be a pro didn’t mean that they should immediately start doing six hour training rides everyday. Of course, the ambition of many a young rider led them down that path— and then shortly burnt them out of the sport. The same holds true for anyone trying to improve- if they attempt to make too big of a jump the results can lead to frustration, demotivation and time wasted. It’s one thing to jump into the deep end, it’s quite another to be dropped into the middle of the ocean. However, if the steps are too small then the apprentice might not be engaging in critical problem solving skills or seeing enough improvement to keep them motivated.

Whereas being mindful of the “teacher’s gap” required a closer evaluation of myself, being mindful of the “student’s gap” requires careful observation of the apprentice. Where are they really at and how big of a jump are they ready for? An apprentice may exude confidence but still only be ready for baby steps. Conversely, an apprentice might be quite advanced but lack confidence— so being thrown into the deep end is just what they need to realize how far they’ve come.

Constant Evaluation

At the risk of sounding cliché, the one thing that both the teacher’s gap and student’s gap have in common is their constant change. In software development we are always facing new challenges and learning new things. In addition, our community is so valuable because every developer understands something a little bit differently than someone else.

There will always be a gap between what a mentor knows and what an apprentice knows— and when the relationship between the two is at its healthiest the apprentice is even teaching the mentor a thing or two. And developers always want to learn and build new things, so we all have a constantly changing student’s gap between what we are and where we want to be.

In order to help each other succeed- as a mentor, co-worker or a kindred spirit- it’s important to evaluate the current state of these two gaps when providing guidance. As we often discover after spending any length of time on a single code base, the developers we are today are never the developers we were a few months ago.

February 10, 2014
Problem Solving Steps

Developing software is all about problem solving. At the highest level we hope our software solves a problem for our customers and users. At the next level down we’re solving the problem of creating a system that moves data from here, does something with it, and move it over there. Below that we’re solving a problem by implementing sort of algorithm, and at the bottom level we’re solving the problem of properly telling a machine what to do with our functions and data.

When I first started programming it was often these low-level problems— getting the machine to do what I want— that would catch me up and prove the most frustrating- things like a nil object error, an unexpected return value or worse yet, no behavior when I expected something to happen. Over the years a few simple tactics have actually turned these frustrations into nothing more than speedbumps and micro-learning lessons… but there are still those times when I tell the computer to A, it does Z, and I can only respond with a big, fat wtf. Fortunately, by falling back on these steps I can usually find my way again.

[Note: if you’re looking for a great post on problem solving tips be sure to check out Doug Bradbury’s post.]

My “Low-Level” Problem Solving Steps (in order)

1) Read the error message.

More often than not when I hit a snag there’s an error message staring me in the face— and as soon as I learned how to properly read them they become problem solving tool numero uno. Good people put hard work into making sure that stack trace printed out for me— and bless them. Anyone who’s kind enough to make sure other poor saps get a nicely outputted stack trace should start including a link to a charity or beer fund they’d like us to donate to. But seriously, the error message often tells you exactly where to go and what went wrong. When I’m working on a toy project or playing around with a new language a lot of times I’ll just let the error messages guide me along- sure, we can call it error-driven development, but really I’m just messing around— and with good error messages, usually having fun.

2) Read the code, I mean really read the code.

You keep using that word, I do not think it means what you think it means.

When I’m working in a foreign code base I know that trying to understand all of it is not always required and I should trust my teammates and the developer before me. So I’ll look over the code to see what’s going on be all, “Yep, got it. I see that this function returns X”. Then I’ll write a test for what I’m trying to do, and of course I’m expecting the test to fail, but sometimes it fails in some spectacular way that makes my head explode. The error message directs me back to the source code that I was originally looking at, and only after carefully reading through it do I realize that the method is doing some entirely different from what I thought. (Also known as RTFM)

3) Pry! These eyes… are prying

Thanks to the one and only Josh Cheek for my exposure to pry. I think pry should be the first tool that every Rubyist learns. For newbies it’s incredibly valuable to be able to poke around under the hood and for experienced programmers it’s an extremely powerful tool for troubleshooting or fine-tuning an algorithm. In my perfect problem-solving world (well, not entirely perfect because steps 1 and 2 didn’t work, and then there’s still a problem to solve…) I have a spec I can run in conjunction with a well-placed pry statement and not only am I able to quickly solve the problem but I also gain a deeper understanding of whatever it is I’m working on. [Sidenote: Most languages have some form of debugger, but when I’m working in another language, or in a Ruby project that doesn’t have pry available- the best fallback is definitely the humble print statement (eg. puts, println, console.log, etc.).]

Bonus tip: Get your Grep On

I started with TextMate’s ‘find in project’ and moved on to Ack in MacVim and this past year I’ve become a decent grep'er. However, going code spunkeling is often one of the last things I do when solving a problem. I enjoy reading code and I probably have some subconscious fear that if I dive in I won't come up for air. But a few weeks ago I rolled on to a team with Mark Grant and today he put on a spelunking clinic for me— he dove with both precision and speed. While implementing a feature I came across a method whose name signaled a potentially dangerous side effect, but I had no idea what it actually did. A quick grep revealed only one other use in the project and no method definition. The system we’re working on uses a service-oriented architecture so there were several different projects that could have defined or used it and I wasn’t sure where to start looking. I asked Mark if he knew and he wasn’t sure, but he did know the system well enough to strategically aim his greps. Within a few seconds he followed the trail and pointed me to the method definition and where it was being used. Score one for the grepper.

It’s the Small Steps

Before we can run we need to know how to walk, and when we fall the first step is to get back up. These four steps usually get set me back on the the right path. In a follow-up post I’ll tackle some of the problems higher up the chain.

November 24, 2013
Update OSX SSL Certs for Ruby 2.0.0-p247

From the department of fool me twice, shame on me. I ran into this issue on my laptop about a month ago and blanked on the solution when I had the same issue on my desktop.

All of my recent client work has used Ruby-1.9.3 so I decided to start using Ruby 2 for a couple of my personal projects in order to see what kinks I came across. I’m an RVM user so installing the new version was a simple matter of rvm install ruby 2.0.0-p247 (the latest patch when I made the jump).

The first kink came hard and fast when I wasn’t able to install any gems. A simple gem install bundler would result in this error:

WARNING:  Unable to pull data from 'https://rubygems.org/': SSL_connect returned=1 errno=0 state=SSLv3 read  
server certificate B: certificate verify failed (https://s3.amazonaws.com/production.s3.rubygems.org/specs.4.8.gz)

I spent a couple minutes doing some troubleshooting with no success, but then a search brought up a few different stack overflow posts that saved me from any (further) frustration. I actually had two problems- my rvm was woefully out of date and I needed to update the my SSL certificates.

Updating RVM

The RVM team couldn’t have made it any easier: rvm get stable

Checking & Updating SSL Certificates

Kudos again to the RVM team for making it simple:
Check the status of your certificates with: rvm osx-ssl-certs status
Update all of your certificates with: rvm osx-ssl-certs update all

Note: while just searching for links for this post I came across these exact same steps from Michal Papis- the release manager for RVM.

August 23, 2013
Postgres and OS X: Round Two

TL;DR If you’re on OS X, installed Postgres with homebrew, and are receiving errors asking if your Postgres server is running locally and accepting connections, check that your PGHOST is configured for localhost

In the never-ending battle that is Postgres versus Mac OS X, which I’ve written about before, Postgres narrowly claimed a victory tonight but four little words and a helpful Stack Overflow answer saved the day.

I was digging into a Rails app and firing up Postgres for one of the first few times on a computer running OS X 10.8.4. When I tried to run any of the rake db commands I received what unfortunately may be a familiar error for any dev trying to run Postgres on OS X:

could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?

Seeing as how I’d stared down the Postgres beast before I was confident this would be a relatively quick yak-shave and tried to fire up Postgres on the command line. Somewhat surprisingly it worked and I was able to create and edit tables and roles without any problem.

Next I did a check for running processes via ‘ps auxwww | grep postgres’ and I could see that all the expected postgres processes were there. Hmmm….

The next line in the stack trace directed me down into the gem file…

../gems/activerecord-3.2.13/lib/active_record/connection_adapters/postgresql_adapter.rb:1216:in `initialize'

…but when I opened that I immediately spied a splat operator in the method that meant the offending argument could really be anything…

def connect
      @connection = PGconn.connect(*@connection_parameters)

So then I took a step back and wandered back up to the original error. What stuck out to me there was the very specific socket in the error: .s.PGSQL.5432.

A Google search then led me to my solution, which was to configure my PGHOST to point to localhost. This could be done in one of two places, either by adding ‘export PGHOST=localhost’ to a file that handled some of my other variables (like my ~/.bash_profile), or by adding host:localhost to the Rails app’s config/database.yml file (for the test and development environments.

I ended up setting the variable in my .bash_profile because when I fired up an old Sinatra app that used Postgres I received similar errors. Setting the variable system-wide took care of those errors as well.

August 15, 2013
Configuring Rspec Options Per Example

Over the past several months we’ve been internationalizing the Rails app that I’ve been working on. There are all sorts of lessons we’ve learned from rolling an app out to 17 countries (and counting)— and suffice it to say that Biggie wasn’t wrong when he said: “Mo countries, Mo problems” (or something to that effect).

We have a thorough ‘full-slice’ set of tests that uses plain old RSpec + Capybara in lieu of Cucumber, and before each of these tests we log in as a user. Once we started adding more countries we needed to log in as different users and our test assertions began to vary. For example, business rules dictated that some view elements might not be displayed for a user in Europe, or the form that a Euro user sees will differ from the one a U.S. user sees. We needed to write tests accordingly and vary the locale of the test users logging in.

I decided to use the Rspec.configure block in a spec_helper.rb file so that it was very easy for us to control the locale of the user at the moment we were writing our tests. We did this via an option passed in to either the it/do or describe block:

describe "view widget for adjusting price" do
  it "calculates price with value added tax field for European users", :user_locale => :euro do
    ... test set up and assertion with VAT...
  end
end

or…

describe "view widget with no VAT calculation", :user_locale => :us do
  it "calculates price without VAT for U.S. users" do
    ... test setup and assertion without VAT...
  end
end

As I mentioned, the :user_locale option is handled back in our spec_helper.rb file. The configuation looks something like this:

RSpec.configure do |config|
  config.before :each do
    user_locale = example.options[:user_locale]
    login_for_location(user_locale)
  end
end

def login_for_location(user_locale)
  ... the login/token/auth code ...
end

The key here is example.options in the third line of the Rspec.configure block. All of your RSpec examples can take metadata so when we pass in the hash of :user_locale => :euro to a test example it is then available to us during the configuration. For further reading I recommend a quick look through the rspec-core source code on metadata.

There is one catch to be aware of, but the solution is rather simple (which dawned on me after looking at a project fellow 8th Light’er Myles Megyesi had set up). If you only have a certain amount of tests that require configuration then I wouldn’t recommend putting this login configuration inside of the main spec_helper.rb file— especially if you have a fork in your logic. It doesn’t make any sense for tests that have nothing to do with logging in or a locale to hit this configuration block. Instead, just create a second spec_helper file in the appropriate directory and only include it for those tests that need it. For example, we the locale configuration in spec/integration/locale/spec_helper.rb.

July 30, 2013
Posting JSON with Net::HTTP

Recently I’ve been working on a gem that serves as a proxy between the app that includes it and an external service. It adds a route and forwards GET and POST requests to the service and then returns the responses. The gem includes a simple Rails engine and we are using Net::HTTP from Ruby’s standard library to forward the requests. I’ll got into more depth about building the gem later, but for now just wanted to offer a quick tip on posting with Net::HTTP.

The GET request with Net::HTTP is very simple and only requires a couple of lines. The URI module is included as part of Net::HTTP and is often used to build the Uniform Resource Identifier objects for requests.

uri = URI('http://www.your-url.com/stuff')
response = Net::HTTP.get_response(uri)

Sending a POST can also be pretty straightforward:

uri = URI('http://www.your-url.com/stuff')
response = Net::HTTP.post_form(uri, 'param1' => 'info', 'param2' => 'more info')

However, the external service that we are posting to is expecting JSON so we needed to configure our request to send appropriate headers. Unfortunately Net::HTTP’s post_form method doesn’t support headers. Figuring out the process to do that was a little cumbersome so I figured I’d document it here.

The key to sending JSON is to create a new Net::HTTP object and then send the headers hash as a third argument to its post method. Unfortunately, that’s not included in the documentation, but once we figured that out it’s pretty simple. (Props to this guy for a little extra googling-fu.) Here’s an example of what it looks like:

params = {'param1' => 'info', 'param2' => 'more info'}
json_headers = {"Content-Type" => "application/json",
                "Accept" => "application/json"}

uri = URI.parse('http://www.your-url.com/stuff')
http = Net::HTTP.new(uri.host, uri.port)

response = http.post(uri.path, params.to_json, json_headers)

And voila, you have a response object at your disposal.

July 10, 2013
Repository vs Proxy

Recently one of the 8th Light apprentices said that he was using the Repository pattern in a project and asked me how it differed from the "Gang of Four’s" Proxy pattern. I confessed that I hadn’t read through all of the patterns in Design Patterns: Elements of Reusable Object-Oriented Software, so this was an excellent chance to read up on the Proxy pattern (and get back into blogging).

The short answer to his question can be found from the GoF’s stated intent for the Proxy Pattern:

Provide a surrogate or placeholder for another object to control access to it.

The Repository class from my post on the pattern never really controls access to the underlying repositories— it behaves only as a simple pointer and never acts as a surrogate or placeholder for the underlying data stores. The Repository class never stores any data itself, never has any affect on the data being sent to the datastore, and is never responsible for the creation of any datastore. It simply points to data stores with no regard for what they are. They could be in-memory relational databases, or flat-files— much like the honey badger, my Repository class doesn’t care. Furthermore, in the ‘Applicability’ section of the GoF Proxy pattern chapter, it states that the Proxy is used specifically when something more powerful than a simple pointer is required, but my Repository is never anything more than that.

The Long Answer

There is, however, one statement in the GoF book that could easily be interpreted as a similarity between the two patterns. In fact, the first time I ride it I had to ask whether or not my implementation of the Repository pattern was in fact just a Proxy.

The GoF list the first motivation for using the Proxy pattern as “deferring the full cost of an object’s creation until we actually need to use it”. Deferment was certainly part of my motivation in using the Repository pattern, however that deferment had everything to do with deferring a decision about an implementation detail (the database)- and nothing to do with deferring creation. I still had to create an in-memory datastore and implement all of the methods that I would need from a database. So for all intents and purposes my in-memory datastore is a full-fledged database. I might have even discovered that my app never needed anything more than that.

Of course, I did know that I was going to need some sort of persistence beyond an in-memory datastore, so I think my implementation could be interpreted as a figurative proxy, even if not a literal one. What it did was allow me to determine what I was going to really need from my datastore— as well as provide a lightweight and fast database to test against.

So Now That We Know What a Proxy Isn’t…

There are a few other statements in the GoF book that highlight key differences between my implementation of the Repository pattern and the Proxy pattern, and through those differences we can understand a little more about what a Proxy is.

As I mentioned earlier, the GoF state that the “Proxy is applicable whenever there is a need for a more versatile or sophisticated reference to and object than a simple pointer”. Examples of that versatility and power include:

  • Virtual proxy: This also falls under the category of “deferring creation”. The example the GoF use for this is when a proxy can provide a smaller version of an image file that will get the job done instead of instantiating an image at its full resolution. I recently participated in a project where we were using caching on a proxy
  • Remote Proxy: this is a proxy that represents something in a local address space instead of having to make the call to a remote object or service. I recently participated in a project where we used cached data on a proxy to save ourselves the expensive call to an external service.
  • Protection Proxy: exactly as it sounds, in this case the proxy is useful when different access rights need to be granted.
  • Smart Reference: in this case the proxy performs some additional behavior before calling the actual object. Examples from the GoF include counting references to an object to manage memory or checking that the actual object is properly locked so that you can make sure nothing else changes it.

Wrap-Up

Ultimately, the difference between my implementation of the Repository pattern and the GoF Proxy pattern boils down to the extra behavior that a Proxy does besides “pointing”. Although I’d heard from others that the “Design Patterns” can be a bit intimidating, it’s still one of those books that every programmer should own and the Proxy chapter is a good one with lots of concrete examples. Since proxies are something we see with regularity “in real life” I recommend checking it out and reading a little deeper into the details.

April 4, 2013
HTML5 Date input

Thus, whither the jquery-ui datepicker?

It sounds like the HTML5 date type for inputs has been around for a while but I just found out about it during today’s announcement of Chrome Beta 27.

    `Best Day Ever: <input type="date" name="best-day" value="2009-01-02">`  

Best Day Ever:

January 20, 2013
Pairing Tour: Chris Peak and Sprites

Day eight of my pairing tour took me to a client site to pair with one of 8th Light’s design craftsman, Chris Peak. The 8th Light team he’s working with just finished a major milestone for the client so Chris had a list of housekeeping tasks to tackle. We started off writing a little CoffeeScript and Jasmine specs, made some tweaks to the database config, and wrapped the day working with Image sprites in CSS.

There wasn’t much to report on regarding the CoffeScript or database config tweaks— however, the sprite stuff was really cool and it was great to watch Chris quickly flip between Photoshop and his CSS file to get the icons just right.

Like many people, my introduction to sprites was primarily through Twitter Bootstrap. By just attaching a class name like class = “icon-home” to an element a cool little pre-made “home” icon would show up. I knew that all of these icons came from one single image sheet but had never dug into the “magic” behind them.

Well, as it turns out there really isn’t that much magic, it’s just a clever use of the width, height, background-image and background-position attributes.

Here’s a look at the relevant attributes from inspecting the elements of the icons page in Twitter’s own Bootstrap guide:

.icon-home {
    background-position: 0 −24px;
    background-image: (“../img/glyphicons-halflings.png”);
    width: 14px;
    height: 14px;
}

The first two lines of this block include the png file that has all of the icons (as seen here) and then positions it accordingly. By positioning it −24 pixels along y-axis it shifts the focus of the image down the “sheet” of images. Since the home-icon is positioned all the way to the left there is no adjustment necessary for the x-axis. The width and height attributes are simply the constraints that they want to put on the background image. The home-icon is only 14 pixels x 14 pixels so that is all that they need to include.

An easy way to experiment with sprites in “real-time” is to head over to the aforementioned Twitter Bootstrap icon section, right click on an icon to inspect it, and then start playing around with the CSS attributes to see how each adjustment affects the image. Happy sprit-ing.

January 17, 2013
Pairing Tour: Eric K - Working with iOS Touch Events

On Tuesday I had the chance to pair with Eric Koslow on the client project that I worked on with Brian Pratt last week. Eric did his apprenticeship during mine so we’ve paired quite a bit together. He’s a quick thinker who seems to know something about every toolset out there so I invariably learn something new every time we work together.

He was continuing to work on the JavaScript for the iPad web app, which meant tracking down some unexpected behavior and getting the app to respond to touches and swipes the way that it should.

The secret to handling touch events in Safari on iOS is that the mobile browser provides unique DOM elements that you can interact with. The ones that we worked with most were the targetTouches and touchEvent object. Apple’s documentation explains it best:

The system continually sends touchEvent objects to an application as fingers touch and move across a surface. A touch event provides a snapshot of all touches during a multi-touch sequence, most importantly the touches that are new or have changed for a particular target. A multi-touch sequence begins when a finger first touches the surface. Other fingers may subsequently touch the surface, and all fingers may move across the surface. The sequence ends when the last of these fingers is lifted from the surface. An application receives touch event objects during each phase of any touch.

So, in a nutshell, what happens is that targetTouches ends up being an array of touchEvent objects. These events are things like touchstart, touchmove and touchend, and can be mapped to the mouse events mousedown, mousemove and mouseup. These touchEvents have various properties, such as the X and Y coordinates of each event.

Unfortunately all the code we worked on is in the client repo so I’m going to need to update this post with some better examples after I follow up with Eric, but here’s a quick and dirty example:

Let’s say that you wanted to track how far a touch moved along the X- or Y-axis. Normally a touch that moved further along the X-axis would just move the page around on the mobile browser (and snap back into place), but you want to intercept it and do something like a “page swipe” so that you can advance to the next slide in an HTML presentation or the next photo in a web gallery.

function pageSwipe(event) {
    event.preventDefault();
    var movementThreshold = 100;    
    var xDistanceMoved = event.targetTouches[0].pageX - startX;
    var yDistanceMoved = event.targetTouches[0].pageY - startY;
    if (xDistanceMoved > yDistanceMoved && xDistanceMoved > movementThreshold)
        advanceToNextPage;
};

All this function does is grab the first element out of the targetTouches and ask what its X and Y coordinates are (pageX and pageY). By subtracting the starting X and Y values we can then determine just how far it moved. If the X distance is greater than Y and also greater than the “accidental movement” threshold, then you trigger the page swipe. (Again, not the greatest example, so I’ll definitely update the post with more).

I feel like Eric and I just “touched” on the tip of the iceberg when it came to event handling in mobile browsers. As so much web consumption moves to mobile I’m looking forward to learning more about it.

Liked posts on Tumblr: More liked posts »