Stan
Stan

Reputation: 38255

Strategy Pattern with strategies contains similar code

In most examples, strategy pattern is usually good for compression algorithms/ codec algorithms, where these algorithm might have quite different code.

However, in my case, the statistics algorithms I want to refactor to strategy pattern, have 50% code similar or exactly the same. I was wondering how do people deal with this? If I use strategy pattern, there could be 50% of the code copied around, which is not desired. If not refactor, the code is ended up with many sets of if-else all around to handle different types of statistics algorithms. How to evaluate the trade-off? What could be other possible solutions?

Upvotes: 2

Views: 1592

Answers (2)

ntohl
ntohl

Reputation: 2125

You may use Template Method if it is easier, but also there is a big possibility, that with inheritance, You can derive Your concrete strategies from a common base class containing most of the common code.

Upvotes: 6

NamshubWriter
NamshubWriter

Reputation: 24286

The end goal is not to reduce as much code duplication as possible. The goal is to make the code maintainable. You need to ask yourself if reducing this duplication would make the strategy implementations easier or harder to maintain.

If reducing the duplication makes the code harder to maintain, then keep the duplication, but possibly find another way to mitigate the concern (documentation and tests are two possible ways).

If reducing the duplication would make the code easier to maintain, then think of the possible ways of removing duplication (delegation, like with Strategy and Decorator; inheritance, like with Template Method, etc).

Upvotes: 7

Related Questions