1

I have a class which contains two methods.

These methods add & remove an object to a datastore.

The class which contains these methods has a no arg constructor but each of the two methods takes a variable amount of parameters for the addition / removal.

Should these methods be static and if not should the method parameters be initialized within the structure as instance variables instead of at the method level ?

pseudo code :

   class Utility {

       public Utility(){
    }

    public void add(String arg1, int arg2, boolean arg3){
    //add logic here
    }

    public void remove(int arg1, char arg2, float arg3){
    //remove logic here
    }
    }
1
  • 1
    Are the parameters something that change between invocations of the add and remove functions? What does each parameter mean? Knowing the use of the parameters would help generate better comments on this. May 22, 2012 at 2:24

2 Answers 2

0

Something to consider regarding if the methods should be static or not is the actual state that the class instances can contain. If the methods are static, then they can not access any state stored in object instances, like DB connections, unless of course the instance is passed-in to the static method (Yuk, ugly).

If there are other class instance variables that need to be accessed by these methods, apart from the DB connection, then these methods probably should not be static.

As for the actual method parameters and storing them, that just depends on the situation at-hand, and is hard to answer. But in general I would not store those values via methods intended to add or remove from a DB, but instead use a constructor or attribute setters, then call add/remove without said attributes. But again, this just depends.

As mentioned in @Carl Manaster's answer, if this class just becomes a container for several static methods, then a refactor should be considered. You may consider a refactor which would involve making some sort of a POJO (or persist-able hierarchy) out of the objects to be persisted and create a separate Persistence class (or class hierarchy) which would take the POJOs as method arguments.

1

If you have no reason to persist the values between method calls, as would appear to be the case from your example code, then the methods should be static. When you have too many static methods, it's a "smell" that perhaps a new, smaller class is waiting to be "sprouted"; in that new class, what are static methods in the original class might become non-static, and some of the data that is currently passed as parameters might become fields in the new class.

1
  • +1, I mentioned you in my answer, but with a different twist.
    – Brady
    May 22, 2012 at 11:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.