Java: prefer Utility Class depending on a class instance or static methods?

I've a Java class that does something like this

public class MyObjectUtil {

    private final MyObject myObject;

    public MyObjectUtil (MyObject myObject){            
        this.myObject = myObject;    
    }

    public boolean isSomeInfoPresentValid() {
        return myObject.isSomething();
    }

    public void modifyMyObjectInSomeWay(String blah) {
        myObject.modify(blah);
    }

}

Every time I've to instantiate my Utility class to interact with a specific instance of MyObject.

myObject is present as a Session obj

MyObjectUtil myObjUtil = new MyObjectUtil(myObject);
myObjUtil.modifyMyObjectInSomeWay("blah");
boolean valid = myObjUtil.isSomeInfoPresentValid();

To achieve the same result I could have static functions that do the same operations using myObject every time as a method param.

public class MyObjectUtil {

    public static boolean isSomeInfoPresentValid(MyObject myObject) {
        return myObject.isSomething();
    }

    public static void modifyMyObjectInSomeWay(MyObject myObject, String blah) {
        myObject.modify(blah);
    }

}

I don't know which way I should go.
I'm using the Util class in my controllers and sometimes I need to call few methods against the same myObject instance, so to me the 1st solution seems the more correct. At the same time in this way as I've many request against my controllers I can end up creating a lot of MyObjectUtil instances everytime as myObject is related to a specific http request.

Which way should I go in my case and how should I choose in other cases?

MyObject is used in specific ways by some Utilities Classes like MyObjectXXXUtil MyObjectYYYUtil. I would like to mantain these Util methods (that modify myObject and check specific status) out of the specific MyObject implementation, as they are not specific to that. Many Util functions can interact with MyObject in a certain way.

5
задан spike07 13 December 2010 в 20:37
поделиться