mercredi 9 septembre 2015

How can I avoid dependencies between methods?

I have the following method:

protected ArrayList<String> prepInstaller(RemoteSession session) {
    ArrayList<String> installCommand = new ArrayList<String>();
    installer.setInstallOption(getCommand());
    installer.setInstallProperties(generateInstallProperties());
    installer.setTestHome(getTestHome(session));

    switch (installer.getInstallOption()) {
    case ("addon"):
        installer.setAddOnScriptPath(getAddOnScriptPath(session, true));
        installer.setAddOnImageLocation(getAddOnPath(session, true));
        installCommand.add(installer.getInstallCommand());
        break;
    case ("install"):
        installer.setImageLocation(getImageLocation(session, true));
        installCommand.add(installer.getInstallCommand());
        break;
    case ("patch"):
    case ("rollback"):
        installer.setPatchLocationPath(getPatchPath(session, true));
        for(String currentPatch: installer.getPatches()) {
            installCommand.add(installer.getInstallCommand(currentPatch));
        }
        break;
    }

    return installCommand;
}

My problem is that this line:

installCommand.add(installer.getInstallCommand());

contains installer.getInstallCommand() which will contain null objects unless the following are run:

installer.setInstallOption(getCommand());
installer.setInstallProperties(generateInstallProperties());
installer.setTestHome(getTestHome(session));

among others... The method has dependencies on previous methods being run which is not desirable. I have defined installer as a static factory:

public static InstallData getInstance() {
    if (instance == null) {
        instance = new InstallData();
    }
    return instance;
}

I have looked at using the builder pattern but it seems a bit unwieldly. I couldn't find a tidy version of it. I don't want to use a constructor, as it will be messy and I will need several of them.

I have also tried to construct an object containing all of the set methods and then passing the object into a new class which returned getInstallCommand(), but that got quite messy also.

Ideas welcome :)

Aucun commentaire:

Enregistrer un commentaire