开发者

Reinitialize a Ruby object

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? Thanks!


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


It works but is a little unconventional. Most likely you will want to add more functionality to the constructor. What might be better is to use a private method the actually zeroes out the arrays and then your intent will be more clear in the code:

class Clipboard
  def initialize
    [...]
    setup
    [...]
  end

  def reset
    setup
  end

  private

  def setup
     @folders, @files = [], []
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜