6 July 2012

Faking it…

 …and why it will make you a better lover coder

If you’ve ever integrated your app with another service for something common like authentication (maybe via omni auth, twitter or even active directory) then it’s possible you’ve had this pain.

What do you do when you want to code on that app but you’re offline?

This highlighted to me recently how important it is to keep all your responsibilities isolated and self contained. I’d integrated an internal web app’s authentication with the active directory server so that user admin and auth could be kept centralised across our internal architecture.

So, in all the parts of the app that touch authentication, I deferred out via LDAP to our active directory server and, lo and behold, it worked.

Fast forward a couple of months and I’m coding at home, working on an idea I had at the end of the office day while it’s still fresh in my mind….and I can’t use the app at all because (quelle surprise!) the server is on the internal office network.

*facepalm*

So, I figured, let’s fake it! Like you do in your testing environment, stub out the calls you’re not interested in so that you can focus on the ones your *are* interested in. This turned out to be a un uphill struggle since I was making direct calls to the LDAP server from many parts of the codebase (controllers, model, files in lib etc).

Naughty naughty.

So, I refactored all those direct calls into wrapper methods in a single module in the lib directory. Now everything else must go via the active directory module to interact with LDAP.

Now, at the bottom of that file, I can re-open that code like this:

1
2
3
4
5
6
7
8
if
Rails
.
env
.
development?
  
module
ActiveDirectoryInteractions
    
def
self
.
authenticate
(
username
)
      
true
    
end
    
# etc etc
  
end
end

Magic! All the live API calls are self contained in one place and easily faked out for dev mode and there is no responsibility for that interaction peppered across the codebase.

So the lesson? If you struggle to fake the implementation of some functionality in your codebase, it probably means it’s not very well organised. Wrap it all up in one place so the responsibility doesn’t leak and make your code brittle.