Changes between Version 46 and Version 47 of ProgrammingGuidelines


Ignore:
Timestamp:
07/12/11 16:59:06 (8 years ago)
Author:
welberge
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • ProgrammingGuidelines

    v46 v47  
    280280} 
    281281}}} 
     282=== Creating testable code: Dependency Injection === 
     283{{{ 
     284class Foo 
     285{ 
     286  private final Bar bar; 
     287  public Foo() 
     288  { 
     289    bar = new Bar(); 
     290  } 
     291} 
     292Is less testable than this: 
     293class Foo 
     294{ 
     295  private final Bar bar; 
     296  public Foo(Bar b) 
     297  { 
     298    bar = b; 
     299  } 
     300} 
     301}}} 
     302Because in the first case you cannot easily mock bar, which makes it hard to 
     303test Foo in isolation. The second form is called dependency injection (you inject 
     304the dependency to bar into the constructor). When using dependency injection, a convenience 
     305no-argument constructor can still be added: 
     306{{{ 
     307class Foo 
     308{ 
     309  private final Bar bar; 
     310  public Foo(Bar b) 
     311  { 
     312    bar = b; 
     313  } 
     314  public Foo() 
     315  { 
     316    this(new Bar()); 
     317  } 
     318} 
     319}}} 
    282320 
    283321[[ViewTopic()]]