Skip to content

Instantly share code, notes, and snippets.

@phstc phstc/Legacy.java
Created Jul 14, 2012

Embed
What would you like to do?
Refactoring Legacy Code - Removing strong dependencies
/*
* Legacy code with strong dependency with OrderDAO.
*/
public class OrderDAO {
public boolean delete(int id) {
// ...
}
}
public class OrderService {
public boolean delete(int id) {
return new OrderDAO().delete(id);
}
}
/*
* It isn't unit testable, OrderDAO should be mocked
*/
public class OrderServiceTest {
@Test
public void shouldDeleteAnOrder() {
OrderService subject = new OrderService();
assertTrue(subject.delete(1));
}
}
/*
* First Refactory - It isn't the state of art, but at least it is unit testable.
* Easy to change, no side effect (in theory).
* OrderService still having a strong dependency of OrderDAO.
*/
public class OrderService {
public boolean delete(int id) {
return getOrderDAO().delete(id);
}
protected OrderDAO getOrderDAO() {
return new OrderDAO();
}
}
public class OrderServiceTest {
@Test
public void shouldDeleteAnOrder() {
final OrderDAO orderDAO = mock(OrderDAO.class);
doReturn(true).when(orderDAO).delete(anyInt());
/*
* Anonymous class rocks
*/
OrderService subject = new OrderService(){
protected OrderDAO getOrderDAO(){
return orderDAO;
}
};
assertTrue(subject.delete(1));
}
}
/*
* Second Refactory - A little bit better, still having a strong dependency of OrderDAO,
* but at least it will be created once.
*/
public class OrderService {
private OrderDAO orderDAO;
public OrderService() {
orderDAO = new OrderDAO();
}
public OrderService(OrderDAO orderDAO) {
this.orderDAO = orderDAO;
}
public boolean delete(int id) {
return orderDAO.delete(id);
}
}
public class OrderServiceTest {
@Test
public void shouldDeleteAnOrder() {
final OrderDAO orderDAO = mock(OrderDAO.class);
doReturn(true).when(orderDAO).delete(anyInt());
OrderService subject = new OrderService(orderDAO);
assertTrue(subject.delete(1));
}
}
/*
* Third Refactory - The direct dependency of OrderDAO is optional just for backward compatibility.
*/
public interface Persistable {
public boolean delete(int id);
}
public class OrderDAO implements Persistable {
public boolean delete(int id) {
// ...
}
}
public class OrderService {
private Persistable orderDAO;
public OrderService() {
orderDAO = new OrderDAO();
}
public OrderService(Persistable orderDAO) {
this.orderDAO = orderDAO;
}
public boolean delete(int id) {
return orderDAO.delete(id);
}
}
public class OrderServiceTest {
@Test
public void shouldDeleteAnOrder() {
final Persistable orderDAO = mock(Persistable.class);
doReturn(true).when(orderDAO).delete(1);
OrderService subject = new OrderService(orderDAO);
assertTrue(subject.delete(1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.