ROR中的单一原则

class Invocie
    def initialize(customer:, state:, total:)
        @customer = customer
        @state = state
        @total = total
    end

    def detials
        "Customer: #{@customer}, Total: #{@total}"
    end

    def sales_tax
        case @state 
        when "AZ" then 5.5
        when "TX" then 3.2
        when "CA" then 8.7
        end
    end

    def email_invoice
        puts "Email invoice ..."
        puts detials
    end

end

发票类的使用

为什么SRP很重要?(Single Responsibility Principle)

为什么这种类型的OOP设计模式很重要? 我们最初的 Invoice 类的发票代码工作得很好,那么我们为什么要更改它? 假设这个程序是由一个真实的会计部门使用的。如果用户想知道某个州的税率是多少,该怎么办? 系统要求用户创建一个发票来计算该值是没有意义的。

我们在本节中所做的重构程序,可以使SalesTax类独立使用,也可以由任何其他可能需要该特性的类使用。在计算机科学领域,这个概念称为耦合。在我们最初的代码示例中,销售税方法与Invoice类高度耦合。这意味着如果我们处理税率,而不需要Invoice类,那么生成税率将会很麻烦 我们的重构解决了这个问题,现在我们可以说税率属性具有低耦合。这意味着用户可以访问税率组件,而不必使用其他类。重新设计方法如下:

发票类

class Invocie
    def initialize(customer:, state:, total:)
        @customer = customer
        @state = state
        @total = total
    end

    def detials
        "Customer: #{@customer}, Total: #{@total}"
    end

end

SaleTax类

class SalesTax
    def initialize(state:)
        @state = state
    end

    def sales_tax
        case @state 
        when "AZ" then 5.5
        when "TX" then 3.2
        when "CA" then 8.7
        end
    end

end

Mail 类

class Mailer
    #类函数的应用
    def self.send_email(content)
        puts "Emailing ..."
        puts content 
    end
end

类的调用

invoice = Invocie.new(customer:"Baidu", state: "AZ", total: 100)
tax = SalesTax.new(state: "AZ")
puts tax.sales_tax
Mailer.send_email(invoice.detials)

你可能感兴趣的:(ROR中的单一原则)