Implementing the Strategy Pattern With Spring

introdev.io
Javarevisited
Published in
3 min readMar 29, 2020

--

Image by Diese lizenzfreien Fotos darfst du zwar verwenden Pixabay

My personal goal as a software engineer is to build software that works, solves problems, and is maintainable, scalable and performant. To accomplish this is very important to write code in an organized way. so it is clear what each piece of code is doing, avoid duplicates and improve maintainability.

A few weeks ago, we had a requirement where we needed to ingest the same object, but based on one of the fields, do a completely different processing for it. The easiest and quickest approach might be to create different classes with different logic and simply have multiple “if/else” statements to execute the desired process. But what if we don’t have two processes but maybe 5 or 10 in the future?

I’m probably exaggerating, but it’ll be 9 “if” and 1 “else” along with 10 other classes instantiated with the implementation for each process. As you imagine, this is very difficult to maintain, scale, read and something that I would never feel proud to put in production.

In a fast-paced industry we tend to forget that many of these problems have a established solution already. So just by doing a quick research on google, I came across the strategy pattern. I had implemented this pattern before but at first it did not come to my mind. However, seeing this was like the light at the end of a tunnel!

--

--

introdev.io
Javarevisited

I’m Daniel Sanchez, a software engineer sharing insights on Java, Go, and software development, helping others grow and solve problems through code.