Java Clean Code Tutorial #10 – AVOID Static Methods

Published: 27 March 2017
on channel: Philip Starritt
4,425
44

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/testin...

Spring IO https://spring.io/

Spring Framework https://projects.spring.io/spring-fra...

Dependency Injection https://en.wikipedia.org/wiki/Depende...


On this page of the site you can watch the video online Java Clean Code Tutorial #10 – AVOID Static Methods with a duration of hours minute second in good quality, which was uploaded by the user Philip Starritt 27 March 2017, share the link with friends and acquaintances, this video has already been watched 4,425 times on youtube and it was liked by 44 viewers. Enjoy your viewing!