DEV Community

Cover image for I thought adding one query parameter would take few minutes
Rafi Uzzaman
Rafi Uzzaman

Posted on

I thought adding one query parameter would take few minutes

For the last few years I never really cared much about design patterns. My code worked. Features shipped. Why make it complicated?

Then I got a task on a part of our production code that I had not worked on for almost a year. Add one more query parameter to a search module. I thought easy, few minutes, maybe less.

I opened the file

There were already six if-else branches. One searched by name. Another by stock. Another by tax. Another by rack. Each one had been added at a different time for a different requirement. Each one worked fine on its own.

If-else code block example

Before I wrote a single line for my new parameter, I had questions stuck in my head. Which branch does this belong to? Will this break something already working? Is this same logic sitting somewhere else too?

Those few minutes turned into almost an hour. And I had not written any code yet. I was just reading.

The query parameter was not the difficult part.

Finding the right place for it was.

The real problem

The task itself was never hard. Understanding where it belonged was hard.

Each branch existed for a real reason. Nobody did anything wrong adding them one at a time. But six branches in, the file had become a place where every new feature meant touching code that already worked. Small change, real risk, every time.

The change

I pulled each search into its own strategy class. A resolver picks the right one and runs it.

Strategy version code
Now a new search type means writing one new class. Not touching the five that already work.

Before and After comparison diagram

Why I liked this approach

  • Adding a new type does not mean editing an existing, working method
  • Testing one search type means testing one small class, nothing else
  • Reading one class to understand it, not the whole file
  • The service just picks the right strategy, it does not need to know how each one works internally

One thing I learned

You don't need to know pattern names to feel this problem. You just need to notice the feeling, too much to read before I can add my small thing. That feeling is the signal. The name comes after.

I am not saying this is the only right way to do it. It is what worked for what I had.

Next

Once this was split up, I noticed the database queries inside each piece were nearly identical, just copy-pasted with small changes. That's the next one.

Top comments (0)