Is it permissible to have a parameter in the class constructor?

a rubygem, which I write, and it is useful for counting the occurrence of words in the text, I choose to put 3 parameters in the class constructor.

The code works, but I want to reorganize it for convenience. In your experience, is it easier to read / mantain / to use as an API a class with a constructor without parameters and with many seters / getters methods or with code like this with all the parameters in the constructor?

TIA

Paolo

def initialize(filename, words, hide_list)

  if ! filename.nil?
    @filename = filename
    @occurrences = read
  else
    @filename = STDIN
    @occurrences = feed
  end

  @hide_list = hide_list
  @sorted = Array(occurrences).sort { |one, two| -(one[1] <=> two[1]) }
  @words = words

end
+5
source share
3 answers

You can do this rails path where the parameters are set in a hash:

def initialize(filename = nil, options = {})
  @hide_list = options[:hide_list]
  @words = options[:words]

  if filename
    @filename = filename
    @occurrences = read
  else
    @filename = STDIN
    @occurrences = feed
  end

  @sorted = Array(occurrences).sort { |one, two| -(one[1] <=> two[1]) }

end

Then you can call it like this:

WC.new "file.txt", :hide_list => %w(a the to), :words => %w(some words here)

or that:

wc = WC.new
wc.hide_list = %w(a the is)
wc.words = %w(some words here)
+3
source

, , , , API.

, getter/setter , .. , , - .

+3

, Ruby, , . .

0

All Articles