Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中选择getter和setter_Java_Getter Setter - Fatal编程技术网

如何在java中选择getter和setter

如何在java中选择getter和setter,java,getter-setter,Java,Getter Setter,我的payment类只有一个局部私有变量——totalCost,因为totalCost也有一个getter和setter方法。TotalCost是唯一的局部变量,因为它是payment类中多个方法中使用的唯一一个局部变量。这个类应该有更多的getter和setter吗 public class Payment { private int totalCost; public Payment(){ } public int calculateItemcost(in

我的payment类只有一个局部私有变量——totalCost,因为totalCost也有一个getter和setter方法。TotalCost是唯一的局部变量,因为它是payment类中多个方法中使用的唯一一个局部变量。这个类应该有更多的getter和setter吗

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;
    }
}     

对于可能需要在其他类中“获取”的字段,可以使用getter,
以及可能需要在其他类中“设置”的字段的setter。因此,在编写getter/setter之前,请考虑您的需求。

因为您只有一个字段,而您已经有了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
方法。

我遵循两条准则

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

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

例如,如果您的类对购买有硬编码的10%税率(现在忘记硬编码这是一个坏主意),那么您可能会有一个税收组件的getter,即使它是一个计算值而不是一个私有成员。此外,您可能希望根据税前价格设置值

因此,如果政府秃鹫的税前价值增加了10%,比如:

public void setPreTax (int preTaxAmt) {
    totalCost = preTaxAmt * 11 / 10;
}
public int getTax (void) {
    return totalCost / 11;
}
我没有费心使用浮点进行计算,因为它与讨论无关,而且您已经在使用
int

这种对象/实现分离是一件好事——您应该根据希望提供给它的客户端的信息来设计API,而不是基于内部细节。

您知道其中的细节吗

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

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

为什么?

因为getter和setter通知您类的实现(尤其是它的字段)及其设计

总是通过创建getter/setter系统地编写代码的开发人员完全误解了面向对象编程的概念

事实上,这导致了一场灾难

因此,它迫使客户机自己实现业务逻辑,即使它不是它的角色

简而言之:在应用程序中,80%的getter和setter是不必要的。 面向对象编程是关于消息的。你想要一个物体的行为,告诉它!不要为了把厨房放在一边而询问它的状态信息,因为这通常是一种程序化的编码方式。 (!)并支持对DRY的不尊重(不要重复你自己)