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