Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - method vs constructor arguments

Tags:

java

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?

like image 384
Bober02 Avatar asked Nov 18 '12 23:11

Bober02


People also ask

What is the difference between constructors and methods in Java?

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 .

What is an example of a constructor in Java?

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 ).

What is an argument in a method?

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.

When is the constructor of an object called?

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.


1 Answers

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.

like image 193
Michael Berry Avatar answered Oct 18 '22 11:10

Michael Berry