My problem is to create a class which would let to use an object (settings container or simply container) safely. I have more than 10 methods where I have to repeat the same actions: save the the container’s state, change the state, do some job, restore the state, return results. Example:
public List<String> childKeys() {
//saving state (repeated many time in other methods)
final String clientGroup = clientSettings.group();
//changing state (repeated many time in other methods)
clientSettings.endAllGroups();
clientSettings.beginGroup(currentGroup);
//doing job (exclusive for each method)
final List<String> childKeys = clientSettings.childKeys();
//restoring state (repeated many time in other methods)
clientSettings.endAllGroups();
clientSettings.beginGroup(clientGroup);
return childKeys;
}
I need doing this to prevent a user changing system settings and want to avoid writing the same code many times.
Do you see any way to redesign the code so the methods calls could be prepared and cleaned up automatically?
If I understand you well, you want to make sure a certain code is called before and/or after a certain set of methods?
Have you considered AOP? That would be a nice way to add the same code to a bunch of method calls without polluting your code with superclasses / extra-calls all over the place.
Spring-AOP is a nice implementation of it, which uses AspectJ under the hood. Have a look.