Search code examples
coding-stylesingle-responsibility-principle

Single responsibility principle - function


I'm reading some tuts about SOLID programming, and I'm trying to refactor my test project to implement some of those rules.

Often I have doubts with SingleResponsibilityPrinciple, so I hope someone could help me with that.

As I understood, SRP means that (in case of a function), function should be responsible for only one thing. And that's seems pretty easy and simple, but I do get in a trap of doing more than thing.

This is simplified example:

class TicketService {

    private ticket;

    getTicket() {

        httpClient.get().then(function(response) {
            ticket = response.ticket;
            emit(ticket);  <----------------------
        });
    }

}

The confusing part is emit(ticket). So, my function is named getTicket, that's exactly what I'm doing there (fetching it from server e.g.), but on the other hand, I need to emit that change to all other parts of my application, and let them know that ticket is changed.

I could create separate set() function, where I could do setting of private variable, and emit it there, but that seems like a same thing.

Is this wrong? Does it break the rule? How would you fix it?


Solution

  • This can lead to unexpected behavior. If I want to re-use your class in the future and I see with auto-completion in my IDE the method getTicket() I expect to get a Ticket.

    However renaming this method to mailChangedTicket, ideally you want this method to call the getTicket method (which actually returns the ticket) and this way you have re-usable code which will make more sense.

    You can take SRP really far, for example your TicketService has a httpClient, but it probably doesn't matter where the ticket comes from. In order to 'fix' this, you will have to create a seperate interface and class for this.

    A few advantages:

    • Code is becoming more re-usable
    • It is easier to test parts separately

    I can recommend the book 'Clean Code' from Robert C. Martin which gives some good guidelines to achieve this.