Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it acceptable having parameter in class constructor?

a rubygem I'm writing and that is useful for counting word occurrences in a text, I choose to put 3 parameters in class constructor.

The code is working, but I want to refactor it for niceness. In your experience, it's easier to read/mantain/use as API a class with a constructor with no params and a lot of setters/getters method or a code like this one, with all the params 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
like image 734
Paolo Perego Avatar asked Jul 09 '10 15:07

Paolo Perego


People also ask

Can a class constructor have parameters?

Constructor ParametersConstructors can also take parameters, which is used to initialize attributes.

Should a constructor have parameters?

1. No-argument constructor: A constructor that has no parameter is known as the default constructor. If we don't define a constructor in a class, then the compiler creates a default constructor(with no arguments) for the class.

Can a constructor have a parameter list?

The constructor is used when an object is constructed. Most of the work in constructing an object is automatically done by the Java system. Usually you need to write only a few statements that initialize a instance variables.

Can a Java constructor have parameters?

A Java class constructor initializes instances (objects) of that class. Typically, the constructor initializes the fields of the object that need initialization. Java constructors can also take parameters, so fields can be initialized in the object at creation time.


1 Answers

You could do it the rails way, where options are given 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 this:

wc = WC.new
wc.hide_list = %w(a the is)
wc.words = %w(some words here)
like image 65
mckeed Avatar answered Oct 16 '22 13:10

mckeed