为Java中的方法选择适当的名称

时间:2012-10-19 15:02:01

标签: java methods getter-setter

我对某些事情感到有些困惑,如果你们都能清楚地表达这一点,我会很感激。我有班级付款,有一些方法和getter / setter。 例如,我是否使用方法ItemCost返回属性itemCost的阀门,还是使用getter?

public class Payment {
    private int itemCost, totalCost;

    public int itemCost(int itemQuantity, int itemPrice){
        itemCost = itemPrice * itemQuantity;
        return itemCost;
    }

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

    public int getBalance(int clickValue, int totalCost){

        totalCost = totalCost - clickValue;
        return totalCost;
    }

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

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

    public int getItemcost(){
        return this.itemCost;
    }    

    public void setItemcost(int itemCost){
        this.itemCost = itemCost;
    }
} 

确定,而不是实例化:     另一个类中的int cost = payment.itemCost(quantity,itemPrice)

DO:payment.itemCost(quantity,itemPrice)     payment.getItemcost

编辑2:是否会使所有方法返回无效并且只是使用getter更好的编码?

public class Payment {
    private int itemCost, totalCost;

    public void calculateItemcost(int itemQuantity, int itemPrice){
        itemCost = itemPrice * itemQuantity;
    }

    public void calculateTotalCost(BigDecimal itemPrice){
        this.totalCost = totalCost + itemCost;
    }

    public void calculateBalance(int clickValue, int totalCost){
        this.totalCost = totalCost - clickValue;
    }

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

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

    public int getItemcost(){
        return this.itemCost;
    }    

    public void setItemcost(int itemCost){
        this.itemCost = itemCost;
    }
} 

3 个答案:

答案 0 :(得分:2)

getter / setters的目的是为对象中的特定属性设置值并从对象获取相同的内容,这样您就可以将属性定义为私有并强制执行封装(OO原则之一) )。

当您进行任何计算(或)业务逻辑时,最好使用适当的操作名称来获取/设置。

修改

正如neel评论的那样,它始终建议将POJO作为简单的bean而不是填充业务逻辑/计算。您可能有另一个具有业务逻辑的类,并使用get / setter在进行计算时从POJO获取值。

答案 1 :(得分:0)

通常,应该possible从方法名称中了解您的方法应该做什么。

因此,只有在您想要返回或设置班级属性时,才应使用getterssetters。这样,您的代码看起来更具可读性,the name的{​​{1}}清楚地说明它会做什么。

但是,如果你的方法没有返回确切的属性,而是返回一些计算的结果,那么你应该相应地命名你的方法。

对于E.g: - 如果您的方法返回methods作为类的某些属性的计算,则将该方法命名为cost。这更有意义。

PS : - 请记住,您的代码将比我创建时保留更长的时间。 calculateCost让其他人了解,而不是Code理解。

答案 2 :(得分:0)

目前您有两种方法可以设置itemCost

public void setItemcost(int itemCost){
    this.itemCost = itemCost;
}

public int itemCost(int itemQuantity, int itemPrice){
    itemCost = itemPrice * itemQuantity;
    return itemCost;
}

理想情况下,你会有一个设置方法,但是如果你希望这个类像这样工作,我会建议让这两个方法返回void并使用getItemCost来获取值。