Reputation: 959
Below is an attempt to create a reusable solution for the control break pattern. It is built on Command Pattern (Action and Test interfaces). However, I realized my old COBOL thinking got in the way, because this solution is predicated on each of the Action and Test objects having access to "global variables." And my immediate thought after that was "the need for variable access like this (wider scope) must be an already invented wheel.
How to give all the Actions and Tests below access to a group of variables -- an indeterminate group because this is supposed to be a reusable solution??
public class ControlBreak {
public static void controlBreak(Action initialize,
Test endOfInput,
Test onChange,
Action breakAction,
Action detailAction,
Action getNext) {
boolean hasProcessed = false;
getNext.execute();
for (initialize.execute();endOfInput.test();detailAction.execute(),getNext.execute()) {
hasProcessed = true;
if (onChange.test()) {
breakAction.execute();
}
detailAction.execute();
}
if (hasProcessed) {
breakAction.execute();
} else {
// throw empty input exception
}
}
}
Upvotes: 0
Views: 318
Reputation: 959
Thanks to millimoose, I got where I was going. Here's the fleshed out code, for reference:
public class ControlBreak<TParams> {
public TParams controlBreak(Action<TParams> initialize,
Test<TParams> endOfInput,
Test<TParams> onChange,
Action<TParams> breakAction,
Action<TParams> detailAction,
Action<TParams> getNext,
TParams params) {
boolean hasProcessed = false;
getNext.execute(params);
for (params = initialize.execute(params);endOfInput.test(params);params = detailAction.execute(params),params = getNext.execute(params)) {
hasProcessed = true;
if (onChange.test(params)) {
breakAction.execute(params);
}
detailAction.execute(params);
}
if (hasProcessed) {
breakAction.execute(params);
} else {
// throw empty input exception
}
return params;
}
}
Upvotes: 1
Reputation: 39980
On a few re-reads, it seems like you're trying to abstract a certain control flow, where the parameters can be coupled. In this case, I'd look into generics. I.e. something like this:
public static void <TParams> controlBreak(Action<TParams> initialize, ..., TParams params) {
// ...
initialize.execute(params)
// ...
}
That way this method will remain reusable, but the various actions / tests can still accept a strongly-typed set of parameters/variables. (The concrete type of TParam
.)
Upvotes: 1