vendredi 26 août 2016

Nested classes for TDD?

When I write code following TDD I often find myself creating small classes to make the testing easier. However often those small classes are only used by one class so you could argue that cohesion suffers since now the logic which had strong cohesion in one class is spread through multiple classes.

So the question is there a practice of using nested package private classes to split up the logic. Unit tests can still inject mock implementation of these classes while the cohesion doesn't suffer as much since these nested classes would still live under one class.

So instead of :

@Component
public class A {

  @Autowire
  private B b; 

  public void doPublicStuff(){
     for (...){
       b.doImplementationStuff(..);      
     }
  }  
}

@Component
class B {
  doImplementationStuff(){}
}

It would be something like

@Componenet 
public class A {

  // Allow injection for unit tests
  A(B b, SomeOtherClass someOtherClass){
   this.b = b;
   this.someOtherClass = someOtherClass;
  }

  public A(){ 
     // gets instantiated in default constructor to expected implementation
     b = new B();
  }

  private B b; 

  @Autowire
  private SomeOtherClass someOtherClass;

  public void doPublicStuff(){
     for (...){
       b.doImplementationStuff(..);      
     }
  }  

  class B {
    doImplementationStuff(){}
  }
}

Aucun commentaire:

Enregistrer un commentaire