Only perform action for specific sub classes of objects

Viewed 22

How can I apply an action only for specific sub classes of objects in an object oriented way in Java based on the SOLID principles?

Eg, currently I would do something like this:

public void WorkerMethod(Result result) {
   // processing code
   // ...
   // finish processing code, now save

   if (result instanceof ModelResult || result instanceof DataResult || ...) 
      databaseClient.saveStringData(GetDataToSave(result));
   else ; // I don't want to save these objects
}

I thought one way of doing it would be to extend my Result class and add a "shouldSave()" method which returns false by default. Then override it for subclasses I want to save, but this doesn't feel right / feels hacky / code smell.

What is the correct OOP way to do this?

0 Answers
Related