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
Constructor ParametersConstructors can also take parameters, which is used to initialize attributes.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With