HomeОбразованиеRelated VideosMore From: Philip Starritt

Java Clean Code Tutorial #10 – AVOID Static Methods

21 ratings | 1844 views
Java Static vs Non Static? When developing functionality, I always give my code and design extra thought before declaring a Java Static Method. Why? I feel that Static Methods are Ok and great for: - Utility classes that contain static methods that you would not need to mock out in tests. These can include functions that don’t do any networking & only use their parameters to compute the return value. E.g. Apache Commons StringUtils. - For use as a static factory method instead of a public constructor. These are great for using a descriptive name to construct classes. This can improve code readability. Static methods are easy to test themselves. The real challenge arises when another class & method calls that static method and that static method performs functionality that you would typically need to mock out in an automated test. Such functionality can include Networking, IO, Calling external services etc. Mocking out that static method can cause a good a headache as you would need to use frameworks or utilities to assist, e.g. PowerMock. This is unnecessary work and the code smell should be flagged by your initial unit tests. An alternative to calling static methods would be to remove static and use dependency injection to inject an instance of that class as a dependency. This would provide you with flexibility in your tests to easy replace the dependency with a mock or stub. This is easy with the likes of Spring Framework. Software is written once and read hundreds of times. So let’s make our fellow developers life easier. Why clean code? Simple. Clean code allows us to confidently make changes and deliver more features quickly to our customers. Don’t forget to subscribe for your regular dose of Java Tutorials! STOP THE ROT. Till episode 11, Philip Recorded in the Mourne Mountains, Slieve Donard. Newcastle, County Down, Northern Ireland. A great post on static methods by Christian Posta http://blog.christianposta.com/testing/java-static-methods-can-be-a-code-smell/ Spring IO https://spring.io/ Spring Framework https://projects.spring.io/spring-framework/ Dependency Injection https://en.wikipedia.org/wiki/Dependency_injection
Html code for embedding videos on your blog
Text Comments (2)
Ian McDevitt (2 years ago)
Well said, avoid where possible. Static variables are also a real pain and pet hate of mine. The rare exception for methods is where you can't extend the class or decorate (in Java anyway) so you create a bag of pure function statics like StringUtils. These can be tested without mocking because here's no state.
Ar A (2 years ago)
hey can you do also a tutorial with bcrypt password and resetting ?

Would you like to comment?

Join YouTube for a free account, or sign in if you are already a member.