0

According to the Single Responsibility Pattern (SRP) a method or class should have one responsibility. I have read a couple of sources and viewed some videos and I would like to understand it by writing some code samples.

According to me, the following:

def addAndSubtract(a,b,c)
  a + b - c
end

is conflicting with the SRP as this method has two responsibilities, i.e. addition and subtraction.

So how to align this with SRP? One responsibility per method right? Is the following correct?

def addAndSubtractSrp(a,b,c)
  subtract(add(a,b),c)
end

def add(a,b)
  a + b
end

def subtract(a,b)
  a - b
end

Discussion

According to me, this is aligned with SRP as there are now two methods that have one responsibility. When I would like to add multiplication and division then I need to create separate methods right?

5
  • 1
    I agree this is a dupe. Also, single responsibility could be a function ,(method) that calculates a complex algorithm. The point of SRP isn't to do a single operation, it's to manage change as the codebase evolves. – Paul Jan 13 '18 at 0:29
  • 1. SRP is a class principle. It has no meaning for methods. Methods have a different metric: only do one thing. Yours does two things. – Robert Harvey Jan 13 '18 at 1:02
  • 2. According to me, this is aligned with SRP as there are now two methods that have one responsibility. -- No. addAndSubtractSrp still does two things; it adds and subtracts. That you've refactored out the equation (and turned it into two methods, making the whole thing more complicated) doesn't change that fact. – Robert Harvey Jan 13 '18 at 1:04
  • 3. To fix your method so that it only does one thing, change its name to something like adjustBalance, or whatever that equation actually accomplishes. – Robert Harvey Jan 13 '18 at 1:05
  • 1
    At this point you should have asked yourself: Is the single responsibility principle total nonsense and something that should be avoided, or am I understanding it wrong? Because your code change is total nonsense. – gnasher729 Jan 13 '18 at 2:42