A couple of months ago I started working in a new project, and when going through the code it stroke me the amount of static methods used. Not only utility methods as collectionToCsvString(Collection<E> elements)
, but also plenty of business logic is kept in them.
When I asked the guy responsible for the rationale behind this, he said it was a way of escaping from Spring's tyranny. It goes something around this thinking process: to implement a customer receipt creation method, we could have a service
@Service
public class CustomerReceiptCreationService {
public CustomerReceipt createReceipt(Object... args) {
CustomerReceipt receipt = new CustomerReceipt();
// creation logic
return receipt;
}
}
Now, the guy said that he dislikes having classes unnecessarily managed by Spring, basically because it imposes the restriction that client classes must be Spring beans themselves. We end up having everything managed by Spring, which pretty much forces us to work with stateless objects in a procedural way. More or less what is stated here https://www.javacodegeeks.com/2011/02/domain-driven-design-spring-aspectj.html
So instead of the above code, he has
public class CustomerReceiptCreator {
public static CustomerReceipt createReceipt(Object... args) {
CustomerReceipt receipt = new CustomerReceipt();
// creation logic
return receipt;
}
}
I could argue to the point of avoiding Spring managing our classes when possible, but what I don't see is the benefit of having everything static. These static methods are also stateless, so also not very OO. I would feel more comfortable with something as
new CustomerReceiptCreator().createReceipt()
He claims that static methods have some extra benefits. Namely:
- Easier to read. Import the static method and we only need to care about the action, no what class is doing it.
- Is obviously a method free of DB calls, so performance-wise cheap; and it is a good thing to make it clear, so that the potential client does need to go into the code and check for that.
- Easier to write tests.
But I just feel there is something not completely right with this, so I would like to hear some more seasoned developers' thoughts on this.
So my question is, what are the potential pitfalls of this way of programming?
static
method that you are illustrating above is just an ordinary factory method. Making factory methods static is the generally-accepted convention, for a number of compelling reasons. Whether the factory method is appropriate here is a different matter.