Setting Variables in Constructor vs Within Method in Java

javarefactoring

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
    }
    }

Best Answer

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.