I need to refactor a class that became too messy. The class has a method that reads some raw data from one of our repositories, and another that "filters" it:
The data is in the form of level
and on/off
, for each X*Y of the units we have.
The filtering process lets some of the data pass in the raw form, changes a small amount from on to off, or reduces the level, and some is just blocked in this stage.
And this stage there a already quite a lot of rules, but none of them is general enough to apply to all units, so we have a lot of if/else
statements that are hard to follow and can cause bugs.
I'd be happy to redesign it in a more readable and easier-to-maintain form.
I can't provide a code snippet, but a pseudo code will look like this:
for x in X:
for y in Y:
if data[x] == ...
if data[x][y] == ...
copy as is
else if
manipulate data and copy
else
disable this data
else if data[x] == ...
Is there a known design pattern for this scenario? I was looking at the filter pattern but I don't know if my criteria are unified enough
for each item{ ruleA(item); ruleB(item) }
. Sometimes it can be helpful to flip this around, with each rule or filter handling all items and potentially forwarding or disabling items for the next rule:items = ruleA(items); items = ruleB(items)
. This could make it easier to test rules in isolation and could make it possible to write individual rules more efficiently, though different rules might then have to duplicate some work. In particular, as CandiedOrange points out in an answer, some rules might not have to iterate over the entire X × Y cartesian product.