javaoopsingle-responsibility-principle

How to comply the SRP when you want to execute several functions always together?


The single responsability principle (SRP) says the next:

A module should be responsible to one, and only one, actor

or

A class should have one and only one reason to change

by this, I understand that a function only should have one task to complete. But, what happens when I want to execute always two (ore more) functions one after another and I don't want to call one without the other?

I put an example:

I have these functions

void createProduct(){/*...*/};
void notifyUsers(){/*...*/};

And always I create a product I want to notify my users. So, should I create this function and call instead call both of them:

void createAndNotify(){
  createProduct();
  notifyUsers();
}

Or this violate the SRP and I should call both of theme every time like this?

  createProduct();
  notifyUsers();

Solution

  • Even if you always want to notify users when you create a product, the problem with having one class responsible for both is that you're tightly coupling the sending of notifications with the creation of products, which are separate concerns.

    Maybe in the future you'll want to change the manner in which notifications are sent, e.g. emails becoming push notifications. Your current design means that changing the notification code might break your product creation code. There is not enough isolation between them.

    One way to loosely couple this would be to have one class for creating products, e.g. ProductService, and one for performing notifications, e.g. NotificationService. The ProductService can publish an event (preferably to some sort of event bus) which the NotificationService listens for and reacts to.