0

How do I make my "complex" Strategy class fulfill Single Responsibility Principal? Is there any other pattern that I can apply instead?

I thought about Decorator pattern that can add more responsibility/operations to my "algorithm", but it does not seem to fit.

See this SimpleStrategy class. It gets cached and latest records, compares them and updates if required, and then performs any post processing.

class SimpleStrategy {
    private DbRecordFetcher dbRecordFetcher;
    private LatestRecordFetcher latestRecordFetcher;
    private RecordComparator recordComparator;
    private DataUpdater dataUpdater;
    private PostProcessor postProcessor;

    public void process(Input input) {
        I cached = dbRecordFetcher.fetch(input);
        I latest = latestRecordFetcher.fetch(input);

        boolean isChanged = recordComparator.compare(cached, latest);

        if (isChanged) {
            dataUpdater.update(input, latest);
        }

        postProcessor.process(input, latest);
    }
}

All the classes that SimpleStrategy is composed off are interfaces, so I can inject different implementations, for example, to fetch db and latest records.

How do I refactor it to make it follow SRP?

rajan
  • 157
  • 1
  • 2
  • 10
  • 1
    At _some_ point you have to do things like this and you can't get around it. You can only have so many low level building blocks before you have to start composing things. I'm not saying you have reached that point here (though maybe you have), but it's not uncommon for me to have classes that act like glue between a bunch of interfaces and only do that job, which is not uncommon to what you've written above. If the class has a single method that has effectively 6 lines of code, that seems pretty minimal to me. – Water Sep 02 '19 at 23:58
  • Thank you @Water for your response. This is my understanding as well, so I'm checking with community if there are alternatives before I consider it as necessary. – rajan Sep 03 '19 at 00:06
  • Why do you think this code violates the [SRP](https://stackoverflow.com/tags/single-responsibility-principle/info)? – jaco0646 Sep 03 '19 at 00:57
  • My understanding was one method or class doing just one thing and doing it right. After reading through more details on the the link you gave, it seems my issue is about separation-of-concerns instead. – rajan Sep 04 '19 at 02:06
  • https://stackoverflow.com/questions/46541197/does-the-single-responsibility-principle-work-in-oop/46556381#46556381 – Matt Timmermans Sep 04 '19 at 19:33
  • [What is the scope of the Single Responsibility Principle?](https://stackoverflow.com/a/57085753/1371329) – jaco0646 Sep 22 '19 at 13:21

0 Answers0