From Assembly to Defusing IFs: A Journey of Innovation and Impact.
The IF Strategy is the approach of using an IF statement (or equivalent conditional logic) to handle a change in behavior.
When faced with a request to alter program behavior based on certain conditions, the immediate solution often involves wrapping the existing logic with an IF.
For example:
if (condition) { doSomething(); } else { doSomethingElse(); }
This solves the problem quickly but introduces potential long-term issues as conditions multiply.
"Can you calculate this differently if this happens?"
The typical response? Add an IF:
if condition: do_something() else: do_something_else()
This works, but the real question is: What happens when there are ten conditions? Twenty?
The following examples provide basic ideas for avoiding IF statements.
Note: These examples are not exhaustive—they're just the start of your journey away from the IF Strategy.
Try:
actions = { "start": start_task, "stop": stop_task, "pause": pause_task, } actions[action]()
Instead of:
if action == "start": start_task() elif action == "stop": stop_task() elif action == "pause": pause_task()
Try:
abstract class Shape { abstract void draw(); } class Circle extends Shape { void draw() { System.out.println("Drawing a Circle"); } } class Square extends Shape { void draw() { System.out.println("Drawing a Square"); } } // Usage Shape shape = new Circle(); shape.draw();
Instead of:
if (shape.type.equals("circle")) { shape.drawCircle(); } else if (shape.type.equals("square")) { shape.drawSquare(); }
Try:
class State: def handle(self): pass class IdleState(State): def handle(self): print("Handling idle state") class RunningState(State): def handle(self): print("Handling running state") class StoppedState(State): def handle(self): print("Handling stopped state") # Usage current_state = RunningState() current_state.handle()
Instead of:
if state == "idle": do_idle() elif state == "running": do_running() elif state == "stopped": do_stopped()
The IF Strategy often feels like the easiest path—but it’s a path that leads to tangled logic and rigid systems. These simple examples are just the beginning. Avoiding IFs is an ongoing process of thinking differently about code.
Want to learn more? Stay tuned for projects and workshops that go beyond these elementary examples. This is just the start.