What is the better way to work with private field and private methods?
Is it graceful to use private field inside private methods or it’s better to put them as parameters,when call private method from public method?
field:
private Item model;
1.
public method:
...
if (model.getPrice() != null) {
String formattedPrice = formatPrice();
}
...
private method:
private int formatPrice(){
int price = model.getPrice() + 10;
}
VS
2.
public method:
if (model.getPrice() != null) {
String formattedPrice = formatPrice(model.getPrice());
}
...
private method:
formatPrice(int price){
int price = price + 10;
}
I think this is highly subjective and depends on your preference, and also on the particular case.
In general, both approaches seem valid to me. There’s no problem accessing a private member from a private method, and there’s no problem passing it as a parameter.
Regarding the specific example, I slightly prefer the 2nd implementation. The private method is self-contained there – it doesn’t depend on anything other than its parameters. This makes it easier to read, test, and reuse. You can reason about the method and argue about its correctness without needing to know what
modelis and how itsgetPricemethod works.