简体   繁体   中英

Ruby class with public method

I have a class with a public method, for example:

class CsvParse
  def initialize(csv_file)
    @csv_file = csv_file
  end
  def parse
    ...
  end
end

csv_parse = CsvParse.new('csv_file.csv')
csv_parse.parse

But the design of the class can be like this too:

class CsvParse
  def initialize(csv_file)
    @csv_file = csv_file
    parse
  end

  private
  def parse
    ...
  end
end

csv_parse = CsvParse.new('csv_file.csv')

What is the best practice?

In this particular case there is a helper method exposed, that parses file to it's csv representation (whatever it is.)

Semantically the best call would be:

csv_parse = CsvParser.parse 'csv_file.csv'

So, I would go with declaring constructor private, preventing these objects from being directly created:

class CsvParser
  def initialize ...
  end
  private_class_method :new

  def self.parse *args
    CsvParser.send(:new, *args).send(:parse)
  end
private
  def parse ...
end 

通常,您不应该在初始化时就开始解析-根据单一职责原则,一种方法应该做一件事情。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM