1
\$\begingroup\$

I have a class which updates an object. The class takes a String id in its constructor and returns the appropriate class based on the id. I think these two methods should be separated into their own classes as returning an object based on a String id will probably have uses elsewhere in the code base.

I've considered adding the functionality which returns the object to update into its own static method:

ObjectToUpdate = Utils.getObjectToUpdate(id)

Is there a better way or a design pattern?

UpdateContestantObj c = new UpdateContestantObj(childWithParentRatingsObject.getCoupleId());
c.getContestantObj().setSortVal(singleScoringFM.getScore());
c.persistContestant();

public class UpdateContestantObj {

    private String id;
    private ContestantObj contestantToSave = null;

    public ContestantObj getContestantObj(){
        return this.contestantToSave;
    }

    public UpdateContestantObj(String id){
        this.id = id;

        SimpleSortingVector simpleSortingVector = (SimpleSortingVector)FutureContent.future.getContent(Constants.CONTESTANTS_DATA);
        Enumeration contestantsEnumeration = simpleSortingVector.elements();

        while(contestantsEnumeration.hasMoreElements()){
            final ContestantButtonField contestantButtonField = (ContestantButtonField)contestantsEnumeration.nextElement();
            if(contestantButtonField.getContestant().getId().equalsIgnoreCase(this.id)){
                contestantToSave = contestantButtonField.getContestant();
            }
        }   
    }

    public void persistContestant(){

        contestantsStore.setContents(contestantToSave); 
        contestantsStore.commit();

    }
}
\$\endgroup\$
1
  • \$\begingroup\$ In one sense if you've thought about asking then the answer is "yes". \$\endgroup\$ – user3040 Nov 23 '11 at 12:57
3
\$\begingroup\$

There's no super-design-pattern that would be beneficial here, but you could definitely benefit from some basic OO concepts like encapsulation and single responsibility.

For starters, rather than making a bunch of utility methods, it's better design to allow each class a static method like:

// inside the ContestantObj class
public static ContestantObj fromID(string ID) {
   // code to retrieve ContestantObj 
}

This way, each class is responsible for creating itself, which it should be (outside of cases where a builder or abstract factory is required).

Your UpdateContestantObj constructor should take in a ContestantObj. It shouldn't care about how the ContestantObj is created. A "Contestant Updater" should be a machine that takes in Contestants and outputs Contestants that have been updated.

Also, the naming convention of ContestantObj should simply be Contestant. We know it's an object.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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