I have recently been thinking about the following design consideration: let's say I have an object that is able to read in a file and return some result. Would you say this object should rather expose an interface:
void readFromFile(File file);
or would you design it to have a method
void readFromFile();
and provide necessary values in constructor? The second option seems to be fine if we want to have multiple parameters for constructor and use a builder to build fileReaders based on some user preferences... What do you think?
Constructors are special methods used to initialize objects whereas methods are used to execute certain statements. Following are the important differences between Constructors and Methods. Constructor is used to create and initialize an Object .
Example. Create a constructor: public class Main { int x; public Main() { x = 5; } public static void main(String[] args) { Main myObj = new Main(); System.out.println(myObj.x); } } Try it Yourself ». Note that the constructor name must match the class name, and it cannot have a return type (like void ).
Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order. You can use any data type for a parameter of a method or a constructor.
Also note that the constructor is called when the object is created. All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you.
It depends on the wider context of the object.
If your object is highly cohesive, i.e. it has a narrow scope in its purpose which is primarily to read from a particular file, then it should be defined in the constructor. In terms of OO design, high cohesion is generally a good thing - so I'd generally favour this option. If your application is multi-threaded and thus your object needs to be thread safe, then I'd definitely lean towards this - I'd argue this approach makes it easier to build granular, immutable objects which is a great help when trying to avoid race hazards.
If your object is responsible for many other tasks, you don't really need to worry about concurrency, and it doesn't really make sense for the file to be included as part of the state of the actual object, then the method that takes the parameter would arguably be the best choice.
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