What if-else

Prashant Sajwan
GoComet
Published in
3 min readMay 21, 2024

Have you seen a code having too many if-else blocks?
so many that you wish that you would not have to update anything there ever…
so many that the file is 700+ lines and difficult to navigate
so many that checking which cases are missed in the test-case file takes 15–30 minutes of your time
so many that it has bugs and too many hot-fixes

A year ago…

we were facing this problem which you might have seen or will see in the future hopefully…

how does this code look to you?

How difficult will it be if I have to update the PAWN logic???

Let’s try rewriting the code

Let’s rewrite this using aggregates

Aggregates are like Bubbles.

Imagine your software project was not one massive code-base — but a collection of small bubbles. Each bubble can be worked on independently. That means, you only need to think about what’s in the bubble at any given moment — not the entire system all at once.

Aggregates are the same. They are bubbles. Just on a smaller scale.

Base class Piece defining common structure

Pawn class defining responsibilities

Pawn class defining responsibilities

Rook class defining responsibilities

Let’s compare the final changes

Let’s compare the final changes

Let’s review the problem and the fix

So what were the problems in the initial code?

  • voids the golden rule of One class One responsibility
  • too many if-else conditions, increases complexity,
    bad Developer Experience
  • highly coupled code
  • difficult to write unit-test cases
  • large file size
  • difficult to create mind-map and navigate through the flow

How does aggregation solve this?

  • One class One Responsibility: each class is isolated.
  • removes if-else by moving code to separate classes.
  • easy to read/update
  • easy to navigate as responsibilities are divided into respective files, creating clear visibility

How we solved our problem

  • A class responsible for giving a response to a request, here the response is Freight Cost for a Lane
  • It also has to check which type of plan the current user has, Free/Trial/Paid
  • All this happening in a single File

Previously it looked something like this-

After separating Free, Trial, and Paid logic into separate classes-

--

--