Re: What would you do?
- From: "John C. Bollinger" <jobollin@xxxxxxxxxxx>
- Date: Mon, 26 Sep 2005 22:00:22 -0500
James Yong wrote:
Let say I have a method in a helper class that is used throughout my java project. This method changes a string value to empty if it has a null value.
public final String emptyStringIfNull(String a) { return a==null?"":a; }
Would it be better to make this mathod to be static and synchronized? On one hand, I am worry about the trade off in the slowdown caused by synchronization.. On the other, I find it a sore to always to instantiate the helper class.
What are your views on it?
Others have covered the synchronization angle quite well. Most have been satisfied with making the method static, and some have even encouraged it. In truth, the method in question has so specific an apparent contract that making it static probably bears almost no risk. NEVERTHELESS, in my newfound campaign against wanton use of static class members, I'll point out that there is at least a minor cost to making the method static: static methods are not polymorphic. If you make the method static then you give up the possibility of overriding it on some subclass of your utility class to do something such as count the number of times it is invoked, log its activity, or some such.
Are you likely to want to do such things? Probably not, in this particular case. All the same, it should not be taken for granted that any method that *could* be made static necessarily *should* be made static. If you have already implemented the method as an instance method, then I'd leave it that way. Why fix it if it isn't broken? If you decide to make it static anyway then be sure to change all invocations to use the static invocation syntax (ClassName.foo()); invoking a static method via a reference-type expression is evil.
-- John Bollinger jobollin@xxxxxxxxxxx .
- Follow-Ups:
- Re: What would you do?
- From: Oliver Wong
- Re: What would you do?
- References:
- What would you do?
- From: James Yong
- What would you do?
- Prev by Date: Re: library for rendering HTML
- Next by Date: Re: XML Parsing Problems with SAX xerces
- Previous by thread: Re: What would you do?
- Next by thread: Re: What would you do?
- Index(es):
Relevant Pages
|