This discussion is archived
8 Replies Latest reply: Nov 2, 2012 4:41 PM by rp0428 RSS

Should I use a static method or an instance method?

LosLobo Newbie
Currently Being Moderated
Just a simple function to look at a HashMap and tell how many non-null entries.
This will be common code that will run on a multi-threaded weblogic app server and potentially serve many apps running at once.
Does this have to be an instance method? Or is it perfectly fine to use a static method?

public static int countNonNullEntries(HashMap hm){
if(hm==null)return 0;
int count=0;
for(int i=0; i<hm.size(); i++) {
if(hm.get(i)!=null)
{ count++;}
}
return count;
}

OR

public int countNonNullEntries(HashMap hm){
if(hm==null)return 0;
int count=0;
for(int i=0; i<hm.size(); i++) {
if(hm.get(i)!=null)
{ count++;}
}
return count;
}
  • 1. Re: Should I use a static method or an instance method?
    rp0428 Guru
    Currently Being Moderated
    Welcome to the forum!
    >
    Just a simple function to look at a HashMap and tell how many non-null entries.
    This will be common code that will run on a multi-threaded weblogic app server and potentially serve many apps running at once.
    Does this have to be an instance method? Or is it perfectly fine to use a static method?
    >
    Sounds more like a general-purpose toolkit method that isn't related to any specific class or instance.
  • 2. Re: Should I use a static method or an instance method?
    TPD-Opitz-Consulting-com Expert
    Currently Being Moderated
    Welcome to the forum.
    968981 wrote:
    Just a simple function to look at a HashMap and tell how many non-null entries.
    This will be common code that will run on a multi-threaded weblogic app server and potentially serve many apps running at once.
    Does this have to be an instance method? Or is it perfectly fine to use a static method?
    The question is the other way around: Is there a good reason to make the method static?

    Ususally the answer is: no.

    So it is here.
    The good thing of having this method statig is that it meight decrese memory foot pring but unless you're facing memory related problem you should not think about that.

    I'm not shure if this method beeing static maks problems in multithreaded environments like the one you're aiming at. But I do know that an immutable object is always thread save. So my answer to your question is: yes, it should be non static.
    public int countNonNullEntries(HashMap hm){
      if(hm==null)throw new IlligelArgumentException("don't accept or return nulls just for convenience");
      int nullsCounter=0;
      for(Object mapValue: myMap.values()) {
        if(null==mapValue) nullsCounter++;
     }
     return nullsCounter;
    }
    bye
    TPD
  • 3. Re: Should I use a static method or an instance method?
    800268 Expert
    Currently Being Moderated
    TPD Opitz-Consulting com wrote:
    The question is the other way around: Is there a good reason to make the method static?

    Ususally the answer is: no.
    The question is: does this method need state? Yes -> method of a class with that state. No -> static.
    The good thing of having this method statig is that it meight decrese memory foot pring but unless you're facing memory related problem you should not think about that.
    I doubt there is any difference between the memory foot print of a static or not method.
    I'm not shure if this method beeing static maks problems in multithreaded environments like the one you're aiming at. But I do know that an immutable object is always thread save.
    Does the method use shared state (data)? No -> no multi threaded problems.
    Can the parameters be modified by different threads? Yes, if multiple threads modified the parameter map, but nothing you can do about it here (no way to force the calling thread to lock on whatever you lock on).
    So my answer to your question is: yes, it should be non static.
    The method should be static since it uses no state.
    It is thread-safe when only the calling thread can modify the passed map (using a synchronized or ConcurrentHashMap is not enough, since you don't call a single atomic method on the map).
    // Better use Map instead of HashMap
    // We don't care about the generic type, but that does not mean we should use a raw type
    public static int countNonNullEntries(Map<?, ?> map) {
      // whether to accept null map or not, no need for explicit exception
      // since next statement throw NPE anyway
      Collection<?> values = map.values();
      // note your method is called countNonNull, not countNull!
      // (original code it would need to by if(null != mapValue) notNullsCounter++;
      return values.size() - java.util.Collections.frequency(values, null);
    }
  • 4. Re: Should I use a static method or an instance method?
    gimbal2 Guru
    Currently Being Moderated
    Walter Laan wrote:
    The method should be static since it uses no state.
    Sure, if you accept that as a valid argument to make a method static or not. I don't, I let myself be guided by actual application design. Your argument already crashes and burns when object oriented design comes into the picture for example, its quite hard to override a static method.

    And since Java is an object oriented language, I try to stay away from elements that tend to get in the way of its very nature. Such as static methods/members. They're useful for small utility things, there they can't do much harm.
  • 5. Re: Should I use a static method or an instance method?
    800268 Expert
    Currently Being Moderated
    gimbal2 wrote:
    Walter Laan wrote:
    The method should be static since it uses no state.
    Sure, if you accept that as a valid argument to make a method static or not. I don't, I let myself be guided by actual application design. Your argument already crashes and burns when object oriented design comes into the picture for example, its quite hard to override a static method.
    I suppose that rule in its strict sense is too far (for example you could have a method expected to use state when overridden, but the default case doesn't). However, guided by the example method, it is clearly a utility method for a Map. It is very unlikely you'll ever want to override it.
    They're useful for small utility things, there they can't do much harm
    This is a small utility method? So you do agree it is better static?
  • 6. Re: Should I use a static method or an instance method?
    LosLobo Newbie
    Currently Being Moderated
    I'm assuming everyone passing in a hashmap has their own copy which is not shared.
    My question is if two threads pass in different HashMaps say one with 1 null and another with 10 nulls, is it possible they could step on each other inside the method itself and one of them to not get the correct count back. So hypothetically, if a million threads called this method at the same instance each having a different expected return value is it possible that one of them could receive an improper return value because the method is looking at someone elses hashmap and returning it's count of null values? If this was NOT static and an instance method I would expect it to return the correct count every time since each of the million instances has it's own sandbox it's running in. Thoughts?

    public static int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    }
    return count;
    }
  • 7. Re: Should I use a static method or an instance method?
    EJP Guru
    Currently Being Moderated
    You've already asked that question twice in another thread, and it has nothing to do with whether the method is static or not, which is the topic of this thread. Please stick to the point, and please don't cross-post.
  • 8. Re: Should I use a static method or an instance method?
    rp0428 Guru
    Currently Being Moderated
    >
    If this was NOT static and an instance method I would expect it to return the correct count every time since each of the million instances has it's own sandbox it's running in.
    >
    Well your expectation is making a lot of assumptions that we know nothing about. A method is a member of a class whether it is static or instance. So you can create a singleton and let all of your million instances use it.

    Walter has already answered your question. You have a standalone utility method that doesn't have any concurrency issues so doesn't need to be synchronized. You need a class to put the method in. Beyond that the method doesn't have any instance-related concerns so can be static.

    I'm sure this will generate disagreement but, in my opinion, if the method is completely independent of the class it belongs to then it should be a static method. A static method can be (and should be) called without even constructing an instance of the class it belongs to.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points