A lack of dependency injection

This is one of the smells often detected in a legacy codebase. As there is no need to test the classes in isolation, the collaborators are instantiated where they are needed, putting the responsibility for creating collaborators and using them in the same class.

Here's an example, using the new operator:

public class BirthdayGreetingService { 
 
  private final MessageSender messageSender; 
 
  public BirthdayGreetingService() { 
    messageSender = new EmailMessageSender(); 
  } 
 
  public void greet(final Employee employee) { 
    messageSender.send(employee.getAddress(), 
"Greetings on your birthday"); } }

In the current state, the BirthdayGreeting service is not unit-testable. It has the dependency to EmailMessageSender hardcoded in the constructor. It is not possible to replace this dependency without modifying the codebase (except for injecting objects using reflection or replacing objects on the new operator).

Modifying the codebase is always a source of possible regressions, so it should be done with caution. Refactoring requires tests, except when it is not possible.

The Legacy Code Dilemma. 

When we change code, we should have tests in place. To put tests in place, we often have to change code.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.242.175