Reputation: 13530
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;
}
Upvotes: 0
Views: 621
Reputation: 719606
Here are the pro's and con's that I can identify:
This version ...
private int formatPrice() {
// format model.getPrice()
}
... potentially avoids the "problem" of formatting the wrong thing as a price, and potentially saves a few characters if you call it in lots of places.
This version ...
private int formatPrice(int price) {
// format price
}
... can be used to format prices coming from different sources (rather than just from model.getPrice()
), but the calls are a bit more wordy, and there is nothing to stop you to formating some integer that does not represent a price.
However, in my opinion, there's not much difference between the two approaches. Certainly, not enough difference for one or the other be clearly a "better way" in general.
Upvotes: 1
Reputation: 6411
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?
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 model
is and how its getPrice
method works.
Upvotes: 2
Reputation: 22948
You should use private methods when you don't want them to be seen outside of the class you're implementing. So if one would create an instance of that class, that private method would be inaccessible than.
As for private fields, same logic. Well nothing is really private in Java anyways, you can get to it by using reflection anyways..
Upvotes: 0