One of my pet peeves (I have a few) is finding the protected
keyword in the wild because 99% of the time (seriously) the developer does not understand its use.
The use case is simple. You want an instance of a class to be able to access what would normally be private within another instance of the same class. For example, you are trying to apply an operation (e.g. multiply) on some item of state within the two classes; it has to be possible for one of the classes to reach into the other class and get a value for the operation to be applied.
Using multiply as an example:
class A
def initialize(value) = @value = value
def *(other) = value * other.value
protected
attr_reader :value
end
a1 = A.new(3)
a2 = A.new(4)
puts a1 * a2
It should be no surprise that this prints 12
when run.
If the value has been private
rather than protected
the output would be:
protected.rb:5:in `*': private method `value' called for #<A:0x000000010520e1c0 @value=4> (NoMethodError)
def *(other) = value * other.value
^^^^^^
from protected.rb:15:in `<main>'
So protected has nothing to do with inheritance (as many people seem to think), everything to do with constraining access to state only to instances of the same class.
I give the slightly more lengthy explanation there because the question does arise of why not to just use public
? The answer, to quote myself, encapsulation is vital in complex software systems. Everything that is public increases the surface area of a class and hence the cognitive overhead when working with the code. A classes public surface area should be as small as possible and protected
allows you to achieve this.
Top comments (0)