Load file inside a constructor, bad practice?

Viewed 197

Is this a bad practice? I've seen few peoples say that constructor should not do the real work.

class FooConfig {
   public FooConfig(File file) {
      loadFile(file);
   }

   private void loadFile(File file) {
      // do something...
   } 
}

Or I should do this instead?

class FooConfig {
   private final File file;

   public FooConfig(File file) {
      this.file = file;
   }

   public void loadFile(File file) {
      // do something...
   }
}
FooConfig config = new FooConfig(file);
config.loadFile();

Thank you.

1 Answers

It depends, but in general, unless you know what you're doing, there is nothing wrong in it. It's actually more simpler to initialize in the constructor. This is what the caller of your code would expect anyway: an object accepting a file is expected to process it upon initialization. The caller would also avoid bugs where they forget to call the initialization method manually.

I'm pretty sure that if you look at third-party libraries (e.g. Spring), you will find occurrences of such constructors accepting files. For example, FileSystemXmlApplicationContext offers a parameter to do a "refresh" based on the input files, so that the user can have control over the refreshing of the context (either the constructor does it, or the refresh has to be done manually).

Related