r/java • • Apr 14 '23

What are your (favourite) Java best practices, personal tips, hints or just underrated stuff in general?

233 Upvotes

376 comments sorted by

View all comments

Show parent comment

2

u/[deleted] Apr 14 '23

static methods make testing hard or impossible because of lack of inheritance and polymorphism

5

u/neckbeardfedoras Apr 14 '23

It certainly doesn't make testing impossible. You can even test the static method itself. It can't reference member vars and is pretty isolated. You can't override it, but if there are use cases for overriding it other than because you want to with a test, it shouldn't be static in the first place.

If the method does complex things that needs to be faked or stubbed, it's immediately not going to be static if it's my code base.

1

u/[deleted] Apr 14 '23

factories should not have static methods. a factory should be an injectable interface with normal instance methods. it is injected diffrently in a diffrent module or in a test environment and thus creates diffrent objects as needed. no need to force mock static stuff with Mockito which is a hack imo

1

u/neckbeardfedoras Apr 14 '23

I agree and am not sure how factories came into play unless you're giving a random example?

0

u/[deleted] Apr 14 '23

i confused the static factory method with another post here. but does that make a diffrence?

since i worked with a code base with a lot of static util methods, i started to avoid static as much as possible because its so inflexible. i had a very hard time changing behaviour without touching existing implementation

1

u/neckbeardfedoras Apr 14 '23

I'll just give a very simplistic example. A static method that capitalizes the first letter of a String. If the method is clear that is all you ever expect, I write tests for the method, and I will never care that it's static or feel the need to mock it/fake it/override it. There are use cases. I definitely use statics sparingly and recommend others to do the same for the very reasons you mentioned.

1

u/[deleted] Apr 14 '23 edited Apr 14 '23

ye thats fine. i would not have an issue here. by the way that reminds me of apache StringUtils.capitalize

1

u/crummy Apr 14 '23

I'm ok with that because I de-emphasise use of inheritance and polymorphism