SOLID in Rails - Interface Segregation Principle


Many client specific interfaces are better than one general purpose interface.

We want to show or create Fee. It's the same method but with additional options - save or not, so we pass params true or false
class FeeCalculator
def calculate(product, user, vat, save_result)
# calculation
if save_result
# storing result into db
end
end
end
class ProductController
def show
@fee = FeeCalculator.new.calculate(product, user, vat, false)
end
end
class OrderController
def create
@fee = FeeCalculator.new.calculate(product, user, vat, true)
end
end
view raw Solid-I01.rb hosted with ❤ by GitHub



But good way is divide this one action to different actions

class FeeCalculator
def calculate(product, user, vat)
# calculation
end
def save(fee)
# storing result into db
end
end
class OrderController
def create
fee = fee_calculator.calculate(product, user, vat)
fee_calculator.save(fee)
end
private
def fee_calculator
FeeCalculator.new
end
end
class ProductController
def show
@fee = FeeCalculator.new.calculate(product, user, vat)
end
end
view raw Solid-I02.rb hosted with ❤ by GitHub


Comments