Question

In an effort to reduce my NCSS count of a class (~850), I have split all of the methods into their own classes and to make things easier, I extend an abstract class that holds all the helper functions.

AbstractMethod.class

public class AbstractMethod {
    protected String requestWebPage(URL url) {
        // download a webpage as a string
    }
}

Example "account" subclass

public class AccountData extends AbstractMethod {
    public String getAccount(String sessionId){
        String webPage = requestWebPage("http://google.com/"+sessionId);
        system.out.println(webPage);
        return webPage;
    }
}

I have approx 10 of these method classes and would like to only initialize them when one of the methods in the main/base class is called:

public class MyBaseClass() {
    private static AccountData ad;

    public MyBaseClass() {
        ad = new AccountData();  // Is there a better way?
    }

    public String getAccount(String sessionId) {
        return ad.getAccount(String sessionId);
    }
}

I have tried to create an initialise function in the MyBaseClass class that accepts the subtype as a parameter and create an object based on it's class:

private void initAccount() {
    if (ad == null) {
        ad = new AccountData();
    }
}

but it's ugly and I have to have one per sub-class.

So, what's the "correct" way to do this? Sometimes when the class is called, we will only use 1 or 2 of the methods, so I don't want to have to initialise all the sub-classes each time.

Was it helpful?

Solution 2

Instantiating classes in Java is cheap. If the classes are not doing anything substantial in their contructors then just do

public String getAccount(String sessionId) {
    AccountData ad = new AccountData();
    return ad.getAccount(String sessionId);
}

Don't optimize where it's not nessesary. Profile your code before. You might be suprised how wrong your assumtions are (I know I was many times).

OTHER TIPS

It would seem to me that what you really want is to use static methods rather than abstract helper classes, perhaps along with import static.

That way, the class(es) defining those methods would, as you wish, only be initialized once the methods are actually called.

You would also not limit your inheritence structure in general to where the methods happen to be defined.

That's assuming you don't use any instance data for those methods, of course; but from the looks of your sample code, it doesn't seem that way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top