Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

prefer static methods over non static methods

 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a utility class:



and now I use that in (a stateless ejb) class:




Is the use of a static method better than using dependency injection?








For both versions, everything works as expected, but I am unsure about the quality of my code (Performance. Maintenance, ..). What version is really better?



 
Campbell Ritchie
Sheriff
Pie
Posts: 49466
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What static methods? I can't see any static methods. I can see static nested classes, but that is something different. A static nested class is easier to use than non-static because you don't have to create an instance of the outer class.
 
Matthew Brown
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Assuming that you turn them into proper methods, instead of inner classes....

The advantage of the injection approach is that it makes it simple to provide an alternative implementation, whereas with a static method you're tightly coupled to that particular method. So I would say it depends on whether there's any chance you'll want to have a different implementation. In the example you've given, it seems unlikely. But if the utility method was more complicated, and especially if it had dependencies on other components, then being able to mock up an alternative might be very useful for unit testing, for example.
 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh sorry, I wrote it false:

I really mean a static method:



I have corrected it above. But the questions is the same.
 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The advantage of the injection approach is that it makes it simple to provide an alternative implementation, whereas with a static method you're tightly coupled to that particular method.


Thank you, this is a really a good point!

Are there any risks or cautions when using static methods within an ejb-container ? I guess, static Methods bypasses some typical ejb-states. (EntityManager, Transaction, Security,..?).


But if the utility method was more complicated, and especially if it had dependencies on other components..


Yes, my static method calls other static methods from other classes. So should I go for dependency injection? I am actually using it, but I have thought to provide static methods as much as I can, is a good design choice.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic