java - What is the best approach to passing third party objects into constructor -


i have class takes in argument , popluate private hashmap argument.

public class table {   private map<string, string> map = new hashmap<string, string>();   private workbook workbook;   // approach 1   public table(workbook workbook) {     this.workbook = workbook;     // populate map using workbook   }    // approach 2   public table(inputstream is) {     this.workbook = workbookfactory.create(is)     // populate map   }   // approach 3  public table(file file) {    this.workbook = workbookfactory.create(file)    // populate map  } } 

workbook apache poi workbook. best approach consideration junit , mockito also.

i'm leaning towards approach 1, because according this, http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/ should avoid new keyword in constructor. don't want client have knowledge of apache poi use class.

approach 2 , 3 pretty similar. can pass in file or input stream , not worry underlying implementation. mocking hard can't mock workbook approach?

consider this:

public class table {   private map<string, string> map = new hashmap<string, string>();   private workbook workbook;    table(workbook workbook) {     this.workbook = workbook;     // populate map using workbook   }    public table(inputstream is) {        this(workbookfactory.create(is)) ;   }   public table(file file) {      this(new fileinputstream(file);  } } 

note workbook specific constructor declared package protected normal clients won't able call it, if unit cases share same package library, you'll have no problems calling constructor directly unit test. allow write separate unit tests other 2 constructors.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -