Private Methods vs Lambdas in Ruby

Scoping your methods to the lowest common denominator is imperative to reducing regression to the absolute minimum.

Okay, that’s a lot of words in a sentence and not necessarily the most common sequence of words either. So, it warrants some explanation. And while I have the word Ruby in the title, the underlying approach or recommendation in itself isn’t specific to Ruby. It’s just that I am likely going to use a Ruby example since that’s what I worked on today!

A private method in Ruby is not as private as a private method in other languages in that it can be accessed at runtime but, having said that, you would have to do something explicitly as a developer to override the default behavior when it comes to accessing them so it is quite alright to treat it as private for purposes of this discussion.

So, we all know when to use private methods but I am going to state the obvious. If you don’t want a method to be accessible outside the class (or module) it is defined in, you would make it private, and you want to make as many methods private as possible so you aren’t worried one bit when it comes to refactoring time. The more scoped your methods are, the less likely would the chances of regression be (when you refactor to your heart’s content).

Here’s an example of a private method:

private def not_everyone_sees_me
# does something
end

Say, we have another method in the same class that calls this:

def everyone_sees_me
# do something
# call private method to do more things
not_everyone_sees_me
end

This will work. Sure. But, there’s a problem here. not_everyone_sees_me is private, yes, but it is a little too public within the space of being private. Now, what in the world do I mean by that? Even if no one else invokes this method in this class, refactoring this private method will require that you ensure that there are no other callers, which while not super hard, can become very inconvenient as the size of your class grows.

If you scoped that method so it is nested to the caller, it will alleviate this issue making refactoring blissful. There are 2 ways you can do that in Ruby:

def everyone_sees_me

def not_everyone_sees_me
end
not_everyone_sees_meend

Or:

def everyone_sees_me

not_everyone_sees_me = ->() {
}
not_everyone_sees_me.callend

Both options will work. As to why & when you may want to use one approach vs the other, it’s for another day, and another article :)

Manage your projects on https://snowpal.com!

--

--

Krish @ products.snowpal.com | learn.snowpal.com

I am a Software Developer and Architect, and run the engineering team at Snowpal. Subscribe to our APIs to reduce time to market for your web & mobile apps.