Ruby in a more functional way : Freezing

One of the tenets of functional programming is immutability.

Freezing variables

Immutable values means that once a variable has been set, it can never change. It’s forever the same, immutable.

But wait a second, if a variable is frozen….doesn’t it mean that it no longer varies? which means it’s not longer a variable? exactly, it becomes a constant!

life_constant = "change"
life_constant.freeze
life_constant = "taxes"

If you try the above means you get a runtime error, as you can’t modify a frozen string.

Freezing objects

Sidenote, no point freezing Fixnums as they are already immutable objects.

After having a chat with my mentors, it seems that there’s not much value in freezing objects. A particular reason why one would freeze an object is due to a lack of trust. Defensive programming. Being afraid that someone is going to mutate the object underneath your feet. Perhaps a better approach is teach your team and having a code base where the team doesn’t feel the need to mutate the object.

I’m not sure, what I am sure about is that using freeze is not idiomatic in ruby. Plus you would have freeze all over your codebase, which would be yuck.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s