5

I've just read the book called Clean Code. The author (Robert C. Martin) talks about a single responsibility that a function should have in a program. It should only do one thing.

Now, I would like to understand how is it now possible to reuse a code that does multiple things. Let's say I have a method called runTrafficAndCheckIfItPassed and it calls two methods inside of it: runTraffic and checkIfTrafficPassed.

Now let's say that in my software I need to run traffic and to check it's result in a lot of places in my software. sometimes I need to check that traffic has failed, and sometimes I need to check if it passed.

Why wouldn't it be right to call the runTrafficAndCheckIfItPassed function and why is it way better to call the functions inside separately?

As far as I see, if there will be a change in the runTraffic function, for example to receive another parameter, the change will be implemented in one place, only in runTrafficAndCheckIfItPassed, which we see will be easy to maintain. But if I will use the functions separately I will need to change it in any place. But the author says it's wrong. So do you have any examples or tips why it is considered wrong?

Here's how I used it:

runTrafficAndCheckIfItPassed(TCPTraffic):
   trafficResults=runTraffic(TCPTraffic)
   hasAllTrafficPassed=checkIfTrafficPassed(trafficResults)
   return hasAllTrafficPassed
Glorfindel
  • 3,167
Azuk
  • 59

2 Answers2

16

Though the name gives a different impression, the function runTrafficAndCheckIfItPassed does only "one thing" in the "clean code sense": it coordinates the calls to two other functions.

The operational code for those two actions included, however, is in runTraffic and checkIfTrafficPassed, which are two functions for which we can assume they "do one thing" as well, but on a lower level of abstraction.

To apply the "do one thing" metapher correctly, one needs to take different levels of abstraction into account. Things which may be seen as one operation on a higher level usually consist of lots of single commands, actions and steps on a lower level.

To make the different levels of abstraction more transparent, it is often a good a idea to give a function like runTrafficAndCheckIfItPassed a different name, one which summarizes the combined actions under one concise term. If you cannot come up with such a name, then alas, let the name as it is now, naming things is one of the toughest tasks in software development ;-)

You find a good example in this older SE post.

Doc Brown
  • 218,378
4

Generally, anything with "and" in the name leaves a suspicion that it's violating the SRP. However, that sort of function could be renamed to something like "tryRunTraffic", with little change in meaning.

Functions named "try..." are often used to indicate that they will return a success or failure code, rather than throwing an exception if they fail. This is useful if failure is not an error.

Simon B
  • 9,772