[英]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.) 在这种特殊情况下,公开了一个辅助方法,该方法将文件解析为csv表示形式(无论它是什么)。
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
通常,您不应该在初始化时就开始解析-根据单一职责原则,一种方法应该做一件事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.