代码之家  ›  专栏  ›  技术社区  ›  nicorellius

如何避免在代码中使用运行总计?

  •  1
  • nicorellius  · 技术社区  · 15 年前

    CaluculateDiscountPrice module
        DiscountPrice = (FloorPrice * (1 – DiscountRate))
    End module
    
    CalculateDeliveryPrice module
        If DeliveryFee = “Yes” Then
            DeliveryPrice = DiscountPrice + 20  
        ElseIf DeliveryFee = “No” Then
            DeliveryPrice = DiscountPrice
        End If
    End module
    
    CalculateTradeInCredit module
        If TradeInCredit = “Yes” Then
            CreditedPrice = DeliveryPrice – 5
        ElseIf TradeInCredit = “No” Then
            CreditedPrice = DeliveryPrice
        End If
    End module
    
    CaluculateCostOfBed module
        CostOfBed = CreditedPrice
    End module
    

    DiscountPrice 用于连接前两个模块,然后 DeliveryPrice 第二个。假设,最后一个模块可能根本不需要在那里,因为我解决了这个问题。对初学者有什么帮助吗?

    1 回复  |  直到 15 年前
        1
  •  1
  •   jtolle    15 年前

    当我看你的例子时,我突然想到的是 联轴器 模块之间(如果你还没有研究过这个概念,你可能很快就会知道了。)但是,太多的耦合和太少的内聚常常会结合在一起,所以希望我仍然可以给你一个有用的答案(过于简单,但在这里的定义是足够的:内聚模块做一个集中的事情,而不是几个不相关的事情,耦合模块依赖于彼此做任何事情。我们通常希望模块内部具有强内聚性,但与其他模块的耦合性较弱。)

    我从你的伪代码推断出你想这样计算床的价格:

    * start with the floor price
    * discount it
    * add in a delivery fee
    * subtract a trade-in credit
    * the result is the cost of the bed
    

    把送货费加到折扣价上 计算送货费 .

    包括任何折扣价格会让人困惑的东西。

    因此,考虑到所有这些,考虑这个替代设计:

    CalculateDeliveryFee module                                  
        If DeliveryFeeCharged = “Yes” Then                                  
            DeliveryFee = 20                                    
        End If                                  
    End module                                  
    
    CalculateTradeInCredit module                                  
        If TradeInCreditApplied = “Yes” Then                                  
            TradeInCredit = 5                                  
        End If                                  
    End module                                  
    
    CaluculateCostOfBed module 
        DiscountPrice = (FloorPrice * (1 – DiscountRate))  
        AsDeliveredPrice = DiscountPrice + DeliveryFee   
        WithTradeInPrice = AsDeliveredPrice - TradeInCredit                             
        CostOfBed = WithTradeInPrice 
    End module                                  
    

    现在,耦合减少了-交付和模块交易根本不知道床位价格。这也提高了他们的凝聚力,因为他们做的事情更专注于计算费用,而不是计算价格和费用的总和。实际的价格计算确实依赖于其他模块,但这是问题的内在原因。而且计算是有凝聚力的——它所做的“一件事”就是计算床的价格!

    推荐文章