I am wondering if I am implementing the reinitialization of a Ruby object correctly.
I have a class called Clipboard
that holds folders and files. When creating a new clipboard object, it is always empty: there are no folders or files on it. I also have a reset
method that clears all the folders and files from the clipboard.
At first my code looked liked this:
class Clipboard
def initialize
@folders = []
@files = []
end
def reset
@folders = []
@files = []
end
end
But the fact that reset
and initialize
are exactly the same annoyed me. Besides resetting a clipboard object is the same as reinitializing it. So I changed my code to:
class Clipboard
def initialize
@folders = []
@files = []
end
def reset
initialize
end
end
This works, but I was wondering if it is the correct way of going about reinitializing my object? Are there any reasons why I should not be calling initialize
from an instance method?
This code smells to me as it doesn't seem like good practice to call the constructor from within the an instance. I would simply refractor it like so:
class Clipboard
def initialize
setup
end
def reset
setup
end
private
def setup
@folders = []
@files = []
end
end