Skip to content

Instantly share code, notes, and snippets.

@stmoerman
Last active October 5, 2016 02:40
Show Gist options
  • Save stmoerman/7e4cce4fc454c1d9a16638ffd2f969f8 to your computer and use it in GitHub Desktop.
Save stmoerman/7e4cce4fc454c1d9a16638ffd2f969f8 to your computer and use it in GitHub Desktop.
Both Refactoring and Refactoring to Patterns have approaches to resolve this.
If your (pseudo) code looks like:
class RequestHandler {
public void handleRequest(int action) {
switch(action) {
case LOGIN:
doLogin();
break;
case LOGOUT:
doLogout();
break;
case QUERY:
doQuery();
break;
}
}
}
This code violates the Open Closed Principle and is fragile to every new type of action code that comes along.
To remedy this you could introduce a 'Command' object:
interface Command {
public void execute();
}
class LoginCommand implements Command {
public void execute() {
// do what doLogin() used to do
}
}
class RequestHandler {
private Map<Integer, Command> commandMap; // injected in, or obtained from a factory
public void handleRequest(int action) {
Command command = commandMap.get(action);
command.execute();
}
}
If your (pseudo) code looks like:
class House {
private int state;
public void enter() {
switch (state) {
case INSIDE:
throw new Exception("Cannot enter. Already inside");
case OUTSIDE:
state = INSIDE;
...
break;
}
}
public void exit() {
switch (state) {
case INSIDE:
state = OUTSIDE;
...
break;
case OUTSIDE:
throw new Exception("Cannot leave. Already outside");
}
}
Then you could introduce a 'State' object.
// Throw exceptions unless the behavior is overriden by subclasses
abstract class HouseState {
public HouseState enter() {
throw new Exception("Cannot enter");
}
public HouseState leave() {
throw new Exception("Cannot leave");
}
}
class Inside extends HouseState {
public HouseState leave() {
return new Outside();
}
}
class Outside extends HouseState {
public HouseState enter() {
return new Inside();
}
}
class House {
private HouseState state;
public void enter() {
this.state = this.state.enter();
}
public void leave() {
this.state = this.state.leave();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment