3

Component and Service type beans and most of the other bean types are by default singleton.

In one of my code Pull requests, I declared a method as static in a Component as the method wasn't modifying any class level variables.

My code reviewer pointed out that since the class is anyways a Singleton and is going to have a single reference, he said it was unnecessary to make the method static, but rather make it a instance method.

Which way is the correct way of writing code as most of the classes in my application are Singletons?

Vineeth Chitteti
  • 1,454
  • 2
  • 14
  • 30

1 Answers1

6

Your reviewer is probably right about this one, it makes little sense to declare a static method inside a singleton; unless this static method is a factory method that returns the singleton instance itself.

I could think of two other reasons not to declare static methods in the singleton : testing is harder for static methods in some cases and you will really confuse the caller of this singleton. He/she might see that there is a static method and have a hard time understanding why it was declared like this, it would require extra reasoning as far as I see for such a method.

Eugene
  • 117,005
  • 15
  • 201
  • 306
  • 1
    A static method is not really associated with the instance, cannot access instance state, and therefore defeats the purpose of using the singleton pattern in the first place. – Tim Biegeleisen Jan 18 '19 at 11:24
  • 1
    Agreed. My take on this: it's not necessarily 'wrong' but it is unconventional and therefore confusing. Following conventions is an asset for code maintainability. – Adriaan Koster Jan 18 '19 at 11:35