Ruby: Why to use private_constant (pt 1)
Adrian Lee
Posted on October 1, 2022
I don't want to muddy the waters by going over all the reasons to use private_constant (e.g. for inner classes, that's pt 2) since I want to focus on what we most commonly think of as constants in ruby i.e. FOO = 1
.
I'm too used to seeing classes that define constants at the top of the class (great!) but then leave me wondering .. is that constant being used from outside the class? In a small code base that isn't a problem; in a large code base it's essential that a classes public interface is public for a reason, not by chance.
Sometimes people do consider this and we end up with:
class Foo
def blahblah = FOO
...
private
FOO = 1
end
puts Foo:FOO
:shocked_pikachu_face: when people discover that the above quite happily prints 1
The proper way to declare a private constant is to use ... private_constant
class Foo
FOO = 1
private_constant :FOO
def blahblah = FOO
end
puts Foo::FOO
Now we have a private constant:
ruby private_constants.rb
private_constants.rb:7:in `<main>': private constant Foo::FOO referenced (NameError)
puts Foo::FOO
^^^^^
Encapsulation is vital in complex software systems. Please watch your privates!
Posted on October 1, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.