如何在java中选择你的getter和setter

时间:2012-10-25 01:16:41

标签: java getter-setter

我的付款类只有一个本地私有变量 - totalCost,因此totalCost也有getter和setter方法。 TotalCost是唯一的局部变量,因为它是支付类中多个方法中唯一使用的变量。这堂课应该有更多的吸气者和制定者吗?

public class Payment {
    private int totalCost;

    public Payment(){
    }

    public int calculateItemcost(int itemQuantity, int itemPrice){
        return itemPrice * itemQuantity;

    public int calculateTotalcost(int itemCost){
        return totalCost = totalCost + itemCost;
    }


    public int calculateBalance(int clickedValue, int totalCost){
        return this.totalCost = totalCost - clickedValue;

    public int getTotalcost(){
        return this.totalCost;
    }    

    public void setTotalcost(int totalcost) {
        this.totalCost = totalcost;
    }
}     

4 个答案:

答案 0 :(得分:2)

您可以将getter用于您可能需要的字段" get"在其他课程中, 和你可能需要的字段的设置者"设置"在其他课程中。因此,在编写getter / setter之前,请考虑您的要求。

答案 1 :(得分:2)

因为你只有一个字段,你已经拥有了getter和setter。无关紧要。看起来很好。

虽然,重构这个:

    public int calculateTotalcost(int itemCost){
        return totalCost = totalCost + itemCost;
    }

    public int calculateBalance(int clickedValue, int totalCost){
        return this.totalCost = totalCost - clickedValue;
    }

致电二传手。例如:

public int calculateTotalcost(int itemCost){
       setTotalCost(totalCost + itemCost);
       return getTotalCost();
    }

这种方式对totalCost的更改已本地化为setTotalCost方法。

答案 2 :(得分:2)

我遵循的两条准则。

首先,不一定所有私有数据都应该通过getter和setter公开,因为其中一些可能仅供内部使用。

其次,getter和setter应该提供对象视图,而不是实现视图。

例如,如果您的班级对购买有10%的硬编码税率(现在忘记硬编码这是一个坏主意),您可以获得税务组件的吸气剂,即使它是计算值而不是私人会员。此外,您可能希望根据税前价格设置值。

所以,如果政府秃鹫的税前价值增加了​​10%,那就像:

public void setPreTax (int preTaxAmt) {
    totalCost = preTaxAmt * 11 / 10;
}
public int getTax (void) {
    return totalCost / 11;
}

我没有费心使用浮点计算,因为它与讨论无关,而你已经在使用int

此对象/实现拆分是一件好事 - 您应该根据要提供给客户的信息来设计API,而不是基于内部细节。

答案 3 :(得分:2)

您知道law of Demeter吗?

它收集了一些小指南,以避免代码中的松散耦合。

Getters和setter是导致类之间紧密耦合的元素。

为什么?

因为getter和setter会告诉你类的实现(特别是它的字段)及其设计。

总是系统地创建getter / setter的代码总是误解了面向对象编程的概念。

确实,这会导致anemic domain model

因此,它强制客户端自己实现业务逻辑,即使它不是它的角色。

简而言之:在一个应用程序中,80%的getter和setter是不必要的。 面向对象的编程是关于消息。你想要一个对象的行为,告诉它!不要询问有关其状态的信息,以便将您的厨房放在一边,因为这通常是一种程序化的编码方式。 (Tell ! Don't Ask !!)并赞成不尊重DRY(不要重复自己)。