0

Yesterday I was reviewing some Java code with a co-worker and we were discussing the Single Responsibility Principle. We refactored the code a bit and it complies very well to this principle.

Since I'm more of a front-end guy instead of backend I'm mostly writing JavaScript. Because of the SRP discussion I was looking at my code and found the following:

retrieveLabels : function() {
    getResultFromService(this, url, function(labelObject) {
        this.setLabels(labelObject)
    });
}

This function, to me, doesn't comply to SRP, it retrieves the labels (asynchroniously) and it stores this object in a variable. So basicly I want to return labelObject and pass the object to another function.

The problem here for me is the callback because it is asynchroniousl, how would one make this SRP compliant?

zwik
  • 89
  • 8
  • so you want to synchronously return the asynchronously retrieved `labelObject`? – Jaromanda X Oct 20 '16 at 08:06
  • This function has no problem with SRP; its responsibility is clearly defined and minimal. It's debatable whether the function name clearly describes what exactly it's doing, but that's about it. – deceze Oct 20 '16 at 08:06
  • `it retrieves the labels` -- no it doesn't. The function `getResultFromService` retrieves the labels. This function ONLY pass the return labels to `this.setLabels()` – slebetman Oct 20 '16 at 08:07
  • Note that if this was synchronous the code would be `this.setLabels(getResultFromService(url))` -- nobody would accuse the function of retrieving the label – slebetman Oct 20 '16 at 08:08
  • You can modify it to take a callback as parameter, like this. `this.retrieveLabels(this.setLabels);`. Or you can use Promises instead of callbacks – Telman Oct 20 '16 at 08:13

0 Answers0