Skip to content

Instantly share code, notes, and snippets.

@Mattia46
Created October 21, 2015 10:03
Show Gist options
  • Select an option

  • Save Mattia46/2339aa38b9343842bae9 to your computer and use it in GitHub Desktop.

Select an option

Save Mattia46/2339aa38b9343842bae9 to your computer and use it in GitHub Desktop.

Encapsulation is the packing of data and functions into a single component.

Encapsulation means that the internal representation of an object is hidden from the outside. Only the object can interact with its internal data. Public methods can be created to open a defined way to access the logic inside an object.

class Document  
  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def set_name(name)
    @name = name
  end
end
d = Document.new('name1')  
d.set_name('name1')

Can easily change the value of my document name without having to know how the Document class is implemented. From Samurails Give an example of a poorly-encapsulated class that uses an attr_accessor. The example above is poorly encapsulated. Explain why it is a poor example of Encapsulation User should not be able to write to name directly bypassing the set_name method. Refactor the class to better use Encapsulation.

class Document  
  attr_reader :name

  def initialize(name)
    @name = name
  end

  def set_name(name)
    @name = name
  end

  private

  attr_writer :name

end
@sjmog
Copy link

sjmog commented Oct 21, 2015

I don't think the class is well encapsulated in the second instance. I could still do something like this:

doc = Document.new("my_file")
weird_object = SomeClass.new(:all, :kinds, :of, :properties)
doc.set_name(weird_object)
# => <#Document:0007x22afdd245 @name=<#SomeClass ... >>

i.e. mess around with the Document's name from outside.

Also, you define a private attr_writer but never do anything with it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment