Is it acceptable having parameter in class constructor?
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)
How can a class constructor has a parameter of the same class?
When the class is compiled, all it needs access to is the declaration of the class, not the full implementation.
Put differently, when compiling the constructor
public Example(Example e) {
value = e.getValue();
}
all it needs to know is that there exists a class named Example
and that it has a method getValue
. This information can be gathered in a separate pass over the source files, prior to actually trying to compile the code.
(Btw, a constructor doesn't work much differently from a method. At first glance it may seem like a constructor needs to be compiled before any method is compiled, but that reasoning mixes up compile-time issues with run-time issues.)
Having lots of parameters in a constructor
In general, if you find yourself have too many parameters, that means you don't have enough low-level classes. In your case, you could have a
class Name { /* fname, lname, initial, */ }
and perhaps aclass Contact { /* email, phone */ }
When you extend your class, have the constructor take the base as one parameter, and then add the new extra parameters. (You probably mean Employee will extend Person, rather than vice versa, so
public Employee (Person person, Company company, String employeeId) { super(person); this.company = company; this.employeeId = employeeId; }
Good question!
Constructor Parameters vs Method Parameters?
Pass them to the method. That way you can copy to more than one location without having to reinstantiate FileCopier
, and do other operations that may require other params. In this case you can make the methods static, so no instantiation is needed at all. You'll noticed this is the way the C# File
class works, for example.
Constructor requiring many input arguments
If there are really that many parameters, it could that your class is trying to be too many things at the same time. Take this as a hint that it could be broken down into smaller classes.
Alternatively, you could make the constructor package private, and use a builder in the same package to instantiate it.
Constructor Parameters - Rule of Thumb
With that many parameters, it's time to consider the Builder pattern. Create a builder class which contains all of those getters and setters, with a build() method that returns an object of the class that you're really trying to construct.
Example:
public class ReallyComplicatedClass {
private int int1;
private int int2;
private String str1;
private String str2;
// ... and so on
// Note that the constructor is private
private ReallyComplicatedClass(Builder builder) {
// set all those variables from the builder
}
public static class Builder {
private int int1;
private int int2;
private String str1;
private String str2;
// and so on
public Builder(/* required parameters here */) {
// set required parameters
}
public Builder int1(int newInt) {
int1 = newInt;
return this;
}
// ... setters for all optional parameters, all returning 'this'
public ReallyComplicatedClass build() {
return new ReallyComplicatedClass(this);
}
}
}
And in your client code:
ReallyComplicatedClass c = new ReallyComplicatedClass.Builder()
.int1(myInt1)
.str2(myStr2)
.build();
See pages 7-9 of Effective Java Reloaded [pdf], Josh Bloch's presentation at JavaOne 2007. (This is also item 2 in Effective Java 2nd Edition, but I don't have it handy so I can't quote from it.)
Related Topics
Why Is 032 Different Than 32 in Ruby
Show Markers on Google Maps Dynamically -Rails 3.2
How to Prevent Rails Controller Generator to Modify Config/Routes.Rb
Parsing Large Xml with Nokogiri
How to Create an Operator for Deep Copy/Cloning of Objects in Ruby
Does Anyone Have Parsing Rules for the Notepad++ Function List Plugin for Ruby and Rake
How to Simplify or Clean Up This Anagram Method
Unexpected Keyword_End, Expecting $End (Syntaxerror)
Minitest, Test::Unit, and Rails
Bundle Uses Wrong Ruby Version
How to Get a Listing of Only Files Using Dir.Glob
Using Form_For Tag with Get Method
Monitor Ruby Processes with Monit
Can't Find Gem Railties (>= 0.A) with Executable Rails (Gem::Gemnotfoundexception)
Rake Test Very Slow in Windows
Best Way to Find_Or_Create_By_Id But Update the Attributes If the Record Is Found