vendredi 18 décembre 2015

I need help refactoring code to conform to the Single Responsibility principle

I'm currently trying to understand the SOLID principles by reading the book called Practical Object Oriented Design in Ruby. The first principle is the single responsibility, the way I understand this concept is that a class/method should only have one responsibility or reason to change.

In the code below I have a Calculate class which is responsible for (4) four different operations, add,subtract,multiply and divide, which to me doesn't conform to the Single Responsibility theory.

Can someone be so kind and refactor the following class in a way that it adheres to the Single Responsibility?

I know this could be a very opinionated topic but I really need to understand this concept better.

FYI - For simplicity I'm using Ints only, which I know it is not ideal for divisions and subtractions.

class Calculate{

    let num1:Int
    let num2:Int

    init(firstNum:Int, secondNum:Int){
        num1 = firstNum
        num2 = secondNum
    }

    func add()->Int{

        let total = num1 + num2

        return total
    }

    func subtract()->Int{

        let total = num1 - num2

        return total
    }

    func multiply()->Int{

        let total = num1 + num2

        return total
    }

    func divide()->Int{

        let total = num1 / num2

        return total
    }

}


let operation = Calculate(firstNum:5 , secondNum:5)
print(operation.divide())

Aucun commentaire:

Enregistrer un commentaire