Exploring Encapsulation
What is encapsulation? Perhaps another abstract principle that we should only care about regurgitating for a job interview? Principles can often seem that way: handy to know about but often discarded. However, in order to create maintainable modular Encapsulation is key. As a starter for ten:
Encapsulation is the packing of data and functions into a single object.
Perhaps a better description of exactly what this means can be found here. By following encapsulation we are trying to ensure that an objects internal data can only be accessed and modified by itself rather than through the public interface.
The following example shows a very simplistic case of badly encapsulated code.
class Person
attr_accessor :first_name, :last_name
def initialize(first_name, last_name)
@first_name = first_name
@last_name = last_name
end
def full_name
@full_name = first_name + " " + last_name
end
end
The simple reason that this is bad code is that if we create a new person another object can directly access the person and change their name at will. Their private data is accessible to the outside world. To refactor this we would simply replace our example with the following code:
class Person
attr_reader :first_name, :last_name
def initialize(first_name, last_name)
@first_name = first_name
@last_name = last_name
end
def full_name
@full_name = first_name + " " + last_name
end
end
The person can now tell people what their name is but it cannot be modified at will by outside entities which not only follows the principle of encapsulation but also reflects reality.
As the examples illustrate, a good guideline for sticking keeping your code well encapsulated stick to the "Tell, don't ask principle". That is to say that objects should tell other objects about themselves. Or put negatively, no object should be internally queried by another.
Why is this important to us? Simply put as projects get bigger and bigger if objects are avoiding the use of other objects public interfaces then when refactoring, code often has to be changed both in the asking and the telling object leading to a higher chance that the overall program will break when it is run. As a new developer remembering this can be a life saver!