【发布时间】:2012-05-05 02:37:42
【问题描述】:
使用private field 和private methods 的更好方法是什么?
当从公共方法调用私有方法时,在私有方法中使用私有字段是优雅还是将它们作为参数更好?
字段:
private Item model;
1. 公共方法:
...
if (model.getPrice() != null) {
String formattedPrice = formatPrice();
}
...
私有方法:
private int formatPrice(){
int price = model.getPrice() + 10;
}
VS
2. 公共方法:
if (model.getPrice() != null) {
String formattedPrice = formatPrice(model.getPrice());
}
...
私有方法:
formatPrice(int price){
int price = price + 10;
}
【问题讨论】:
-
如果你的
modifyPrice()方法应该只在这个类中使用(这似乎是因为private可见性),我更喜欢第一个答案。 -
谢谢建议,我也先用,但犹豫了
-
@sergionni 所以不要犹豫 ;)
-
好的,我明白了,谢谢)
标签: java methods call field private