开发者

OOPs : Suggest design for the following scenario

开发者 https://www.devze.com 2023-03-13 14:53 出处:网络
I have a Product object. The Product is taxed at different rates in different places/situations. Some of the products are not taxable at all (Example : Medicine)

I have a Product object. The Product is taxed at different rates in different places/situations. Some of the products are not taxable at all (Example : Medicine)

For example , buying the product may cost $X in shop A and $Y at shop B . It can cost differently in two different states(state taxes are different).

My question is , can we have the attributes to determine the taxes inside the Product object itself.

For example is it a good idea to have attributes such as

                   Boolean isImporte开发者_如何学JAVAd ;
                   Boolean isTaxable ;

Or do we have a better design pattern to do this ?


First of all, I believe there is no single, good answer to this question.

You can have the attributes to determine the taxes inside a Product. However, I would recommend to have a separate class (TaxCalculator?) that would calculate the tax of a Product based on its origin, type, transaction, etc. The motivation is that the Product should represent a product data only; why should e.g. a bottle of wine care what are the taxes assigned to it? Something else should do it, something that is specialised in calculating the tax based on the product.

But that is only my opinion and I do not claim it is the best one. I would like to hear from some more experienced users.


Products need not to know about the tax. Tax is logically related to a sale, so is the product price. In our app we have the following (simplified):

public class Invoice {
    private InvoiceItem[] invoiceItems;
}

public class InvoiceItem{
    private ProductPrice productPrice;
    private BigDecimal taxRate;
}

public class ProductPrice{
    private Product product;
    private BigDecimal price;
    private String currencyCode;
}

public class Product{
    ....
}


You can certainly put those attributes in the Product class.

Or you can create a separate interface (TaxStrategy?) that would take a Product and return a Money tax amount:

public interface TaxStrategy {
    Money calculateTax(Product p);
}

That way you can have different implementations of the interface that compute taxes in different ways. Products need not know that they're taxable. It separates the thing that you sell from the way that you price it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号