Just In Time, Not Just In Case
Something that has finally become a habit for me is adding code when it is needed, not in case it is needed. Often times we “think” we are going to need something, so we add the code to support it. What happens most often with that code is it sits and rots. It adds bloat and weight to your program that is not needed.
Example
I like to see examples first, so I will start with one. In Harmony, sites have users. I had a method in the site model named add_user.
class Site
def add_user(user)
user_id = user.is_a?(User) ? user.id : user
# add user code here, removed for clarity
end
endSome might look at that and think it is a perfectly fine method, but I would disagree. A quick search through my code revealed that I was never passing a user id. Every time I called the method, I passed in a user as an argument. That was the first smell.
The second, which may be for another article is that I used is_a?. We are programming in Ruby folks. It is always better to duck type and ask respond_to? than is_a?. The difference is asking an object what it is, instead of asking an object what it can do.
Having add_user take either a user or a user id meant twice as many tests and an extra line of code. I killed the is_a? ternary line and the accompanying tests and went on my merry way.
How to Avoid Just in Case
The best way that I have found to avoid “just in case” is to test first. When I write my tests first and start with the most basic test I can think of and go from there, my code tends to only be as complex as the test requires. Whenever I begin with program code instead of test code, I end up with “just in case” features like the one above.
This might seem small as it was only one line and it was well tested, but this was only one small example. Cases like this multiply as the program grows and the “real” code begins to get obfuscated behind the cases that might happen someday.
The moral of the story is a line removed is a line that will never have bugs down the road.
*To give credit where I believe credit is due, I am 99% positive that Jamis Buck said “Just in time, not just in case.” at a conference. Could not find a reference though.


Recent comments
1 year 23 weeks ago
1 year 23 weeks ago
1 year 25 weeks ago
1 year 27 weeks ago
1 year 42 weeks ago
1 year 45 weeks ago
1 year 45 weeks ago
1 year 45 weeks ago
1 year 46 weeks ago
1 year 48 weeks ago