我对某些事情有点困惑,如果大家都能对此有所澄清,我将不胜感激。我有一个班级支付有一些方法和getter/setter。 例如,我是否使用ItemCost方法返回属性itemCost的阀门,还是使用getter?在Java中为方法选择合适的名称
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;
}
}
确定,所以代替实例:在另一类
DO INT成本= payment.itemCost(数量,ITEMPRICE):payment.itemCost(数量,ITEMPRICE) payment.getItemcost
?
编辑2:会使所有的方法返回无效,只是使用getters更好的编码?
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;
}
}
这些方法签名(名称+参数类型+返回类型)都很差。例如,'itemCost(itemQuantity,itemPrice)'的签名根本没有说明它修改了'itemCost'。而'totalCost'甚至没有使用它的论点! – ruakh
@Adesh。是的,这将是一个比较好的方法..但是你应该把你的业务逻辑部分从这个类中移出来。然后从其他地方计算你的itemCost和totalCost,并调用'setters'来设置这个类的值。 –