简体   繁体   中英

Private fields inside private methods VS pass them from public methods

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;
}

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.

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.

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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM